From d6b7d72a116aa4b4dba5bddbd70bea5abc9b5a25 Mon Sep 17 00:00:00 2001 From: Adam Turner <9087854+aa-turner@users.noreply.github.com> Date: Fri, 28 Feb 2025 02:13:54 +0000 Subject: [PATCH 1/7] Support single-subject attestations --- README.md | 3 + __tests__/main.test.ts | 1 + action.yml | 7 + dist/index.js | 75961 ++++++++++++++++++++------------------- src/attest.ts | 19 +- src/index.ts | 3 + src/main.ts | 97 +- src/subject.ts | 1 + 8 files changed, 38102 insertions(+), 37990 deletions(-) diff --git a/README.md b/README.md index 5849c6a0c..233a99308 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,8 @@ Attestations are saved in the JSON-serialized [Sigstore bundle][6] format. If multiple subjects are being attested at the same time, a single attestation will be created with references to each of the supplied subjects. +If `single-subject-attestations` is true, each attestation will be written +to the output file on a separate line (using the [JSON Lines][7] format). ## Attestation Limits @@ -320,6 +322,7 @@ jobs: [5]: https://cli.github.com/manual/gh_attestation_verify [6]: https://github.com/sigstore/protobuf-specs/blob/main/protos/sigstore_bundle.proto +[7]: https://jsonlines.org/ [8]: https://github.com/actions/toolkit/tree/main/packages/glob#patterns [9]: https://docs.github.com/en/actions/security-guides/using-artifact-attestations-to-establish-provenance-for-builds diff --git a/__tests__/main.test.ts b/__tests__/main.test.ts index 7e114d499..faff523de 100644 --- a/__tests__/main.test.ts +++ b/__tests__/main.test.ts @@ -47,6 +47,7 @@ const defaultInputs: main.RunInputs = { pushToRegistry: false, showSummary: true, githubToken: '', + singleSubjectAttestations: false, privateSigning: false } diff --git a/action.yml b/action.yml index bc45f792d..0ccd203a9 100644 --- a/action.yml +++ b/action.yml @@ -64,6 +64,13 @@ inputs: The GitHub token used to make authenticated API requests. default: ${{ github.token }} required: false + single-subject-attestations: + description: > + If true, generate one attestation per subject, + otherwise generate a single attestations with multiple subjects. + Defaults to false. + default: false + required: false outputs: bundle-path: description: 'The path to the file containing the attestation bundle.' diff --git a/dist/index.js b/dist/index.js index bf50d285b..96188759f 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5487,7 +5487,7 @@ module.exports = class Agent extends AgentBase { "use strict"; -const { LRUCache } = __nccwpck_require__(32638) +const { LRUCache } = __nccwpck_require__(32477) const dns = __nccwpck_require__(72250) // this is a factory so that each request can have its own opts (i.e. ttl) @@ -5617,7 +5617,7 @@ module.exports = { "use strict"; -const { LRUCache } = __nccwpck_require__(32638) +const { LRUCache } = __nccwpck_require__(32477) const { normalizeOptions, cacheOptions } = __nccwpck_require__(46329) const { getProxy, proxyCache } = __nccwpck_require__(3799) const dns = __nccwpck_require__(42604) @@ -5778,7 +5778,7 @@ module.exports = { const { HttpProxyAgent } = __nccwpck_require__(81970) const { HttpsProxyAgent } = __nccwpck_require__(3669) const { SocksProxyAgent } = __nccwpck_require__(53357) -const { LRUCache } = __nccwpck_require__(32638) +const { LRUCache } = __nccwpck_require__(32477) const { InvalidProxyProtocolError } = __nccwpck_require__(60260) const PROXY_CACHE = new LRUCache({ max: 20 }) @@ -5895,7 +5895,7 @@ module.exports = getOptions /***/ 6187: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const semver = __nccwpck_require__(62088) +const semver = __nccwpck_require__(41437) const satisfies = (range) => { return semver.satisfies(process.version, range, { includePrerelease: true }) @@ -6689,38040 +6689,37802 @@ module.exports = withTempDir /***/ }), -/***/ 77864: -/***/ ((module) => { - -"use strict"; +/***/ 39768: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - createTokenAuth: () => createTokenAuth -}); -module.exports = __toCommonJS(dist_src_exports); + constructor (comp, options) { + options = parseOptions(options) -// pkg/dist-src/auth.js -var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; -var REGEX_IS_INSTALLATION = /^ghs_/; -var REGEX_IS_USER_TO_SERVER = /^ghu_/; -async function auth(token) { - const isApp = token.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } -// pkg/dist-src/with-authorization-prefix.js -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) -// pkg/dist-src/hook.js -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } -// pkg/dist-src/index.js -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); + debug('comp', this) } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) -/***/ }), + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } -/***/ 61897: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } -"use strict"; + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + toString () { + return this.value } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(dist_src_exports); -var import_universal_user_agent = __nccwpck_require__(33843); -var import_before_after_hook = __nccwpck_require__(52732); -var import_request = __nccwpck_require__(66255); -var import_graphql = __nccwpck_require__(70007); -var import_auth_token = __nccwpck_require__(77864); + test (version) { + debug('Comparator.test', version, this.options.loose) -// pkg/dist-src/version.js -var VERSION = "5.1.0"; + if (this.semver === ANY || version === ANY) { + return true + } -// pkg/dist-src/index.js -var noop = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var Octokit = class { - static { - this.VERSION = VERSION; - } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false } - }; - return OctokitWithDefaults; - } - static { - this.plugins = []; + } + + return cmp(version, this.operator, this.semver, this.options) } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static { - this.plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true } - }; - return NewOctokit; - } - constructor(options = {}) { - const hook = new import_before_after_hook.Collection(); - const requestDefaults = { - baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; + return new Range(this.value, options).test(comp.semver) } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false } - this.request = import_request.request.defaults(requestDefaults); - this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); - this.log = Object.assign( - { - debug: noop, - info: noop, - warn: consoleWarn, - error: consoleError - }, - options.log - ); - this.hook = hook; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth = (0, import_auth_token.createTokenAuth)(options.auth); - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook.wrap("request", auth.hook); - this.auth = auth; + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +} + +module.exports = Comparator + +const parseOptions = __nccwpck_require__(65939) +const { safeRe: re, t } = __nccwpck_require__(84894) +const cmp = __nccwpck_require__(23991) +const debug = __nccwpck_require__(86912) +const SemVer = __nccwpck_require__(95548) +const Range = __nccwpck_require__(60031) /***/ }), -/***/ 54471: +/***/ 60031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +const SPACE_CHARACTERS = /\s+/g -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - endpoint: () => endpoint -}); -module.exports = __toCommonJS(dist_src_exports); +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) -// pkg/dist-src/defaults.js -var import_universal_user_agent = __nccwpck_require__(33843); + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } -// pkg/dist-src/version.js -var VERSION = "9.0.4"; + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } -// pkg/dist-src/defaults.js -var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -// pkg/dist-src/util/lowercase-keys.js -function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') -// pkg/dist-src/util/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - if (Object.prototype.toString.call(value) !== "[object Object]") - return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) - return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) -// pkg/dist-src/util/merge-deep.js -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject(options[key])) { - if (!(key in defaults)) - Object.assign(result, { [key]: options[key] }); - else - result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) } - }); - return result; -} -// pkg/dist-src/util/remove-undefined-properties.js -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } } - } - return obj; -} -// pkg/dist-src/merge.js -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); - } else { - options = Object.assign({}, route); + this.formatted = undefined } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + return this.formatted } - return mergedOptions; -} -// pkg/dist-src/util/add-query-parameters.js -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; + format () { + return this.range } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} -// pkg/dist-src/util/extract-url-variable-names.js -var urlVariableRegex = /\{[^}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - if (!matches) { - return []; + toString () { + return this.range } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} -// pkg/dist-src/util/omit.js -function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached } - } - return result; -} -// pkg/dist-src/util/url-template.js -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value = context[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] } + rangeMap.set(comp.value, comp) } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} -// pkg/dist-src/parse.js -function parse(options) { - let method = options.method.toUpperCase(); - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format) => format.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false } } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } } + return false } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} - -// pkg/dist-src/endpoint-with-defaults.js -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); } -// pkg/dist-src/with-defaults.js -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); -} +module.exports = Range -// pkg/dist-src/index.js -var endpoint = withDefaults(null, DEFAULTS); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +const LRU = __nccwpck_require__(35986) +const cache = new LRU() +const parseOptions = __nccwpck_require__(65939) +const Comparator = __nccwpck_require__(39768) +const debug = __nccwpck_require__(86912) +const SemVer = __nccwpck_require__(95548) +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __nccwpck_require__(84894) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(83074) -/***/ }), +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' -/***/ 70007: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() -"use strict"; + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + testComparator = remainingComparators.pop() } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest -}); -module.exports = __toCommonJS(dist_src_exports); -var import_request3 = __nccwpck_require__(66255); -var import_universal_user_agent = __nccwpck_require__(33843); -// pkg/dist-src/version.js -var VERSION = "7.0.2"; + return result +} -// pkg/dist-src/with-defaults.js -var import_request2 = __nccwpck_require__(66255); +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} -// pkg/dist-src/graphql.js -var import_request = __nccwpck_require__(66255); +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' -// pkg/dist-src/error.js -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') } -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } -}; -// pkg/dist-src/graphql.js -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) - continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); - } - } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); -} +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret -// pkg/dist-src/with-defaults.js -function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) } -// pkg/dist-src/index.js -var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') } -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret -/***/ }), + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } -/***/ 38082: -/***/ ((module) => { + debug('caret return', ret) + return ret + }) +} -"use strict"; +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - composePaginateRest: () => composePaginateRest, - isPaginatingEndpoint: () => isPaginatingEndpoint, - paginateRest: () => paginateRest, - paginatingEndpoints: () => paginatingEndpoints -}); -module.exports = __toCommonJS(dist_src_exports); + if (gtlt === '=' && anyX) { + gtlt = '' + } -// pkg/dist-src/version.js -var VERSION = "9.2.2"; + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' -// pkg/dist-src/normalize-paginated-list-response.js -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) - return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` } - response.data.total_count = totalCount; - return response; + + return `${from} ${to}`.trim() } -// pkg/dist-src/iterator.js -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) - return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - return { value: normalizedResponse }; - } catch (error) { - if (error.status !== 409) - throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true } } - }) - }; -} + } -// pkg/dist-src/paginate.js -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; + // Version has a -pre, but it's not one of the ones we like. + return false } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); + + return true } -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; + + +/***/ }), + +/***/ 95548: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const debug = __nccwpck_require__(86912) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(83074) +const { safeRe: re, safeSrc: src, t } = __nccwpck_require__(84894) + +const parseOptions = __nccwpck_require__(65939) +const { compareIdentifiers } = __nccwpck_require__(98219) +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } - let earlyExit = false; - function done() { - earlyExit = true; + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) } - return gather(octokit, results, iterator2, mapFn); - }); -} -// pkg/dist-src/compose-paginate.js -var composePaginateRest = Object.assign(paginate, { - iterator -}); + this.raw = version -// pkg/dist-src/generated/paginating-endpoints.js -var paginatingEndpoints = [ - "GET /advisories", - "GET /app/hook/deliveries", - "GET /app/installation-requests", - "GET /app/installations", - "GET /assignments/{assignment_id}/accepted_assignments", - "GET /classrooms", - "GET /classrooms/{classroom_id}/assignments", - "GET /enterprises/{enterprise}/dependabot/alerts", - "GET /enterprises/{enterprise}/secret-scanning/alerts", - "GET /events", - "GET /gists", - "GET /gists/public", - "GET /gists/starred", - "GET /gists/{gist_id}/comments", - "GET /gists/{gist_id}/commits", - "GET /gists/{gist_id}/forks", - "GET /installation/repositories", - "GET /issues", - "GET /licenses", - "GET /marketplace_listing/plans", - "GET /marketplace_listing/plans/{plan_id}/accounts", - "GET /marketplace_listing/stubbed/plans", - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", - "GET /networks/{owner}/{repo}/events", - "GET /notifications", - "GET /organizations", - "GET /orgs/{org}/actions/cache/usage-by-repository", - "GET /orgs/{org}/actions/permissions/repositories", - "GET /orgs/{org}/actions/runners", - "GET /orgs/{org}/actions/secrets", - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", - "GET /orgs/{org}/actions/variables", - "GET /orgs/{org}/actions/variables/{name}/repositories", - "GET /orgs/{org}/blocks", - "GET /orgs/{org}/code-scanning/alerts", - "GET /orgs/{org}/codespaces", - "GET /orgs/{org}/codespaces/secrets", - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", - "GET /orgs/{org}/copilot/billing/seats", - "GET /orgs/{org}/dependabot/alerts", - "GET /orgs/{org}/dependabot/secrets", - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", - "GET /orgs/{org}/events", - "GET /orgs/{org}/failed_invitations", - "GET /orgs/{org}/hooks", - "GET /orgs/{org}/hooks/{hook_id}/deliveries", - "GET /orgs/{org}/installations", - "GET /orgs/{org}/invitations", - "GET /orgs/{org}/invitations/{invitation_id}/teams", - "GET /orgs/{org}/issues", - "GET /orgs/{org}/members", - "GET /orgs/{org}/members/{username}/codespaces", - "GET /orgs/{org}/migrations", - "GET /orgs/{org}/migrations/{migration_id}/repositories", - "GET /orgs/{org}/organization-roles/{role_id}/teams", - "GET /orgs/{org}/organization-roles/{role_id}/users", - "GET /orgs/{org}/outside_collaborators", - "GET /orgs/{org}/packages", - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - "GET /orgs/{org}/personal-access-token-requests", - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", - "GET /orgs/{org}/personal-access-tokens", - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", - "GET /orgs/{org}/projects", - "GET /orgs/{org}/properties/values", - "GET /orgs/{org}/public_members", - "GET /orgs/{org}/repos", - "GET /orgs/{org}/rulesets", - "GET /orgs/{org}/rulesets/rule-suites", - "GET /orgs/{org}/secret-scanning/alerts", - "GET /orgs/{org}/security-advisories", - "GET /orgs/{org}/teams", - "GET /orgs/{org}/teams/{team_slug}/discussions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/invitations", - "GET /orgs/{org}/teams/{team_slug}/members", - "GET /orgs/{org}/teams/{team_slug}/projects", - "GET /orgs/{org}/teams/{team_slug}/repos", - "GET /orgs/{org}/teams/{team_slug}/teams", - "GET /projects/columns/{column_id}/cards", - "GET /projects/{project_id}/collaborators", - "GET /projects/{project_id}/columns", - "GET /repos/{owner}/{repo}/actions/artifacts", - "GET /repos/{owner}/{repo}/actions/caches", - "GET /repos/{owner}/{repo}/actions/organization-secrets", - "GET /repos/{owner}/{repo}/actions/organization-variables", - "GET /repos/{owner}/{repo}/actions/runners", - "GET /repos/{owner}/{repo}/actions/runs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", - "GET /repos/{owner}/{repo}/actions/secrets", - "GET /repos/{owner}/{repo}/actions/variables", - "GET /repos/{owner}/{repo}/actions/workflows", - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", - "GET /repos/{owner}/{repo}/activity", - "GET /repos/{owner}/{repo}/assignees", - "GET /repos/{owner}/{repo}/branches", - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", - "GET /repos/{owner}/{repo}/code-scanning/alerts", - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - "GET /repos/{owner}/{repo}/code-scanning/analyses", - "GET /repos/{owner}/{repo}/codespaces", - "GET /repos/{owner}/{repo}/codespaces/devcontainers", - "GET /repos/{owner}/{repo}/codespaces/secrets", - "GET /repos/{owner}/{repo}/collaborators", - "GET /repos/{owner}/{repo}/comments", - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/commits", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", - "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", - "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", - "GET /repos/{owner}/{repo}/commits/{ref}/status", - "GET /repos/{owner}/{repo}/commits/{ref}/statuses", - "GET /repos/{owner}/{repo}/contributors", - "GET /repos/{owner}/{repo}/dependabot/alerts", - "GET /repos/{owner}/{repo}/dependabot/secrets", - "GET /repos/{owner}/{repo}/deployments", - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", - "GET /repos/{owner}/{repo}/environments", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", - "GET /repos/{owner}/{repo}/events", - "GET /repos/{owner}/{repo}/forks", - "GET /repos/{owner}/{repo}/hooks", - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", - "GET /repos/{owner}/{repo}/invitations", - "GET /repos/{owner}/{repo}/issues", - "GET /repos/{owner}/{repo}/issues/comments", - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/issues/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", - "GET /repos/{owner}/{repo}/issues/{issue_number}/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", - "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", - "GET /repos/{owner}/{repo}/keys", - "GET /repos/{owner}/{repo}/labels", - "GET /repos/{owner}/{repo}/milestones", - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", - "GET /repos/{owner}/{repo}/notifications", - "GET /repos/{owner}/{repo}/pages/builds", - "GET /repos/{owner}/{repo}/projects", - "GET /repos/{owner}/{repo}/pulls", - "GET /repos/{owner}/{repo}/pulls/comments", - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", - "GET /repos/{owner}/{repo}/releases", - "GET /repos/{owner}/{repo}/releases/{release_id}/assets", - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", - "GET /repos/{owner}/{repo}/rules/branches/{branch}", - "GET /repos/{owner}/{repo}/rulesets", - "GET /repos/{owner}/{repo}/rulesets/rule-suites", - "GET /repos/{owner}/{repo}/secret-scanning/alerts", - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", - "GET /repos/{owner}/{repo}/security-advisories", - "GET /repos/{owner}/{repo}/stargazers", - "GET /repos/{owner}/{repo}/subscribers", - "GET /repos/{owner}/{repo}/tags", - "GET /repos/{owner}/{repo}/teams", - "GET /repos/{owner}/{repo}/topics", - "GET /repositories", - "GET /repositories/{repository_id}/environments/{environment_name}/secrets", - "GET /repositories/{repository_id}/environments/{environment_name}/variables", - "GET /search/code", - "GET /search/commits", - "GET /search/issues", - "GET /search/labels", - "GET /search/repositories", - "GET /search/topics", - "GET /search/users", - "GET /teams/{team_id}/discussions", - "GET /teams/{team_id}/discussions/{discussion_number}/comments", - "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /teams/{team_id}/discussions/{discussion_number}/reactions", - "GET /teams/{team_id}/invitations", - "GET /teams/{team_id}/members", - "GET /teams/{team_id}/projects", - "GET /teams/{team_id}/repos", - "GET /teams/{team_id}/teams", - "GET /user/blocks", - "GET /user/codespaces", - "GET /user/codespaces/secrets", - "GET /user/emails", - "GET /user/followers", - "GET /user/following", - "GET /user/gpg_keys", - "GET /user/installations", - "GET /user/installations/{installation_id}/repositories", - "GET /user/issues", - "GET /user/keys", - "GET /user/marketplace_purchases", - "GET /user/marketplace_purchases/stubbed", - "GET /user/memberships/orgs", - "GET /user/migrations", - "GET /user/migrations/{migration_id}/repositories", - "GET /user/orgs", - "GET /user/packages", - "GET /user/packages/{package_type}/{package_name}/versions", - "GET /user/public_emails", - "GET /user/repos", - "GET /user/repository_invitations", - "GET /user/social_accounts", - "GET /user/ssh_signing_keys", - "GET /user/starred", - "GET /user/subscriptions", - "GET /user/teams", - "GET /users", - "GET /users/{username}/events", - "GET /users/{username}/events/orgs/{org}", - "GET /users/{username}/events/public", - "GET /users/{username}/followers", - "GET /users/{username}/following", - "GET /users/{username}/gists", - "GET /users/{username}/gpg_keys", - "GET /users/{username}/keys", - "GET /users/{username}/orgs", - "GET /users/{username}/packages", - "GET /users/{username}/projects", - "GET /users/{username}/received_events", - "GET /users/{username}/received_events/public", - "GET /users/{username}/repos", - "GET /users/{username}/social_accounts", - "GET /users/{username}/ssh_signing_keys", - "GET /users/{username}/starred", - "GET /users/{username}/subscriptions" -]; + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] -// pkg/dist-src/paginating-endpoints.js -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const r = new RegExp(`^${this.options.loose ? src[t.PRERELEASELOOSE] : src[t.PRERELEASE]}$`) + const match = `-${identifier}`.match(r) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } + + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this } } -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; +module.exports = SemVer + + +/***/ }), + +/***/ 64510: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const parse = __nccwpck_require__(45240) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null } -paginateRest.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); +module.exports = clean /***/ }), -/***/ 84935: -/***/ ((module) => { +/***/ 23991: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const eq = __nccwpck_require__(5113) +const neq = __nccwpck_require__(26487) +const gt = __nccwpck_require__(35012) +const gte = __nccwpck_require__(67745) +const lt = __nccwpck_require__(63691) +const lte = __nccwpck_require__(27672) -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - legacyRestEndpointMethods: () => legacyRestEndpointMethods, - restEndpointMethods: () => restEndpointMethods -}); -module.exports = __toCommonJS(dist_src_exports); + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b -// pkg/dist-src/version.js -var VERSION = "10.3.0"; + case '': + case '=': + case '==': + return eq(a, b, loose) -// pkg/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repositories/{repository_id}/environments/{environment_name}/variables" - ], - createOrUpdateEnvironmentSecret: [ - "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables" - ], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotForBusinessSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotForBusinessSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: [ - "DELETE /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" - } - ], - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getCommitAuthors: [ - "GET /repos/{owner}/{repo}/import/authors", - {}, - { - deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" - } - ], - getImportStatus: [ - "GET /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" - } - ], - getLargeFiles: [ - "GET /repos/{owner}/{repo}/import/large_files", - {}, - { - deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" - } - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - mapCommitAuthor: [ - "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", - {}, - { - deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" - } - ], - setLfsPreference: [ - "PATCH /repos/{owner}/{repo}/import/lfs", - {}, - { - deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" - } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: [ - "PUT /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" - } - ], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ], - updateImport: [ - "PATCH /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" - } - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createInvitation: ["POST /orgs/{org}/invitations"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - enableOrDisableSecurityProductOnAllOrgRepos: [ - "POST /orgs/{org}/{security_product}/{enablement}" - ], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}" - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], - createCard: ["POST /projects/columns/{column_id}/cards"], - createColumn: ["POST /projects/{project_id}/columns"], - createForAuthenticatedUser: ["POST /user/projects"], - createForOrg: ["POST /orgs/{org}/projects"], - createForRepo: ["POST /repos/{owner}/{repo}/projects"], - delete: ["DELETE /projects/{project_id}"], - deleteCard: ["DELETE /projects/columns/cards/{card_id}"], - deleteColumn: ["DELETE /projects/columns/{column_id}"], - get: ["GET /projects/{project_id}"], - getCard: ["GET /projects/columns/cards/{card_id}"], - getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: [ - "GET /projects/{project_id}/collaborators/{username}/permission" - ], - listCards: ["GET /projects/columns/{column_id}/cards"], - listCollaborators: ["GET /projects/{project_id}/collaborators"], - listColumns: ["GET /projects/{project_id}/columns"], - listForOrg: ["GET /orgs/{org}/projects"], - listForRepo: ["GET /repos/{owner}/{repo}/projects"], - listForUser: ["GET /users/{username}/projects"], - moveCard: ["POST /projects/columns/cards/{card_id}/moves"], - moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: [ - "DELETE /projects/{project_id}/collaborators/{username}" - ], - update: ["PATCH /projects/{project_id}"], - updateCard: ["PATCH /projects/columns/cards/{card_id}"], - updateColumn: ["PATCH /projects/columns/{column_id}"] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployment"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteTagProtection: [ - "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" - ], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ] - }, - securityAdvisories: { - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateProjectPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForProjectInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeProjectInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// pkg/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; - }, - set(target, methodName, value) { - return target.cache[methodName] = value; - }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// pkg/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 33450: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__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: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - VERSION: () => VERSION, - retry: () => retry -}); -module.exports = __toCommonJS(dist_src_exports); -var import_core = __nccwpck_require__(61897); - -// pkg/dist-src/error-request.js -async function errorRequest(state, octokit, error, options) { - if (!error.request || !error.request.request) { - throw error; - } - if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { - const retries = options.request.retries != null ? options.request.retries : state.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error, retries, retryAfter); - } - throw error; -} - -// pkg/dist-src/wrap-request.js -var import_light = __toESM(__nccwpck_require__(63251)); -var import_request_error = __nccwpck_require__(93708); -async function wrapRequest(state, octokit, request, options) { - const limiter = new import_light.default(); - limiter.on("failed", function(error, info) { - const maxRetries = ~~error.request.request.retries; - const after = ~~error.request.request.retryAfter; - options.request.retryCount = info.retryCount + 1; - if (maxRetries > info.retryCount) { - return after * state.retryAfterBaseValue; - } - }); - return limiter.schedule( - requestWithGraphqlErrorHandling.bind(null, state, octokit, request), - options - ); -} -async function requestWithGraphqlErrorHandling(state, octokit, request, options) { - const response = await request(request, options); - if (response.data && response.data.errors && /Something went wrong while executing your query/.test( - response.data.errors[0].message - )) { - const error = new import_request_error.RequestError(response.data.errors[0].message, 500, { - request: options, - response - }); - return errorRequest(state, octokit, error, options); - } - return response; -} - -// pkg/dist-src/index.js -var VERSION = "6.0.1"; -function retry(octokit, octokitOptions) { - const state = Object.assign( - { - enabled: true, - retryAfterBaseValue: 1e3, - doNotRetry: [400, 401, 403, 404, 422, 451], - retries: 3 - }, - octokitOptions.retry - ); - if (state.enabled) { - octokit.hook.error("request", errorRequest.bind(null, state, octokit)); - octokit.hook.wrap("request", wrapRequest.bind(null, state, octokit)); - } - return { - retry: { - retryRequest: (error, retries, retryAfter) => { - error.request.request = Object.assign({}, error.request.request, { - retries, - retryAfter - }); - return error; - } - } - }; -} -retry.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 93708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__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: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - RequestError: () => RequestError -}); -module.exports = __toCommonJS(dist_src_exports); -var import_deprecation = __nccwpck_require__(14150); -var import_once = __toESM(__nccwpck_require__(55560)); -var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); -var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); -var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? { - -"use strict"; - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - request: () => request -}); -module.exports = __toCommonJS(dist_src_exports); -var import_endpoint = __nccwpck_require__(54471); -var import_universal_user_agent = __nccwpck_require__(33843); - -// pkg/dist-src/version.js -var VERSION = "8.2.0"; - -// pkg/dist-src/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - if (Object.prototype.toString.call(value) !== "[object Object]") - return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) - return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} - -// pkg/dist-src/fetch-wrapper.js -var import_request_error = __nccwpck_require__(93708); - -// pkg/dist-src/get-buffer-response.js -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -// pkg/dist-src/fetch-wrapper.js -function fetchWrapper(requestOptions) { - var _a, _b, _c; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - throw new Error( - "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - headers: requestOptions.headers, - signal: (_c = requestOptions.request) == null ? void 0 : _c.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error) => { - if (error instanceof import_request_error.RequestError) - throw error; - else if (error.name === "AbortError") - throw error; - let message = error.message; - if (error.name === "TypeError" && "cause" in error) { - if (error.cause instanceof Error) { - message = error.cause.message; - } else if (typeof error.cause === "string") { - message = error.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (/application\/json/.test(contentType)) { - return response.json().catch(() => response.text()).catch(() => ""); - } - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } - return getBufferResponse(response); -} -function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} - -// pkg/dist-src/with-defaults.js -function withDefaults(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); -} - -// pkg/dist-src/index.js -var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } -}); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 18456: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toMessageSignatureBundle = toMessageSignatureBundle; -exports.toDSSEBundle = toDSSEBundle; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const protobuf_specs_1 = __nccwpck_require__(19654); -const bundle_1 = __nccwpck_require__(37742); -// Message signature bundle - $case: 'messageSignature' -function toMessageSignatureBundle(options) { - return { - mediaType: options.certificateChain - ? bundle_1.BUNDLE_V02_MEDIA_TYPE - : bundle_1.BUNDLE_V03_MEDIA_TYPE, - content: { - $case: 'messageSignature', - messageSignature: { - messageDigest: { - algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256, - digest: options.digest, - }, - signature: options.signature, - }, - }, - verificationMaterial: toVerificationMaterial(options), - }; -} -// DSSE envelope bundle - $case: 'dsseEnvelope' -function toDSSEBundle(options) { - return { - mediaType: options.certificateChain - ? bundle_1.BUNDLE_V02_MEDIA_TYPE - : bundle_1.BUNDLE_V03_MEDIA_TYPE, - content: { - $case: 'dsseEnvelope', - dsseEnvelope: toEnvelope(options), - }, - verificationMaterial: toVerificationMaterial(options), - }; -} -function toEnvelope(options) { - return { - payloadType: options.artifactType, - payload: options.artifact, - signatures: [toSignature(options)], - }; -} -function toSignature(options) { - return { - keyid: options.keyHint || '', - sig: options.signature, - }; -} -// Verification material -function toVerificationMaterial(options) { - return { - content: toKeyContent(options), - tlogEntries: [], - timestampVerificationData: { rfc3161Timestamps: [] }, - }; -} -function toKeyContent(options) { - if (options.certificate) { - if (options.certificateChain) { - return { - $case: 'x509CertificateChain', - x509CertificateChain: { - certificates: [{ rawBytes: options.certificate }], - }, - }; - } - else { - return { - $case: 'certificate', - certificate: { rawBytes: options.certificate }, - }; - } - } - else { - return { - $case: 'publicKey', - publicKey: { - hint: options.keyHint || '', - }, - }; - } -} - - -/***/ }), - -/***/ 37742: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0; -exports.isBundleWithCertificateChain = isBundleWithCertificateChain; -exports.isBundleWithPublicKey = isBundleWithPublicKey; -exports.isBundleWithMessageSignature = isBundleWithMessageSignature; -exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope; -exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1'; -exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2'; -exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3'; -exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json'; -// Type guards for bundle variants. -function isBundleWithCertificateChain(b) { - return b.verificationMaterial.content.$case === 'x509CertificateChain'; -} -function isBundleWithPublicKey(b) { - return b.verificationMaterial.content.$case === 'publicKey'; -} -function isBundleWithMessageSignature(b) { - return b.content.$case === 'messageSignature'; -} -function isBundleWithDsseEnvelope(b) { - return b.content.$case === 'dsseEnvelope'; -} - - -/***/ }), - -/***/ 47714: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ValidationError = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -class ValidationError extends Error { - constructor(message, fields) { - super(message); - this.fields = fields; - } -} -exports.ValidationError = ValidationError; - - -/***/ }), - -/***/ 61040: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var build_1 = __nccwpck_require__(18456); -Object.defineProperty(exports, "toDSSEBundle", ({ enumerable: true, get: function () { return build_1.toDSSEBundle; } })); -Object.defineProperty(exports, "toMessageSignatureBundle", ({ enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } })); -var bundle_1 = __nccwpck_require__(37742); -Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } })); -Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } })); -Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } })); -Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } })); -Object.defineProperty(exports, "isBundleWithCertificateChain", ({ enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } })); -Object.defineProperty(exports, "isBundleWithDsseEnvelope", ({ enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } })); -Object.defineProperty(exports, "isBundleWithMessageSignature", ({ enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } })); -Object.defineProperty(exports, "isBundleWithPublicKey", ({ enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } })); -var error_1 = __nccwpck_require__(47714); -Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return error_1.ValidationError; } })); -var serialized_1 = __nccwpck_require__(23404); -Object.defineProperty(exports, "bundleFromJSON", ({ enumerable: true, get: function () { return serialized_1.bundleFromJSON; } })); -Object.defineProperty(exports, "bundleToJSON", ({ enumerable: true, get: function () { return serialized_1.bundleToJSON; } })); -Object.defineProperty(exports, "envelopeFromJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } })); -Object.defineProperty(exports, "envelopeToJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeToJSON; } })); -var validate_1 = __nccwpck_require__(9352); -Object.defineProperty(exports, "assertBundle", ({ enumerable: true, get: function () { return validate_1.assertBundle; } })); -Object.defineProperty(exports, "assertBundleLatest", ({ enumerable: true, get: function () { return validate_1.assertBundleLatest; } })); -Object.defineProperty(exports, "assertBundleV01", ({ enumerable: true, get: function () { return validate_1.assertBundleV01; } })); -Object.defineProperty(exports, "assertBundleV02", ({ enumerable: true, get: function () { return validate_1.assertBundleV02; } })); -Object.defineProperty(exports, "isBundleV01", ({ enumerable: true, get: function () { return validate_1.isBundleV01; } })); - - -/***/ }), - -/***/ 23404: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const protobuf_specs_1 = __nccwpck_require__(19654); -const bundle_1 = __nccwpck_require__(37742); -const validate_1 = __nccwpck_require__(9352); -const bundleFromJSON = (obj) => { - const bundle = protobuf_specs_1.Bundle.fromJSON(obj); - switch (bundle.mediaType) { - case bundle_1.BUNDLE_V01_MEDIA_TYPE: - (0, validate_1.assertBundleV01)(bundle); - break; - case bundle_1.BUNDLE_V02_MEDIA_TYPE: - (0, validate_1.assertBundleV02)(bundle); - break; - default: - (0, validate_1.assertBundleLatest)(bundle); - break; - } - return bundle; -}; -exports.bundleFromJSON = bundleFromJSON; -const bundleToJSON = (bundle) => { - return protobuf_specs_1.Bundle.toJSON(bundle); -}; -exports.bundleToJSON = bundleToJSON; -const envelopeFromJSON = (obj) => { - return protobuf_specs_1.Envelope.fromJSON(obj); -}; -exports.envelopeFromJSON = envelopeFromJSON; -const envelopeToJSON = (envelope) => { - return protobuf_specs_1.Envelope.toJSON(envelope); -}; -exports.envelopeToJSON = envelopeToJSON; - - -/***/ }), - -/***/ 9352: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.assertBundle = assertBundle; -exports.assertBundleV01 = assertBundleV01; -exports.isBundleV01 = isBundleV01; -exports.assertBundleV02 = assertBundleV02; -exports.assertBundleLatest = assertBundleLatest; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const error_1 = __nccwpck_require__(47714); -// Performs basic validation of a Sigstore bundle to ensure that all required -// fields are populated. This is not a complete validation of the bundle, but -// rather a check that the bundle is in a valid state to be processed by the -// rest of the code. -function assertBundle(b) { - const invalidValues = validateBundleBase(b); - if (invalidValues.length > 0) { - throw new error_1.ValidationError('invalid bundle', invalidValues); - } -} -// Asserts that the given bundle conforms to the v0.1 bundle format. -function assertBundleV01(b) { - const invalidValues = []; - invalidValues.push(...validateBundleBase(b)); - invalidValues.push(...validateInclusionPromise(b)); - if (invalidValues.length > 0) { - throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues); - } -} -// Type guard to determine if Bundle is a v0.1 bundle. -function isBundleV01(b) { - try { - assertBundleV01(b); - return true; - } - catch (e) { - return false; - } -} -// Asserts that the given bundle conforms to the v0.2 bundle format. -function assertBundleV02(b) { - const invalidValues = []; - invalidValues.push(...validateBundleBase(b)); - invalidValues.push(...validateInclusionProof(b)); - if (invalidValues.length > 0) { - throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues); - } -} -// Asserts that the given bundle conforms to the newest (0.3) bundle format. -function assertBundleLatest(b) { - const invalidValues = []; - invalidValues.push(...validateBundleBase(b)); - invalidValues.push(...validateInclusionProof(b)); - invalidValues.push(...validateNoCertificateChain(b)); - if (invalidValues.length > 0) { - throw new error_1.ValidationError('invalid bundle', invalidValues); - } -} -function validateBundleBase(b) { - const invalidValues = []; - // Media type validation - if (b.mediaType === undefined || - (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) && - !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) { - invalidValues.push('mediaType'); - } - // Content-related validation - if (b.content === undefined) { - invalidValues.push('content'); - } - else { - switch (b.content.$case) { - case 'messageSignature': - if (b.content.messageSignature.messageDigest === undefined) { - invalidValues.push('content.messageSignature.messageDigest'); - } - else { - if (b.content.messageSignature.messageDigest.digest.length === 0) { - invalidValues.push('content.messageSignature.messageDigest.digest'); - } - } - if (b.content.messageSignature.signature.length === 0) { - invalidValues.push('content.messageSignature.signature'); - } - break; - case 'dsseEnvelope': - if (b.content.dsseEnvelope.payload.length === 0) { - invalidValues.push('content.dsseEnvelope.payload'); - } - if (b.content.dsseEnvelope.signatures.length !== 1) { - invalidValues.push('content.dsseEnvelope.signatures'); - } - else { - if (b.content.dsseEnvelope.signatures[0].sig.length === 0) { - invalidValues.push('content.dsseEnvelope.signatures[0].sig'); - } - } - break; - } - } - // Verification material-related validation - if (b.verificationMaterial === undefined) { - invalidValues.push('verificationMaterial'); - } - else { - if (b.verificationMaterial.content === undefined) { - invalidValues.push('verificationMaterial.content'); - } - else { - switch (b.verificationMaterial.content.$case) { - case 'x509CertificateChain': - if (b.verificationMaterial.content.x509CertificateChain.certificates - .length === 0) { - invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates'); - } - b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => { - if (cert.rawBytes.length === 0) { - invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`); - } - }); - break; - case 'certificate': - if (b.verificationMaterial.content.certificate.rawBytes.length === 0) { - invalidValues.push('verificationMaterial.content.certificate.rawBytes'); - } - break; - } - } - if (b.verificationMaterial.tlogEntries === undefined) { - invalidValues.push('verificationMaterial.tlogEntries'); - } - else { - if (b.verificationMaterial.tlogEntries.length > 0) { - b.verificationMaterial.tlogEntries.forEach((entry, i) => { - if (entry.logId === undefined) { - invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`); - } - if (entry.kindVersion === undefined) { - invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`); - } - }); - } - } - } - return invalidValues; -} -// Necessary for V01 bundles -function validateInclusionPromise(b) { - const invalidValues = []; - if (b.verificationMaterial && - b.verificationMaterial.tlogEntries?.length > 0) { - b.verificationMaterial.tlogEntries.forEach((entry, i) => { - if (entry.inclusionPromise === undefined) { - invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`); - } - }); - } - return invalidValues; -} -// Necessary for V02 and later bundles -function validateInclusionProof(b) { - const invalidValues = []; - if (b.verificationMaterial && - b.verificationMaterial.tlogEntries?.length > 0) { - b.verificationMaterial.tlogEntries.forEach((entry, i) => { - if (entry.inclusionProof === undefined) { - invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`); - } - else { - if (entry.inclusionProof.checkpoint === undefined) { - invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`); - } - } - }); - } - return invalidValues; -} -// Necessary for V03 and later bundles -function validateNoCertificateChain(b) { - const invalidValues = []; - /* istanbul ignore next */ - if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') { - invalidValues.push('verificationMaterial.content.$case'); - } - return invalidValues; -} - - -/***/ }), - -/***/ 11121: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ASN1TypeError = exports.ASN1ParseError = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -class ASN1ParseError extends Error { -} -exports.ASN1ParseError = ASN1ParseError; -class ASN1TypeError extends Error { -} -exports.ASN1TypeError = ASN1TypeError; - - -/***/ }), - -/***/ 86027: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ASN1Obj = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var obj_1 = __nccwpck_require__(50990); -Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return obj_1.ASN1Obj; } })); - - -/***/ }), - -/***/ 84243: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decodeLength = decodeLength; -exports.encodeLength = encodeLength; -const error_1 = __nccwpck_require__(11121); -// Decodes the length of a DER-encoded ANS.1 element from the supplied stream. -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes -function decodeLength(stream) { - const buf = stream.getUint8(); - // If the most significant bit is UNSET the length is just the value of the - // byte. - if ((buf & 0x80) === 0x00) { - return buf; - } - // Otherwise, the lower 7 bits of the first byte indicate the number of bytes - // that follow to encode the length. - const byteCount = buf & 0x7f; - // Ensure the encoded length can safely fit in a JS number. - if (byteCount > 6) { - throw new error_1.ASN1ParseError('length exceeds 6 byte limit'); - } - // Iterate over the bytes that encode the length. - let len = 0; - for (let i = 0; i < byteCount; i++) { - len = len * 256 + stream.getUint8(); - } - // This is a valid ASN.1 length encoding, but we don't support it. - if (len === 0) { - throw new error_1.ASN1ParseError('indefinite length encoding not supported'); - } - return len; -} -// Translates the supplied value to a DER-encoded length. -function encodeLength(len) { - if (len < 128) { - return Buffer.from([len]); - } - // Bitwise operations on large numbers are not supported in JS, so we need to - // use BigInts. - let val = BigInt(len); - const bytes = []; - while (val > 0n) { - bytes.unshift(Number(val & 255n)); - val = val >> 8n; - } - return Buffer.from([0x80 | bytes.length, ...bytes]); -} - - -/***/ }), - -/***/ 50990: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ASN1Obj = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const stream_1 = __nccwpck_require__(1673); -const error_1 = __nccwpck_require__(11121); -const length_1 = __nccwpck_require__(84243); -const parse_1 = __nccwpck_require__(81044); -const tag_1 = __nccwpck_require__(59343); -class ASN1Obj { - constructor(tag, value, subs) { - this.tag = tag; - this.value = value; - this.subs = subs; - } - // Constructs an ASN.1 object from a Buffer of DER-encoded bytes. - static parseBuffer(buf) { - return parseStream(new stream_1.ByteStream(buf)); - } - toDER() { - const valueStream = new stream_1.ByteStream(); - if (this.subs.length > 0) { - for (const sub of this.subs) { - valueStream.appendView(sub.toDER()); - } - } - else { - valueStream.appendView(this.value); - } - const value = valueStream.buffer; - // Concat tag/length/value - const obj = new stream_1.ByteStream(); - obj.appendChar(this.tag.toDER()); - obj.appendView((0, length_1.encodeLength)(value.length)); - obj.appendView(value); - return obj.buffer; - } - ///////////////////////////////////////////////////////////////////////////// - // Convenience methods for parsing ASN.1 primitives into JS types - // Returns the ASN.1 object's value as a boolean. Throws an error if the - // object is not a boolean. - toBoolean() { - if (!this.tag.isBoolean()) { - throw new error_1.ASN1TypeError('not a boolean'); - } - return (0, parse_1.parseBoolean)(this.value); - } - // Returns the ASN.1 object's value as a BigInt. Throws an error if the - // object is not an integer. - toInteger() { - if (!this.tag.isInteger()) { - throw new error_1.ASN1TypeError('not an integer'); - } - return (0, parse_1.parseInteger)(this.value); - } - // Returns the ASN.1 object's value as an OID string. Throws an error if the - // object is not an OID. - toOID() { - if (!this.tag.isOID()) { - throw new error_1.ASN1TypeError('not an OID'); - } - return (0, parse_1.parseOID)(this.value); - } - // Returns the ASN.1 object's value as a Date. Throws an error if the object - // is not either a UTCTime or a GeneralizedTime. - toDate() { - switch (true) { - case this.tag.isUTCTime(): - return (0, parse_1.parseTime)(this.value, true); - case this.tag.isGeneralizedTime(): - return (0, parse_1.parseTime)(this.value, false); - default: - throw new error_1.ASN1TypeError('not a date'); - } - } - // Returns the ASN.1 object's value as a number[] where each number is the - // value of a bit in the bit string. Throws an error if the object is not a - // bit string. - toBitString() { - if (!this.tag.isBitString()) { - throw new error_1.ASN1TypeError('not a bit string'); - } - return (0, parse_1.parseBitString)(this.value); - } -} -exports.ASN1Obj = ASN1Obj; -///////////////////////////////////////////////////////////////////////////// -// Internal stream parsing functions -function parseStream(stream) { - // Parse tag, length, and value from stream - const tag = new tag_1.ASN1Tag(stream.getUint8()); - const len = (0, length_1.decodeLength)(stream); - const value = stream.slice(stream.position, len); - const start = stream.position; - let subs = []; - // If the object is constructed, parse its children. Sometimes, children - // are embedded in OCTESTRING objects, so we need to check those - // for children as well. - if (tag.constructed) { - subs = collectSubs(stream, len); - } - else if (tag.isOctetString()) { - // Attempt to parse children of OCTETSTRING objects. If anything fails, - // assume the object is not constructed and treat as primitive. - try { - subs = collectSubs(stream, len); - } - catch (e) { - // Fail silently and treat as primitive - } - } - // If there are no children, move stream cursor to the end of the object - if (subs.length === 0) { - stream.seek(start + len); - } - return new ASN1Obj(tag, value, subs); -} -function collectSubs(stream, len) { - // Calculate end of object content - const end = stream.position + len; - // Make sure there are enough bytes left in the stream. This should never - // happen, cause it'll get caught when the stream is sliced in parseStream. - // Leaving as an extra check just in case. - /* istanbul ignore if */ - if (end > stream.length) { - throw new error_1.ASN1ParseError('invalid length'); - } - // Parse all children - const subs = []; - while (stream.position < end) { - subs.push(parseStream(stream)); - } - // When we're done parsing children, we should be at the end of the object - if (stream.position !== end) { - throw new error_1.ASN1ParseError('invalid length'); - } - return subs; -} - - -/***/ }), - -/***/ 81044: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseInteger = parseInteger; -exports.parseStringASCII = parseStringASCII; -exports.parseTime = parseTime; -exports.parseOID = parseOID; -exports.parseBoolean = parseBoolean; -exports.parseBitString = parseBitString; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; -const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; -// Parse a BigInt from the DER-encoded buffer -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer -function parseInteger(buf) { - let pos = 0; - const end = buf.length; - let val = buf[pos]; - const neg = val > 0x7f; - // Consume any padding bytes - const pad = neg ? 0xff : 0x00; - while (val == pad && ++pos < end) { - val = buf[pos]; - } - // Calculate remaining bytes to read - const len = end - pos; - if (len === 0) - return BigInt(neg ? -1 : 0); - // Handle two's complement for negative numbers - val = neg ? val - 256 : val; - // Parse remaining bytes - let n = BigInt(val); - for (let i = pos + 1; i < end; ++i) { - n = n * BigInt(256) + BigInt(buf[i]); - } - return n; -} -// Parse an ASCII string from the DER-encoded buffer -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean -function parseStringASCII(buf) { - return buf.toString('ascii'); -} -// Parse a Date from the DER-encoded buffer -// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1 -function parseTime(buf, shortYear) { - const timeStr = parseStringASCII(buf); - // Parse the time string into matches - captured groups start at index 1 - const m = shortYear - ? RE_TIME_SHORT_YEAR.exec(timeStr) - : RE_TIME_LONG_YEAR.exec(timeStr); - if (!m) { - throw new Error('invalid time'); - } - // Translate dates with a 2-digit year to 4 digits per the spec - if (shortYear) { - let year = Number(m[1]); - year += year >= 50 ? 1900 : 2000; - m[1] = year.toString(); - } - // Translate to ISO8601 format and parse - return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`); -} -// Parse an OID from the DER-encoded buffer -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier -function parseOID(buf) { - let pos = 0; - const end = buf.length; - // Consume first byte which encodes the first two OID components - let n = buf[pos++]; - const first = Math.floor(n / 40); - const second = n % 40; - let oid = `${first}.${second}`; - // Consume remaining bytes - let val = 0; - for (; pos < end; ++pos) { - n = buf[pos]; - val = (val << 7) + (n & 0x7f); - // If the left-most bit is NOT set, then this is the last byte in the - // sequence and we can add the value to the OID and reset the accumulator - if ((n & 0x80) === 0) { - oid += `.${val}`; - val = 0; - } - } - return oid; -} -// Parse a boolean from the DER-encoded buffer -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean -function parseBoolean(buf) { - return buf[0] !== 0; -} -// Parse a bit string from the DER-encoded buffer -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string -function parseBitString(buf) { - // First byte tell us how many unused bits are in the last byte - const unused = buf[0]; - const start = 1; - const end = buf.length; - const bits = []; - for (let i = start; i < end; ++i) { - const byte = buf[i]; - // The skip value is only used for the last byte - const skip = i === end - 1 ? unused : 0; - // Iterate over each bit in the byte (most significant first) - for (let j = 7; j >= skip; --j) { - // Read the bit and add it to the bit string - bits.push((byte >> j) & 0x01); - } - } - return bits; -} - - -/***/ }), - -/***/ 59343: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ASN1Tag = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const error_1 = __nccwpck_require__(11121); -const UNIVERSAL_TAG = { - BOOLEAN: 0x01, - INTEGER: 0x02, - BIT_STRING: 0x03, - OCTET_STRING: 0x04, - OBJECT_IDENTIFIER: 0x06, - SEQUENCE: 0x10, - SET: 0x11, - PRINTABLE_STRING: 0x13, - UTC_TIME: 0x17, - GENERALIZED_TIME: 0x18, -}; -const TAG_CLASS = { - UNIVERSAL: 0x00, - APPLICATION: 0x01, - CONTEXT_SPECIFIC: 0x02, - PRIVATE: 0x03, -}; -// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes -class ASN1Tag { - constructor(enc) { - // Bits 0 through 4 are the tag number - this.number = enc & 0x1f; - // Bit 5 is the constructed bit - this.constructed = (enc & 0x20) === 0x20; - // Bit 6 & 7 are the class - this.class = enc >> 6; - if (this.number === 0x1f) { - throw new error_1.ASN1ParseError('long form tags not supported'); - } - if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) { - throw new error_1.ASN1ParseError('unsupported tag 0x00'); - } - } - isUniversal() { - return this.class === TAG_CLASS.UNIVERSAL; - } - isContextSpecific(num) { - const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC; - return num !== undefined ? res && this.number === num : res; - } - isBoolean() { - return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN; - } - isInteger() { - return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER; - } - isBitString() { - return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING; - } - isOctetString() { - return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING; - } - isOID() { - return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER); - } - isUTCTime() { - return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME; - } - isGeneralizedTime() { - return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME; - } - toDER() { - return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6); - } -} -exports.ASN1Tag = ASN1Tag; - - -/***/ }), - -/***/ 69368: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createPublicKey = createPublicKey; -exports.digest = digest; -exports.verify = verify; -exports.bufferEqual = bufferEqual; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const crypto_1 = __importDefault(__nccwpck_require__(76982)); -function createPublicKey(key, type = 'spki') { - if (typeof key === 'string') { - return crypto_1.default.createPublicKey(key); - } - else { - return crypto_1.default.createPublicKey({ key, format: 'der', type: type }); - } -} -function digest(algorithm, ...data) { - const hash = crypto_1.default.createHash(algorithm); - for (const d of data) { - hash.update(d); - } - return hash.digest(); -} -function verify(data, key, signature, algorithm) { - // The try/catch is to work around an issue in Node 14.x where verify throws - // an error in some scenarios if the signature is invalid. - try { - return crypto_1.default.verify(algorithm, data, key, signature); - } - catch (e) { - /* istanbul ignore next */ - return false; - } -} -function bufferEqual(a, b) { - try { - return crypto_1.default.timingSafeEqual(a, b); - } - catch { - /* istanbul ignore next */ - return false; - } -} - - -/***/ }), - -/***/ 49032: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.preAuthEncoding = preAuthEncoding; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const PAE_PREFIX = 'DSSEv1'; -// DSSE Pre-Authentication Encoding -function preAuthEncoding(payloadType, payload) { - const prefix = [ - PAE_PREFIX, - payloadType.length, - payloadType, - payload.length, - '', - ].join(' '); - return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]); -} - - -/***/ }), - -/***/ 52788: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.base64Encode = base64Encode; -exports.base64Decode = base64Decode; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const BASE64_ENCODING = 'base64'; -const UTF8_ENCODING = 'utf-8'; -function base64Encode(str) { - return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING); -} -function base64Decode(str) { - return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING); -} - - -/***/ }), - -/***/ 83917: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var asn1_1 = __nccwpck_require__(86027); -Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return asn1_1.ASN1Obj; } })); -exports.crypto = __importStar(__nccwpck_require__(69368)); -exports.dsse = __importStar(__nccwpck_require__(49032)); -exports.encoding = __importStar(__nccwpck_require__(52788)); -exports.json = __importStar(__nccwpck_require__(13327)); -exports.pem = __importStar(__nccwpck_require__(1055)); -var rfc3161_1 = __nccwpck_require__(20994); -Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } })); -var stream_1 = __nccwpck_require__(1673); -Object.defineProperty(exports, "ByteStream", ({ enumerable: true, get: function () { return stream_1.ByteStream; } })); -var x509_1 = __nccwpck_require__(49358); -Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } })); -Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return x509_1.X509Certificate; } })); -Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return x509_1.X509SCTExtension; } })); - - -/***/ }), - -/***/ 13327: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.canonicalize = canonicalize; -// JSON canonicalization per https://github.com/cyberphone/json-canonicalization -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function canonicalize(object) { - let buffer = ''; - if (object === null || typeof object !== 'object' || object.toJSON != null) { - // Primitives or toJSONable objects - buffer += JSON.stringify(object); - } - else if (Array.isArray(object)) { - // Array - maintain element order - buffer += '['; - let first = true; - object.forEach((element) => { - if (!first) { - buffer += ','; - } - first = false; - // recursive call - buffer += canonicalize(element); - }); - buffer += ']'; - } - else { - // Object - Sort properties before serializing - buffer += '{'; - let first = true; - Object.keys(object) - .sort() - .forEach((property) => { - if (!first) { - buffer += ','; - } - first = false; - buffer += JSON.stringify(property); - buffer += ':'; - // recursive call - buffer += canonicalize(object[property]); - }); - buffer += '}'; - } - return buffer; -} - - -/***/ }), - -/***/ 91817: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0; -exports.ECDSA_SIGNATURE_ALGOS = { - '1.2.840.10045.4.3.1': 'sha224', - '1.2.840.10045.4.3.2': 'sha256', - '1.2.840.10045.4.3.3': 'sha384', - '1.2.840.10045.4.3.4': 'sha512', -}; -exports.SHA2_HASH_ALGOS = { - '2.16.840.1.101.3.4.2.1': 'sha256', - '2.16.840.1.101.3.4.2.2': 'sha384', - '2.16.840.1.101.3.4.2.3': 'sha512', -}; - - -/***/ }), - -/***/ 1055: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toDER = toDER; -exports.fromDER = fromDER; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const PEM_HEADER = /-----BEGIN (.*)-----/; -const PEM_FOOTER = /-----END (.*)-----/; -function toDER(certificate) { - let der = ''; - certificate.split('\n').forEach((line) => { - if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) { - return; - } - der += line; - }); - return Buffer.from(der, 'base64'); -} -// Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM -// encoding dictates that each certificate should have a trailing newline after -// the footer. -function fromDER(certificate, type = 'CERTIFICATE') { - // Base64-encode the certificate. - const der = certificate.toString('base64'); - // Split the certificate into lines of 64 characters. - const lines = der.match(/.{1,64}/g) || ''; - return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`] - .join('\n') - .concat('\n'); -} - - -/***/ }), - -/***/ 97512: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RFC3161TimestampVerificationError = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -class RFC3161TimestampVerificationError extends Error { -} -exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError; - - -/***/ }), - -/***/ 20994: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RFC3161Timestamp = void 0; -var timestamp_1 = __nccwpck_require__(92714); -Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } })); - - -/***/ }), - -/***/ 92714: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RFC3161Timestamp = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const asn1_1 = __nccwpck_require__(86027); -const crypto = __importStar(__nccwpck_require__(69368)); -const oid_1 = __nccwpck_require__(91817); -const error_1 = __nccwpck_require__(97512); -const tstinfo_1 = __nccwpck_require__(62925); -const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2'; -const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4'; -const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4'; -class RFC3161Timestamp { - constructor(asn1) { - this.root = asn1; - } - static parse(der) { - const asn1 = asn1_1.ASN1Obj.parseBuffer(der); - return new RFC3161Timestamp(asn1); - } - get status() { - return this.pkiStatusInfoObj.subs[0].toInteger(); - } - get contentType() { - return this.contentTypeObj.toOID(); - } - get eContentType() { - return this.eContentTypeObj.toOID(); - } - get signingTime() { - return this.tstInfo.genTime; - } - get signerIssuer() { - return this.signerSidObj.subs[0].value; - } - get signerSerialNumber() { - return this.signerSidObj.subs[1].value; - } - get signerDigestAlgorithm() { - const oid = this.signerDigestAlgorithmObj.subs[0].toOID(); - return oid_1.SHA2_HASH_ALGOS[oid]; - } - get signatureAlgorithm() { - const oid = this.signatureAlgorithmObj.subs[0].toOID(); - return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; - } - get signatureValue() { - return this.signatureValueObj.value; - } - get tstInfo() { - // Need to unpack tstInfo from an OCTET STRING - return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]); - } - verify(data, publicKey) { - if (!this.timeStampTokenObj) { - throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing'); - } - // Check for expected ContentInfo content type - if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) { - throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`); - } - // Check for expected encapsulated content type - if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) { - throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`); - } - // Check that the tstInfo references the correct artifact - this.tstInfo.verify(data); - // Check that the signed message digest matches the tstInfo - this.verifyMessageDigest(); - // Check that the signature is valid for the signed attributes - this.verifySignature(publicKey); - } - verifyMessageDigest() { - // Check that the tstInfo matches the signed data - const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw); - const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value; - if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) { - throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo'); - } - } - verifySignature(key) { - // Encode the signed attributes for verification - const signedAttrs = this.signedAttrsObj.toDER(); - signedAttrs[0] = 0x31; // Change context-specific tag to SET - // Check that the signature is valid for the signed attributes - const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm); - if (!verified) { - throw new error_1.RFC3161TimestampVerificationError('signature verification failed'); - } - } - // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 - get pkiStatusInfoObj() { - // pkiStatusInfo is the first element of the timestamp response sequence - return this.root.subs[0]; - } - // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 - get timeStampTokenObj() { - // timeStampToken is the first element of the timestamp response sequence - return this.root.subs[1]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-3 - get contentTypeObj() { - return this.timeStampTokenObj.subs[0]; - } - // https://www.rfc-editor.org/rfc/rfc5652#section-3 - get signedDataObj() { - const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); - return obj.subs[0]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 - get encapContentInfoObj() { - return this.signedDataObj.subs[2]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 - get signerInfosObj() { - // SignerInfos is the last element of the signed data sequence - const sd = this.signedDataObj; - return sd.subs[sd.subs.length - 1]; - } - // https://www.rfc-editor.org/rfc/rfc5652#section-5.1 - get signerInfoObj() { - // Only supporting one signer - return this.signerInfosObj.subs[0]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 - get eContentTypeObj() { - return this.encapContentInfoObj.subs[0]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 - get eContentObj() { - return this.encapContentInfoObj.subs[1]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 - get signedAttrsObj() { - const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); - return signedAttrs; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 - get messageDigestAttributeObj() { - const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() && - sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY); - return messageDigest; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 - get signerSidObj() { - return this.signerInfoObj.subs[1]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 - get signerDigestAlgorithmObj() { - // Signature is the 2nd element of the signerInfoObj object - return this.signerInfoObj.subs[2]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 - get signatureAlgorithmObj() { - // Signature is the 4th element of the signerInfoObj object - return this.signerInfoObj.subs[4]; - } - // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 - get signatureValueObj() { - // Signature is the 6th element of the signerInfoObj object - return this.signerInfoObj.subs[5]; - } -} -exports.RFC3161Timestamp = RFC3161Timestamp; - - -/***/ }), - -/***/ 62925: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TSTInfo = void 0; -const crypto = __importStar(__nccwpck_require__(69368)); -const oid_1 = __nccwpck_require__(91817); -const error_1 = __nccwpck_require__(97512); -class TSTInfo { - constructor(asn1) { - this.root = asn1; - } - get version() { - return this.root.subs[0].toInteger(); - } - get genTime() { - return this.root.subs[4].toDate(); - } - get messageImprintHashAlgorithm() { - const oid = this.messageImprintObj.subs[0].subs[0].toOID(); - return oid_1.SHA2_HASH_ALGOS[oid]; - } - get messageImprintHashedMessage() { - return this.messageImprintObj.subs[1].value; - } - get raw() { - return this.root.toDER(); - } - verify(data) { - const digest = crypto.digest(this.messageImprintHashAlgorithm, data); - if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) { - throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact'); - } - } - // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 - get messageImprintObj() { - return this.root.subs[2]; - } -} -exports.TSTInfo = TSTInfo; - - -/***/ }), - -/***/ 1673: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ByteStream = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -class StreamError extends Error { -} -class ByteStream { - constructor(buffer) { - this.start = 0; - if (buffer) { - this.buf = buffer; - this.view = Buffer.from(buffer); - } - else { - this.buf = new ArrayBuffer(0); - this.view = Buffer.from(this.buf); - } - } - get buffer() { - return this.view.subarray(0, this.start); - } - get length() { - return this.view.byteLength; - } - get position() { - return this.start; - } - seek(position) { - this.start = position; - } - // Returns a Buffer containing the specified number of bytes starting at the - // given start position. - slice(start, len) { - const end = start + len; - if (end > this.length) { - throw new StreamError('request past end of buffer'); - } - return this.view.subarray(start, end); - } - appendChar(char) { - this.ensureCapacity(1); - this.view[this.start] = char; - this.start += 1; - } - appendUint16(num) { - this.ensureCapacity(2); - const value = new Uint16Array([num]); - const view = new Uint8Array(value.buffer); - this.view[this.start] = view[1]; - this.view[this.start + 1] = view[0]; - this.start += 2; - } - appendUint24(num) { - this.ensureCapacity(3); - const value = new Uint32Array([num]); - const view = new Uint8Array(value.buffer); - this.view[this.start] = view[2]; - this.view[this.start + 1] = view[1]; - this.view[this.start + 2] = view[0]; - this.start += 3; - } - appendView(view) { - this.ensureCapacity(view.length); - this.view.set(view, this.start); - this.start += view.length; - } - getBlock(size) { - if (size <= 0) { - return Buffer.alloc(0); - } - if (this.start + size > this.view.length) { - throw new Error('request past end of buffer'); - } - const result = this.view.subarray(this.start, this.start + size); - this.start += size; - return result; - } - getUint8() { - return this.getBlock(1)[0]; - } - getUint16() { - const block = this.getBlock(2); - return (block[0] << 8) | block[1]; - } - ensureCapacity(size) { - if (this.start + size > this.view.byteLength) { - const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0); - this.realloc(this.view.byteLength + blockSize); - } - } - realloc(size) { - const newArray = new ArrayBuffer(size); - const newView = Buffer.from(newArray); - // Copy the old buffer into the new one - newView.set(this.view); - this.buf = newArray; - this.view = newView; - } -} -exports.ByteStream = ByteStream; -ByteStream.BLOCK_SIZE = 1024; - - -/***/ }), - -/***/ 83566: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const asn1_1 = __nccwpck_require__(86027); -const crypto = __importStar(__nccwpck_require__(69368)); -const oid_1 = __nccwpck_require__(91817); -const pem = __importStar(__nccwpck_require__(1055)); -const ext_1 = __nccwpck_require__(96389); -const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14'; -const EXTENSION_OID_KEY_USAGE = '2.5.29.15'; -const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17'; -const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19'; -const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35'; -exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2'; -class X509Certificate { - constructor(asn1) { - this.root = asn1; - } - static parse(cert) { - const der = typeof cert === 'string' ? pem.toDER(cert) : cert; - const asn1 = asn1_1.ASN1Obj.parseBuffer(der); - return new X509Certificate(asn1); - } - get tbsCertificate() { - return this.tbsCertificateObj; - } - get version() { - // version number is the first element of the version context specific tag - const ver = this.versionObj.subs[0].toInteger(); - return `v${(ver + BigInt(1)).toString()}`; - } - get serialNumber() { - return this.serialNumberObj.value; - } - get notBefore() { - // notBefore is the first element of the validity sequence - return this.validityObj.subs[0].toDate(); - } - get notAfter() { - // notAfter is the second element of the validity sequence - return this.validityObj.subs[1].toDate(); - } - get issuer() { - return this.issuerObj.value; - } - get subject() { - return this.subjectObj.value; - } - get publicKey() { - return this.subjectPublicKeyInfoObj.toDER(); - } - get signatureAlgorithm() { - const oid = this.signatureAlgorithmObj.subs[0].toOID(); - return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; - } - get signatureValue() { - // Signature value is a bit string, so we need to skip the first byte - return this.signatureValueObj.value.subarray(1); - } - get subjectAltName() { - const ext = this.extSubjectAltName; - return ext?.uri || /* istanbul ignore next */ ext?.rfc822Name; - } - get extensions() { - // The extension list is the first (and only) element of the extensions - // context specific tag - /* istanbul ignore next */ - const extSeq = this.extensionsObj?.subs[0]; - /* istanbul ignore next */ - return extSeq?.subs || []; - } - get extKeyUsage() { - const ext = this.findExtension(EXTENSION_OID_KEY_USAGE); - return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined; - } - get extBasicConstraints() { - const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS); - return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined; - } - get extSubjectAltName() { - const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME); - return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined; - } - get extAuthorityKeyID() { - const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID); - return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined; - } - get extSubjectKeyID() { - const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID); - return ext - ? new ext_1.X509SubjectKeyIDExtension(ext) - : /* istanbul ignore next */ undefined; - } - get extSCT() { - const ext = this.findExtension(exports.EXTENSION_OID_SCT); - return ext ? new ext_1.X509SCTExtension(ext) : undefined; - } - get isCA() { - const ca = this.extBasicConstraints?.isCA || false; - // If the KeyUsage extension is present, keyCertSign must be set - if (this.extKeyUsage) { - return ca && this.extKeyUsage.keyCertSign; - } - // TODO: test coverage for this case - /* istanbul ignore next */ - return ca; - } - extension(oid) { - const ext = this.findExtension(oid); - return ext ? new ext_1.X509Extension(ext) : undefined; - } - verify(issuerCertificate) { - // Use the issuer's public key if provided, otherwise use the subject's - const publicKey = issuerCertificate?.publicKey || this.publicKey; - const key = crypto.createPublicKey(publicKey); - return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm); - } - validForDate(date) { - return this.notBefore <= date && date <= this.notAfter; - } - equals(other) { - return this.root.toDER().equals(other.root.toDER()); - } - // Creates a copy of the certificate with a new buffer - clone() { - const der = this.root.toDER(); - const clone = Buffer.alloc(der.length); - der.copy(clone); - return X509Certificate.parse(clone); - } - findExtension(oid) { - // Find the extension with the given OID. The OID will always be the first - // element of the extension sequence - return this.extensions.find((ext) => ext.subs[0].toOID() === oid); - } - ///////////////////////////////////////////////////////////////////////////// - // The following properties use the documented x509 structure to locate the - // desired ASN.1 object - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1 - get tbsCertificateObj() { - // tbsCertificate is the first element of the certificate sequence - return this.root.subs[0]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2 - get signatureAlgorithmObj() { - // signatureAlgorithm is the second element of the certificate sequence - return this.root.subs[1]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3 - get signatureValueObj() { - // signatureValue is the third element of the certificate sequence - return this.root.subs[2]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1 - get versionObj() { - // version is the first element of the tbsCertificate sequence - return this.tbsCertificateObj.subs[0]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2 - get serialNumberObj() { - // serialNumber is the second element of the tbsCertificate sequence - return this.tbsCertificateObj.subs[1]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4 - get issuerObj() { - // issuer is the fourth element of the tbsCertificate sequence - return this.tbsCertificateObj.subs[3]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5 - get validityObj() { - // version is the fifth element of the tbsCertificate sequence - return this.tbsCertificateObj.subs[4]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6 - get subjectObj() { - // subject is the sixth element of the tbsCertificate sequence - return this.tbsCertificateObj.subs[5]; - } - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7 - get subjectPublicKeyInfoObj() { - // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence - return this.tbsCertificateObj.subs[6]; - } - // Extensions can't be located by index because their position varies. Instead, - // we need to find the extensions context specific tag - // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9 - get extensionsObj() { - return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03)); - } -} -exports.X509Certificate = X509Certificate; - - -/***/ }), - -/***/ 96389: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0; -const stream_1 = __nccwpck_require__(1673); -const sct_1 = __nccwpck_require__(6144); -// https://www.rfc-editor.org/rfc/rfc5280#section-4.1 -class X509Extension { - constructor(asn1) { - this.root = asn1; - } - get oid() { - return this.root.subs[0].toOID(); - } - get critical() { - // The critical field is optional and will be the second element of the - // extension sequence if present. Default to false if not present. - return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false; - } - get value() { - return this.extnValueObj.value; - } - get valueObj() { - return this.extnValueObj; - } - get extnValueObj() { - // The extnValue field will be the last element of the extension sequence - return this.root.subs[this.root.subs.length - 1]; - } -} -exports.X509Extension = X509Extension; -// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9 -class X509BasicConstraintsExtension extends X509Extension { - get isCA() { - return this.sequence.subs[0]?.toBoolean() ?? false; - } - get pathLenConstraint() { - return this.sequence.subs.length > 1 - ? this.sequence.subs[1].toInteger() - : undefined; - } - // The extnValue field contains a single sequence wrapping the isCA and - // pathLenConstraint. - get sequence() { - return this.extnValueObj.subs[0]; - } -} -exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension; -// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3 -class X509KeyUsageExtension extends X509Extension { - get digitalSignature() { - return this.bitString[0] === 1; - } - get keyCertSign() { - return this.bitString[5] === 1; - } - get crlSign() { - return this.bitString[6] === 1; - } - // The extnValue field contains a single bit string which is a bit mask - // indicating which key usages are enabled. - get bitString() { - return this.extnValueObj.subs[0].toBitString(); - } -} -exports.X509KeyUsageExtension = X509KeyUsageExtension; -// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6 -class X509SubjectAlternativeNameExtension extends X509Extension { - get rfc822Name() { - return this.findGeneralName(0x01)?.value.toString('ascii'); - } - get uri() { - return this.findGeneralName(0x06)?.value.toString('ascii'); - } - // Retrieve the value of an otherName with the given OID. - otherName(oid) { - const otherName = this.findGeneralName(0x00); - if (otherName === undefined) { - return undefined; - } - // The otherName is a sequence containing an OID and a value. - // Need to check that the OID matches the one we're looking for. - const otherNameOID = otherName.subs[0].toOID(); - if (otherNameOID !== oid) { - return undefined; - } - // The otherNameValue is a sequence containing the actual value. - const otherNameValue = otherName.subs[1]; - return otherNameValue.subs[0].value.toString('ascii'); - } - findGeneralName(tag) { - return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag)); - } - // The extnValue field contains a sequence of GeneralNames. - get generalNames() { - return this.extnValueObj.subs[0].subs; - } -} -exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension; -// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1 -class X509AuthorityKeyIDExtension extends X509Extension { - get keyIdentifier() { - return this.findSequenceMember(0x00)?.value; - } - findSequenceMember(tag) { - return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag)); - } - // The extnValue field contains a single sequence wrapping the keyIdentifier - get sequence() { - return this.extnValueObj.subs[0]; - } -} -exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension; -// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2 -class X509SubjectKeyIDExtension extends X509Extension { - get keyIdentifier() { - return this.extnValueObj.subs[0].value; - } -} -exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension; -// https://www.rfc-editor.org/rfc/rfc6962#section-3.3 -class X509SCTExtension extends X509Extension { - constructor(asn1) { - super(asn1); - } - get signedCertificateTimestamps() { - const buf = this.extnValueObj.subs[0].value; - const stream = new stream_1.ByteStream(buf); - // The overall list length is encoded in the first two bytes -- note this - // is the length of the list in bytes, NOT the number of SCTs in the list - const end = stream.getUint16() + 2; - const sctList = []; - while (stream.position < end) { - // Read the length of the next SCT - const sctLength = stream.getUint16(); - // Slice out the bytes for the next SCT and parse it - const sct = stream.getBlock(sctLength); - sctList.push(sct_1.SignedCertificateTimestamp.parse(sct)); - } - if (stream.position !== end) { - throw new Error('SCT list length does not match actual length'); - } - return sctList; - } -} -exports.X509SCTExtension = X509SCTExtension; - - -/***/ }), - -/***/ 49358: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; -var cert_1 = __nccwpck_require__(83566); -Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return cert_1.EXTENSION_OID_SCT; } })); -Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return cert_1.X509Certificate; } })); -var ext_1 = __nccwpck_require__(96389); -Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return ext_1.X509SCTExtension; } })); - - -/***/ }), - -/***/ 6144: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SignedCertificateTimestamp = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const crypto = __importStar(__nccwpck_require__(69368)); -const stream_1 = __nccwpck_require__(1673); -class SignedCertificateTimestamp { - constructor(options) { - this.version = options.version; - this.logID = options.logID; - this.timestamp = options.timestamp; - this.extensions = options.extensions; - this.hashAlgorithm = options.hashAlgorithm; - this.signatureAlgorithm = options.signatureAlgorithm; - this.signature = options.signature; - } - get datetime() { - return new Date(Number(this.timestamp.readBigInt64BE())); - } - // Returns the hash algorithm used to generate the SCT's signature. - // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 - get algorithm() { - switch (this.hashAlgorithm) { - /* istanbul ignore next */ - case 0: - return 'none'; - /* istanbul ignore next */ - case 1: - return 'md5'; - /* istanbul ignore next */ - case 2: - return 'sha1'; - /* istanbul ignore next */ - case 3: - return 'sha224'; - case 4: - return 'sha256'; - /* istanbul ignore next */ - case 5: - return 'sha384'; - /* istanbul ignore next */ - case 6: - return 'sha512'; - /* istanbul ignore next */ - default: - return 'unknown'; - } - } - verify(preCert, key) { - // Assemble the digitally-signed struct (the data over which the signature - // was generated). - // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 - const stream = new stream_1.ByteStream(); - stream.appendChar(this.version); - stream.appendChar(0x00); // SignatureType = certificate_timestamp(0) - stream.appendView(this.timestamp); - stream.appendUint16(0x01); // LogEntryType = precert_entry(1) - stream.appendView(preCert); - stream.appendUint16(this.extensions.byteLength); - /* istanbul ignore next - extensions are very uncommon */ - if (this.extensions.byteLength > 0) { - stream.appendView(this.extensions); - } - return crypto.verify(stream.buffer, key, this.signature, this.algorithm); - } - // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using - // TLS encoding which means the fields and lengths of most fields are - // specified as part of the SCT and TLS specs. - // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 - // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 - static parse(buf) { - const stream = new stream_1.ByteStream(buf); - // Version - enum { v1(0), (255) } - const version = stream.getUint8(); - // Log ID - struct { opaque key_id[32]; } - const logID = stream.getBlock(32); - // Timestamp - uint64 - const timestamp = stream.getBlock(8); - // Extensions - opaque extensions<0..2^16-1>; - const extenstionLength = stream.getUint16(); - const extensions = stream.getBlock(extenstionLength); - // Hash algo - enum { sha256(4), . . . (255) } - const hashAlgorithm = stream.getUint8(); - // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } - const signatureAlgorithm = stream.getUint8(); - // Signature - opaque signature<0..2^16-1>; - const sigLength = stream.getUint16(); - const signature = stream.getBlock(sigLength); - // Check that we read the entire buffer - if (stream.position !== buf.length) { - throw new Error('SCT buffer length mismatch'); - } - return new SignedCertificateTimestamp({ - version, - logID, - timestamp, - extensions, - hashAlgorithm, - signatureAlgorithm, - signature, - }); - } -} -exports.SignedCertificateTimestamp = SignedCertificateTimestamp; - - -/***/ }), - -/***/ 23688: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HEADER_OCI_SUBJECT = exports.HEADER_LOCATION = exports.HEADER_IF_MATCH = exports.HEADER_ETAG = exports.HEADER_DIGEST = exports.HEADER_CONTENT_TYPE = exports.HEADER_CONTENT_LENGTH = exports.HEADER_AUTHORIZATION = exports.HEADER_AUTHENTICATE = exports.HEADER_API_VERSION = exports.HEADER_ACCEPT = exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = exports.CONTENT_TYPE_OCTET_STREAM = exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = exports.CONTENT_TYPE_DOCKER_MANIFEST = exports.CONTENT_TYPE_OCI_MANIFEST = exports.CONTENT_TYPE_OCI_INDEX = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -exports.CONTENT_TYPE_OCI_INDEX = 'application/vnd.oci.image.index.v1+json'; -exports.CONTENT_TYPE_OCI_MANIFEST = 'application/vnd.oci.image.manifest.v1+json'; -exports.CONTENT_TYPE_DOCKER_MANIFEST = 'application/vnd.docker.distribution.manifest.v2+json'; -exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = 'application/vnd.docker.distribution.manifest.list.v2+json'; -exports.CONTENT_TYPE_OCTET_STREAM = 'application/octet-stream'; -exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = 'application/vnd.oci.empty.v1+json'; -exports.HEADER_ACCEPT = 'Accept'; -exports.HEADER_API_VERSION = 'Docker-Distribution-API-Version'; -exports.HEADER_AUTHENTICATE = 'WWW-Authenticate'; -exports.HEADER_AUTHORIZATION = 'Authorization'; -exports.HEADER_CONTENT_LENGTH = 'Content-Length'; -exports.HEADER_CONTENT_TYPE = 'Content-Type'; -exports.HEADER_DIGEST = 'Docker-Content-Digest'; -exports.HEADER_ETAG = 'Etag'; -exports.HEADER_IF_MATCH = 'If-Match'; -exports.HEADER_LOCATION = 'Location'; -exports.HEADER_OCI_SUBJECT = 'OCI-Subject'; - - -/***/ }), - -/***/ 62691: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromBasicAuth = exports.toBasicAuth = exports.getRegistryCredentials = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const node_fs_1 = __importDefault(__nccwpck_require__(73024)); -const node_os_1 = __importDefault(__nccwpck_require__(48161)); -const node_path_1 = __importDefault(__nccwpck_require__(76760)); -const name_1 = __nccwpck_require__(96666); -// Returns the credentials for a given registry by reading the Docker config -// file. -const getRegistryCredentials = (imageName) => { - const { registry } = (0, name_1.parseImageName)(imageName); - const dockerConfigFile = node_path_1.default.join(node_os_1.default.homedir(), '.docker', 'config.json'); - let content; - try { - content = node_fs_1.default.readFileSync(dockerConfigFile, 'utf8'); - } - catch (err) { - throw new Error(`No credential file found at ${dockerConfigFile}`); - } - const dockerConfig = JSON.parse(content); - const credKey = Object.keys(dockerConfig.auths || {}).find((key) => key.includes(registry)) || registry; - const creds = dockerConfig.auths?.[credKey]; - if (!creds) { - throw new Error(`No credentials found for registry ${registry}`); - } - // Extract username/password from auth string - const { username, password } = (0, exports.fromBasicAuth)(creds.auth); - // If the identitytoken is present, use it as the password (primarily for ACR) - const pass = creds.identitytoken ? creds.identitytoken : password; - return { username, password: pass }; -}; -exports.getRegistryCredentials = getRegistryCredentials; -// Encode the username and password as base64-encoded basicauth value -const toBasicAuth = (creds) => Buffer.from(`${creds.username}:${creds.password}`).toString('base64'); -exports.toBasicAuth = toBasicAuth; -// Decode the base64-encoded basicauth value -const fromBasicAuth = (auth) => { - // Need to account for the possibility of ':' in the password - const [username, ...rest] = Buffer.from(auth, 'base64').toString().split(':'); - const password = rest.join(':'); - return { username, password }; -}; -exports.fromBasicAuth = fromBasicAuth; - - -/***/ }), - -/***/ 46803: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OCIError = exports.ensureStatus = exports.HTTPError = void 0; -class HTTPError extends Error { - constructor({ status, message }) { - super(message); - this.statusCode = status; - } -} -exports.HTTPError = HTTPError; -// Inspects the response status and throws an HTTPError if it does not match the -// expected status code -const ensureStatus = (expectedStatus) => { - return (response) => { - if (response.status !== expectedStatus) { - throw new HTTPError({ - message: `Error fetching ${response.url} - expected ${expectedStatus}, received ${response.status}`, - status: response.status, - }); - } - return response; - }; -}; -exports.ensureStatus = ensureStatus; -class OCIError extends Error { - constructor({ message, cause, }) { - super(message); - this.cause = cause; - this.name = this.constructor.name; - } -} -exports.OCIError = OCIError; - - -/***/ }), - -/***/ 32721: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* -Copyright 2024 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const http2_1 = __nccwpck_require__(85675); -const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310)); -const proc_log_1 = __nccwpck_require__(26687); -const promise_retry_1 = __importDefault(__nccwpck_require__(90390)); -const { HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants; -const fetchWithRetry = async (url, options = {}) => { - return (0, promise_retry_1.default)(async (retry, attemptNum) => { - /* eslint-disable @typescript-eslint/no-explicit-any */ - const logRetry = (reason) => { - proc_log_1.log.http('fetch', `${options.method} ${url} attempt ${attemptNum} failed with ${reason}`); - }; - const response = await (0, make_fetch_happen_1.default)(url, { - ...options, - retry: false, // We're handling retries ourselves - }).catch((reason) => { - logRetry(reason); - return retry(reason); - }); - if (retryable(response.status)) { - logRetry(response.status); - return retry(response); - } - return response; - }, retryOpts(options.retry)).catch((err) => { - // If we got an actual error, throw it - if (err instanceof Error) { - throw err; - } - // Otherwise, return the response (this is simply a retry-able response for - // which we exceeded the retry limit) - return err; - }); -}; -// Returns a wrapped fetch function with default options -fetchWithRetry.defaults = (defaultOptions = {}, wrappedFetch = fetchWithRetry) => { - const defaultedFetch = (url, options = {}) => { - const finalOptions = { - ...defaultOptions, - ...options, - headers: { ...defaultOptions.headers, ...options.headers }, - }; - return wrappedFetch(url, finalOptions); - }; - defaultedFetch.defaults = (newDefaults = {}) => fetchWithRetry.defaults(newDefaults, defaultedFetch); - return defaultedFetch; -}; -// Determine if a status code is retryable. This includes 5xx errors, 408, and -// 429. -const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR; -// Normalize the retry options to the format expected by promise-retry -const retryOpts = (retry) => { - if (typeof retry === 'boolean') { - return { retries: retry ? 1 : 0 }; - } - else if (typeof retry === 'number') { - return { retries: retry }; - } - else { - return { retries: 0, ...retry }; - } -}; -exports["default"] = fetchWithRetry; - - -/***/ }), - -/***/ 19812: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _OCIImage_instances, _OCIImage_client, _OCIImage_credentials, _OCIImage_createReferrersIndexByTag; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OCIImage = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const constants_1 = __nccwpck_require__(23688); -const error_1 = __nccwpck_require__(46803); -const registry_1 = __nccwpck_require__(22138); -const DOCKER_DEFAULT_REGISTRY = 'registry-1.docker.io'; -const EMPTY_BLOB = Buffer.from('{}'); -class OCIImage { - constructor(image, creds, opts) { - _OCIImage_instances.add(this); - _OCIImage_client.set(this, void 0); - _OCIImage_credentials.set(this, void 0); - __classPrivateFieldSet(this, _OCIImage_client, new registry_1.RegistryClient(canonicalizeRegistryName(image.registry), image.path, opts), "f"); - __classPrivateFieldSet(this, _OCIImage_credentials, creds, "f"); - } - async addArtifact(opts) { - let artifactDescriptor; - const annotations = { - 'org.opencontainers.image.created': new Date().toISOString(), - ...opts.annotations, - }; - try { - if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) { - await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f")); - } - // Check that the image exists - const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(opts.imageDigest); - // Upload the artifact blob - const artifactBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(opts.artifact); - // Upload the empty blob (needed for the manifest config) - const emptyBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(EMPTY_BLOB); - // Construct artifact manifest - const manifest = buildManifest({ - artifactDescriptor: { ...artifactBlob, mediaType: opts.mediaType }, - subjectDescriptor: imageDescriptor, - configDescriptor: { - ...emptyBlob, - mediaType: constants_1.CONTENT_TYPE_EMPTY_DESCRIPTOR, - }, - annotations, - }); - // Upload artifact manifest - artifactDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(manifest)); - // Check to see if registry supports the referrers API. For most - // registries the presence of a subjectDigest response header when - // uploading the artifact manifest indicates that the referrers API IS - // supported -- however, this is not a guarantee (AWS ECR does NOT support - // the referrers API but still reports a subjectDigest). - const referrersSupported = await __classPrivateFieldGet(this, _OCIImage_client, "f").pingReferrers(); - // Manually update the referrers list if the referrers API is not supported. - if (!artifactDescriptor.subjectDigest || !referrersSupported) { - // Strip subjectDigest from the artifact descriptor (in case it was returned) - /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ - const { subjectDigest, ...descriptor } = artifactDescriptor; - await __classPrivateFieldGet(this, _OCIImage_instances, "m", _OCIImage_createReferrersIndexByTag).call(this, { - artifact: { - ...descriptor, - artifactType: opts.mediaType, - annotations, - }, - imageDigest: opts.imageDigest, - }); - } - } - catch (err) { - throw new error_1.OCIError({ - message: `Error uploading artifact to container registry`, - cause: err, - }); - } - return artifactDescriptor; - } - async getDigest(tag) { - try { - if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) { - await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f")); - } - const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(tag); - return imageDescriptor.digest; - } - catch (err) { - throw new error_1.OCIError({ - message: `Error retrieving image digest from container registry`, - cause: err, - }); - } - } -} -exports.OCIImage = OCIImage; -_OCIImage_client = new WeakMap(), _OCIImage_credentials = new WeakMap(), _OCIImage_instances = new WeakSet(), _OCIImage_createReferrersIndexByTag = -// Create a referrers index by tag. This is a fallback for registries that do -// not support the referrers API. -// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests-with-subject -async function _OCIImage_createReferrersIndexByTag(opts) { - const referrerTag = digestToTag(opts.imageDigest); - let referrerManifest; - let etag; - try { - // Retrieve any existing referrer index - const referrerIndex = await __classPrivateFieldGet(this, _OCIImage_client, "f").getManifest(referrerTag); - if (referrerIndex.mediaType !== constants_1.CONTENT_TYPE_OCI_INDEX) { - throw new Error(`Expected referrer manifest type ${constants_1.CONTENT_TYPE_OCI_INDEX}, got ${referrerIndex.mediaType}`); - } - referrerManifest = referrerIndex.body; - etag = referrerIndex.etag; - } - catch (err) { - // If the referrer index does not exist, create a new one - if (err instanceof error_1.HTTPError && err.statusCode === 404) { - referrerManifest = newIndex(); - } - else { - throw err; - } - } - // If the artifact is not already in the index, add it to the list and - // re-upload the index - if (!referrerManifest.manifests.some((manifest) => manifest.digest === opts.artifact.digest)) { - // Add the artifact to the index - referrerManifest.manifests.push(opts.artifact); - await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(referrerManifest), { - mediaType: constants_1.CONTENT_TYPE_OCI_INDEX, - reference: referrerTag, - etag, - }); - } -}; -// Build an OCI manifest document with references to the given artifact, -// subject, and config -const buildManifest = (opts) => ({ - schemaVersion: 2, - mediaType: constants_1.CONTENT_TYPE_OCI_MANIFEST, - artifactType: opts.artifactDescriptor.mediaType, - config: opts.configDescriptor, - layers: [opts.artifactDescriptor], - subject: opts.subjectDescriptor, - annotations: opts.annotations, -}); -// Return an empty OCI index document -const newIndex = () => ({ - mediaType: constants_1.CONTENT_TYPE_OCI_INDEX, - schemaVersion: 2, - manifests: [], -}); -// Convert an image digest to a tag per the Referrers Tag Schema -// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#referrers-tag-schema -const digestToTag = (digest) => { - return digest.replace(':', '-'); -}; -// Canonicalize the registry name to match the format used by the registry -// client. This is used primarily to handle the special case of the Docker Hub -// registry. -// https://github.com/moby/moby/blob/v24.0.2/registry/config.go#L25-L48 -const canonicalizeRegistryName = (registry) => { - return registry.endsWith('docker.io') ? DOCKER_DEFAULT_REGISTRY : registry; -}; - - -/***/ }), - -/***/ 81057: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getImageDigest = exports.attachArtifactToImage = exports.OCIError = exports.getRegistryCredentials = void 0; -const image_1 = __nccwpck_require__(19812); -const name_1 = __nccwpck_require__(96666); -var credentials_1 = __nccwpck_require__(62691); -Object.defineProperty(exports, "getRegistryCredentials", ({ enumerable: true, get: function () { return credentials_1.getRegistryCredentials; } })); -var error_1 = __nccwpck_require__(46803); -Object.defineProperty(exports, "OCIError", ({ enumerable: true, get: function () { return error_1.OCIError; } })); -// Associates the given artifact with an OCI image. The artifact is identified -// by its media type and a buffer containing the artifact. The image is -// identified by its FQDN and digest. -const attachArtifactToImage = async (opts) => { - const image = (0, name_1.parseImageName)(opts.imageName); - return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).addArtifact(opts); -}; -exports.attachArtifactToImage = attachArtifactToImage; -// Returns the digest of the given image tag in the remote registry. -const getImageDigest = async (opts) => { - const image = (0, name_1.parseImageName)(opts.imageName); - return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).getDigest(opts.imageTag); -}; -exports.getImageDigest = getImageDigest; - - -/***/ }), - -/***/ 96666: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseImageName = void 0; -const expression = (...res) => res.join(''); -const group = (...res) => `(?:${expression(...res)})`; -const repeated = (...res) => `${group(expression(...res))}+`; -const optional = (...res) => `${group(expression(...res))}?`; -const capture = (...res) => `(${expression(...res)})`; -const anchored = (...res) => `^${expression(...res)}$`; -// Lower case letters, numbers -const ALPHA_NUMERIC_RE = '[a-z0-9]+'; -// Separators allowed to be embedded in name components. This allows one period, -// one or two underscore or multiple dashes. -const SEPARATOR_RE = group('\\.|_|__|-+'); -// Registry path component names to start with at least one letter or number, -// with following parts able to be separated by one period, one or two -// underscores or multiple dashes. -const NAME_COMPONENT_RE = expression(ALPHA_NUMERIC_RE, optional(repeated(SEPARATOR_RE, ALPHA_NUMERIC_RE))); -const NAME_RE = expression(NAME_COMPONENT_RE, repeated(optional('\\/', NAME_COMPONENT_RE))); -// Component of the registry domain must be at least one letter or number, with -// following parts able to be separated by a dash. -const DOMAIN_COMPONENT_RE = group('[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]'); -// Restricts the registry domain to be one or more period separated components -// followed by an optional port. -const DOMAIN_RE = expression(DOMAIN_COMPONENT_RE, optional(repeated('\\.', DOMAIN_COMPONENT_RE)), optional(':[0-9]+')); -// Capture the registry domain and path components of a repository name. -const ANCHORED_NAME_RE = anchored(capture(DOMAIN_RE), '\\/', capture(NAME_RE)); -// Parses a fully qualified image name into its registry and path components. -const parseImageName = (image) => { - const matches = image.match(ANCHORED_NAME_RE); - if (!matches) { - throw new Error(`Invalid image name: ${image}`); - } - return { - registry: matches[1], - path: matches[2], - }; -}; -exports.parseImageName = parseImageName; - - -/***/ }), - -/***/ 22138: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var _RegistryClient_instances, _RegistryClient_baseURL, _RegistryClient_repository, _RegistryClient_fetch, _RegistryClient_fetchDistributionToken, _RegistryClient_fetchOAuth2Token; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RegistryClient = exports.ZERO_DIGEST = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const node_crypto_1 = __importDefault(__nccwpck_require__(77598)); -const constants_1 = __nccwpck_require__(23688); -const credentials_1 = __nccwpck_require__(62691); -const error_1 = __nccwpck_require__(46803); -const fetch_1 = __importDefault(__nccwpck_require__(32721)); -const ALL_MANIFEST_MEDIA_TYPES = [ - constants_1.CONTENT_TYPE_OCI_INDEX, - constants_1.CONTENT_TYPE_OCI_MANIFEST, - constants_1.CONTENT_TYPE_DOCKER_MANIFEST, - constants_1.CONTENT_TYPE_DOCKER_MANIFEST_LIST, -].join(','); -exports.ZERO_DIGEST = 'sha256:0000000000000000000000000000000000000000000000000000000000000000'; -class RegistryClient { - constructor(registry, repository, opts) { - _RegistryClient_instances.add(this); - _RegistryClient_baseURL.set(this, void 0); - _RegistryClient_repository.set(this, void 0); - _RegistryClient_fetch.set(this, void 0); - __classPrivateFieldSet(this, _RegistryClient_repository, repository, "f"); - __classPrivateFieldSet(this, _RegistryClient_fetch, fetch_1.default.defaults(opts), "f"); - // Use http for localhost registries, https otherwise - const hostname = new URL(`http://${registry}`).hostname; - /* istanbul ignore next */ - const protocol = hostname === 'localhost' || hostname === '127.0.0.1' ? 'http' : 'https'; - __classPrivateFieldSet(this, _RegistryClient_baseURL, `${protocol}://${registry}`, "f"); - } - // Authenticate with the registry. Sends an unauthenticated request to the - // registry in order to get an auth challenge. If the challenge scheme is - // "basic" we don't need a token and can authenticate requests using basic - // auth. Otherwise, we fetch a token from the auth server and use that to - // authenticate requests. - // https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md#the-registry - async signIn(creds) { - // Initiate a blob upload to get the auth challenge - const probeResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' }); - // If we get a 200 response, we're already authenticated - if (probeResponse.status === 200) { - return; - } - const authHeader = probeResponse.headers.get(constants_1.HEADER_AUTHENTICATE) || - /* istanbul ignore next */ ''; - const challenge = parseChallenge(authHeader); - // If the challenge scheme is "basic" we don't need a token and can - // authenticate requests using basic auth - if (challenge.scheme === 'basic') { - const basicAuth = (0, credentials_1.toBasicAuth)(creds); - __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({ - headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` }, - }), "f"); - return; - } - let token; - if (creds.username === '') { - // If the OAUth2 token request fails, try to fetch a distribution token - token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchOAuth2Token).call(this, creds, challenge).catch(() => undefined); - } - if (!token) { - token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchDistributionToken).call(this, creds, challenge); - } - // Ensure the token is sent with all future requests - __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({ - headers: { [constants_1.HEADER_AUTHORIZATION]: `Bearer ${token}` }, - }), "f"); - } - // Check the registry API version - async checkVersion() { - const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/`); - return response.headers.get(constants_1.HEADER_API_VERSION) || ''; - } - // Upload a blob to the registry using the post/put method. Calculates the - // digest of the blob and checks to make sure the blob doesn't already exist - // in the registry before uploading. - async uploadBlob(blob) { - const digest = RegistryClient.digest(blob); - const size = blob.length; - // Check if blob already exists - const headResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/${digest}`, { method: 'HEAD', redirect: 'follow' }); - if (headResponse.status === 200) { - return { - mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM, - digest, - size, - }; - } - // Retrieve upload location (session ID) - const postResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' }).then((0, error_1.ensureStatus)(202)); - const location = postResponse.headers.get(constants_1.HEADER_LOCATION); - if (!location) { - throw new Error('Missing location for blob upload'); - } - // Translate location to a full URL - const uploadLocation = new URL(location.startsWith('/') ? `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}${location}` : location); - // Add digest to query string - uploadLocation.searchParams.set('digest', digest); - // Upload blob - await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, uploadLocation.href, { - method: 'PUT', - body: blob, - headers: { [constants_1.HEADER_CONTENT_TYPE]: constants_1.CONTENT_TYPE_OCTET_STREAM }, - }).then((0, error_1.ensureStatus)(201)); - return { mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM, digest, size }; - } - // Checks for the existence of a manifest by reference - async checkManifest(reference) { - const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { - method: 'HEAD', - headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES }, - }).then((0, error_1.ensureStatus)(200)); - const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) || - /* istanbul ignore next */ ''; - const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ ''; - const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) || - /* istanbul ignore next */ 0; - return { mediaType, digest, size }; - } - // Retrieves a manifest by reference - async getManifest(reference) { - const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { - headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES }, - }).then((0, error_1.ensureStatus)(200)); - const body = await response.json(); - const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) || - /* istanbul ignore next */ ''; - const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ ''; - const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) || 0; - const etag = response.headers.get(constants_1.HEADER_ETAG) || undefined; - return { body, mediaType, digest, size, etag }; - } - // Uploads a manifest by digest. If specified, the reference will be used as - // the manifest tag. - async uploadManifest(manifest, options = {}) { - const digest = RegistryClient.digest(manifest); - const reference = options.reference || digest; - const contentType = options.mediaType || constants_1.CONTENT_TYPE_OCI_MANIFEST; - const headers = { [constants_1.HEADER_CONTENT_TYPE]: contentType }; - if (options.etag) { - headers[constants_1.HEADER_IF_MATCH] = options.etag; - } - const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { method: 'PUT', body: manifest, headers }).then((0, error_1.ensureStatus)(201)); - const subjectDigest = response.headers.get(constants_1.HEADER_OCI_SUBJECT) || undefined; - return { - mediaType: contentType, - digest, - size: manifest.length, - subjectDigest, - }; - } - // Returns true if the registry supports the referrers API - async pingReferrers() { - const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/referrers/${exports.ZERO_DIGEST}`); - return response.status === 200; - } - static digest(blob) { - const hash = node_crypto_1.default.createHash('sha256'); - hash.update(blob); - return `sha256:${hash.digest('hex')}`; - } -} -exports.RegistryClient = RegistryClient; -_RegistryClient_baseURL = new WeakMap(), _RegistryClient_repository = new WeakMap(), _RegistryClient_fetch = new WeakMap(), _RegistryClient_instances = new WeakSet(), _RegistryClient_fetchDistributionToken = async function _RegistryClient_fetchDistributionToken(creds, challenge) { - const basicAuth = (0, credentials_1.toBasicAuth)(creds); - const authURL = new URL(challenge.realm); - authURL.searchParams.set('service', challenge.service); - authURL.searchParams.set('scope', challenge.scope); - // Make token request with basic auth - const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, authURL.toString(), { - headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` }, - }).then((0, error_1.ensureStatus)(200)); - return tokenResponse.json().then((json) => json.access_token || json.token); -}, _RegistryClient_fetchOAuth2Token = async function _RegistryClient_fetchOAuth2Token(creds, challenge) { - const body = new URLSearchParams({ - service: challenge.service, - scope: challenge.scope, - username: creds.username, - password: creds.password, - grant_type: 'password', - }); - // Make OAuth token request - const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, challenge.realm, { - method: 'POST', - body, - }).then((0, error_1.ensureStatus)(200)); - return tokenResponse.json().then((json) => json.access_token); -}; -// Parses an auth challenge header into its components -// https://datatracker.ietf.org/doc/html/rfc7235#section-4.1 -function parseChallenge(challenge) { - // Account for the possibility of spaces in the auth params - const [scheme, ...rest] = challenge.split(' '); - const authParams = rest.join(' '); - if (!['Basic', 'Bearer'].includes(scheme)) { - throw new Error(`Invalid challenge: ${challenge}`); - } - return { - scheme: scheme.toLocaleLowerCase(), - realm: singleMatch(authParams, /realm="(.+?)"/), - service: singleMatch(authParams, /service="(.+?)"/), - scope: singleMatch(authParams, /scope="(.+?)"/), - }; -} -// Returns the first capture group of a regex match, or an empty string -const singleMatch = (str, regex) => str.match(regex)?.[1] || ''; - - -/***/ }), - -/***/ 47030: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* eslint-disable */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Signature = exports.Envelope = void 0; -function createBaseEnvelope() { - return { payload: Buffer.alloc(0), payloadType: "", signatures: [] }; -} -exports.Envelope = { - fromJSON(object) { - return { - payload: isSet(object.payload) ? Buffer.from(bytesFromBase64(object.payload)) : Buffer.alloc(0), - payloadType: isSet(object.payloadType) ? String(object.payloadType) : "", - signatures: Array.isArray(object?.signatures) ? object.signatures.map((e) => exports.Signature.fromJSON(e)) : [], - }; - }, - toJSON(message) { - const obj = {}; - message.payload !== undefined && - (obj.payload = base64FromBytes(message.payload !== undefined ? message.payload : Buffer.alloc(0))); - message.payloadType !== undefined && (obj.payloadType = message.payloadType); - if (message.signatures) { - obj.signatures = message.signatures.map((e) => e ? exports.Signature.toJSON(e) : undefined); - } - else { - obj.signatures = []; - } - return obj; - }, -}; -function createBaseSignature() { - return { sig: Buffer.alloc(0), keyid: "" }; -} -exports.Signature = { - fromJSON(object) { - return { - sig: isSet(object.sig) ? Buffer.from(bytesFromBase64(object.sig)) : Buffer.alloc(0), - keyid: isSet(object.keyid) ? String(object.keyid) : "", - }; - }, - toJSON(message) { - const obj = {}; - message.sig !== undefined && (obj.sig = base64FromBytes(message.sig !== undefined ? message.sig : Buffer.alloc(0))); - message.keyid !== undefined && (obj.keyid = message.keyid); - return obj; - }, -}; -var tsProtoGlobalThis = (() => { - if (typeof globalThis !== "undefined") { - return globalThis; - } - if (typeof self !== "undefined") { - return self; - } - if (typeof window !== "undefined") { - return window; - } - if (typeof global !== "undefined") { - return global; - } - throw "Unable to locate global object"; -})(); -function bytesFromBase64(b64) { - if (tsProtoGlobalThis.Buffer) { - return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); - } - else { - const bin = tsProtoGlobalThis.atob(b64); - const arr = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; ++i) { - arr[i] = bin.charCodeAt(i); - } - return arr; - } -} -function base64FromBytes(arr) { - if (tsProtoGlobalThis.Buffer) { - return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); - } - else { - const bin = []; - arr.forEach((byte) => { - bin.push(String.fromCharCode(byte)); - }); - return tsProtoGlobalThis.btoa(bin.join("")); - } -} -function isSet(value) { - return value !== null && value !== undefined; -} - - -/***/ }), - -/***/ 45000: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* eslint-disable */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Timestamp = void 0; -function createBaseTimestamp() { - return { seconds: "0", nanos: 0 }; -} -exports.Timestamp = { - fromJSON(object) { - return { - seconds: isSet(object.seconds) ? String(object.seconds) : "0", - nanos: isSet(object.nanos) ? Number(object.nanos) : 0, - }; - }, - toJSON(message) { - const obj = {}; - message.seconds !== undefined && (obj.seconds = message.seconds); - message.nanos !== undefined && (obj.nanos = Math.round(message.nanos)); - return obj; - }, -}; -function isSet(value) { - return value !== null && value !== undefined; -} - - -/***/ }), - -/***/ 70715: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0; -/* eslint-disable */ -const envelope_1 = __nccwpck_require__(47030); -const sigstore_common_1 = __nccwpck_require__(5334); -const sigstore_rekor_1 = __nccwpck_require__(85204); -function createBaseTimestampVerificationData() { - return { rfc3161Timestamps: [] }; -} -exports.TimestampVerificationData = { - fromJSON(object) { - return { - rfc3161Timestamps: Array.isArray(object?.rfc3161Timestamps) - ? object.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.fromJSON(e)) - : [], - }; - }, - toJSON(message) { - const obj = {}; - if (message.rfc3161Timestamps) { - obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => e ? sigstore_common_1.RFC3161SignedTimestamp.toJSON(e) : undefined); - } - else { - obj.rfc3161Timestamps = []; - } - return obj; - }, -}; -function createBaseVerificationMaterial() { - return { content: undefined, tlogEntries: [], timestampVerificationData: undefined }; -} -exports.VerificationMaterial = { - fromJSON(object) { - return { - content: isSet(object.publicKey) - ? { $case: "publicKey", publicKey: sigstore_common_1.PublicKeyIdentifier.fromJSON(object.publicKey) } - : isSet(object.x509CertificateChain) - ? { - $case: "x509CertificateChain", - x509CertificateChain: sigstore_common_1.X509CertificateChain.fromJSON(object.x509CertificateChain), - } - : isSet(object.certificate) - ? { $case: "certificate", certificate: sigstore_common_1.X509Certificate.fromJSON(object.certificate) } - : undefined, - tlogEntries: Array.isArray(object?.tlogEntries) - ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e)) - : [], - timestampVerificationData: isSet(object.timestampVerificationData) - ? exports.TimestampVerificationData.fromJSON(object.timestampVerificationData) - : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.content?.$case === "publicKey" && - (obj.publicKey = message.content?.publicKey ? sigstore_common_1.PublicKeyIdentifier.toJSON(message.content?.publicKey) : undefined); - message.content?.$case === "x509CertificateChain" && - (obj.x509CertificateChain = message.content?.x509CertificateChain - ? sigstore_common_1.X509CertificateChain.toJSON(message.content?.x509CertificateChain) - : undefined); - message.content?.$case === "certificate" && - (obj.certificate = message.content?.certificate - ? sigstore_common_1.X509Certificate.toJSON(message.content?.certificate) - : undefined); - if (message.tlogEntries) { - obj.tlogEntries = message.tlogEntries.map((e) => e ? sigstore_rekor_1.TransparencyLogEntry.toJSON(e) : undefined); - } - else { - obj.tlogEntries = []; - } - message.timestampVerificationData !== undefined && - (obj.timestampVerificationData = message.timestampVerificationData - ? exports.TimestampVerificationData.toJSON(message.timestampVerificationData) - : undefined); - return obj; - }, -}; -function createBaseBundle() { - return { mediaType: "", verificationMaterial: undefined, content: undefined }; -} -exports.Bundle = { - fromJSON(object) { - return { - mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", - verificationMaterial: isSet(object.verificationMaterial) - ? exports.VerificationMaterial.fromJSON(object.verificationMaterial) - : undefined, - content: isSet(object.messageSignature) - ? { $case: "messageSignature", messageSignature: sigstore_common_1.MessageSignature.fromJSON(object.messageSignature) } - : isSet(object.dsseEnvelope) - ? { $case: "dsseEnvelope", dsseEnvelope: envelope_1.Envelope.fromJSON(object.dsseEnvelope) } - : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.mediaType !== undefined && (obj.mediaType = message.mediaType); - message.verificationMaterial !== undefined && (obj.verificationMaterial = message.verificationMaterial - ? exports.VerificationMaterial.toJSON(message.verificationMaterial) - : undefined); - message.content?.$case === "messageSignature" && (obj.messageSignature = message.content?.messageSignature - ? sigstore_common_1.MessageSignature.toJSON(message.content?.messageSignature) - : undefined); - message.content?.$case === "dsseEnvelope" && - (obj.dsseEnvelope = message.content?.dsseEnvelope ? envelope_1.Envelope.toJSON(message.content?.dsseEnvelope) : undefined); - return obj; - }, -}; -function isSet(value) { - return value !== null && value !== undefined; -} - - -/***/ }), - -/***/ 5334: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0; -/* eslint-disable */ -const timestamp_1 = __nccwpck_require__(45000); -/** - * Only a subset of the secure hash standard algorithms are supported. - * See for more - * details. - * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force - * any proto JSON serialization to emit the used hash algorithm, as default - * option is to *omit* the default value of an enum (which is the first - * value, represented by '0'. - */ -var HashAlgorithm; -(function (HashAlgorithm) { - HashAlgorithm[HashAlgorithm["HASH_ALGORITHM_UNSPECIFIED"] = 0] = "HASH_ALGORITHM_UNSPECIFIED"; - HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256"; - HashAlgorithm[HashAlgorithm["SHA2_384"] = 2] = "SHA2_384"; - HashAlgorithm[HashAlgorithm["SHA2_512"] = 3] = "SHA2_512"; - HashAlgorithm[HashAlgorithm["SHA3_256"] = 4] = "SHA3_256"; - HashAlgorithm[HashAlgorithm["SHA3_384"] = 5] = "SHA3_384"; -})(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {})); -function hashAlgorithmFromJSON(object) { - switch (object) { - case 0: - case "HASH_ALGORITHM_UNSPECIFIED": - return HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED; - case 1: - case "SHA2_256": - return HashAlgorithm.SHA2_256; - case 2: - case "SHA2_384": - return HashAlgorithm.SHA2_384; - case 3: - case "SHA2_512": - return HashAlgorithm.SHA2_512; - case 4: - case "SHA3_256": - return HashAlgorithm.SHA3_256; - case 5: - case "SHA3_384": - return HashAlgorithm.SHA3_384; - default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); - } -} -exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON; -function hashAlgorithmToJSON(object) { - switch (object) { - case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED: - return "HASH_ALGORITHM_UNSPECIFIED"; - case HashAlgorithm.SHA2_256: - return "SHA2_256"; - case HashAlgorithm.SHA2_384: - return "SHA2_384"; - case HashAlgorithm.SHA2_512: - return "SHA2_512"; - case HashAlgorithm.SHA3_256: - return "SHA3_256"; - case HashAlgorithm.SHA3_384: - return "SHA3_384"; - default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); - } -} -exports.hashAlgorithmToJSON = hashAlgorithmToJSON; -/** - * Details of a specific public key, capturing the the key encoding method, - * and signature algorithm. - * - * PublicKeyDetails captures the public key/hash algorithm combinations - * recommended in the Sigstore ecosystem. - * - * This is modelled as a linear set as we want to provide a small number of - * opinionated options instead of allowing every possible permutation. - * - * Any changes to this enum MUST be reflected in the algorithm registry. - * See: docs/algorithm-registry.md - * - * To avoid the possibility of contradicting formats such as PKCS1 with - * ED25519 the valid permutations are listed as a linear set instead of a - * cartesian set (i.e one combined variable instead of two, one for encoding - * and one for the signature algorithm). - */ -var PublicKeyDetails; -(function (PublicKeyDetails) { - PublicKeyDetails[PublicKeyDetails["PUBLIC_KEY_DETAILS_UNSPECIFIED"] = 0] = "PUBLIC_KEY_DETAILS_UNSPECIFIED"; - /** - * PKCS1_RSA_PKCS1V5 - RSA - * - * @deprecated - */ - PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PKCS1V5"] = 1] = "PKCS1_RSA_PKCS1V5"; - /** - * PKCS1_RSA_PSS - See RFC8017 - * - * @deprecated - */ - PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PSS"] = 2] = "PKCS1_RSA_PSS"; - /** @deprecated */ - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V5"] = 3] = "PKIX_RSA_PKCS1V5"; - /** @deprecated */ - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS"] = 4] = "PKIX_RSA_PSS"; - /** PKIX_RSA_PKCS1V15_2048_SHA256 - RSA public key in PKIX format, PKCS#1v1.5 signature */ - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_2048_SHA256"] = 9] = "PKIX_RSA_PKCS1V15_2048_SHA256"; - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_3072_SHA256"] = 10] = "PKIX_RSA_PKCS1V15_3072_SHA256"; - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_4096_SHA256"] = 11] = "PKIX_RSA_PKCS1V15_4096_SHA256"; - /** PKIX_RSA_PSS_2048_SHA256 - RSA public key in PKIX format, RSASSA-PSS signature */ - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_2048_SHA256"] = 16] = "PKIX_RSA_PSS_2048_SHA256"; - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_3072_SHA256"] = 17] = "PKIX_RSA_PSS_3072_SHA256"; - PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_4096_SHA256"] = 18] = "PKIX_RSA_PSS_4096_SHA256"; - /** - * PKIX_ECDSA_P256_HMAC_SHA_256 - ECDSA - * - * @deprecated - */ - PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_HMAC_SHA_256"] = 6] = "PKIX_ECDSA_P256_HMAC_SHA_256"; - /** PKIX_ECDSA_P256_SHA_256 - See NIST FIPS 186-4 */ - PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_SHA_256"] = 5] = "PKIX_ECDSA_P256_SHA_256"; - PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P384_SHA_384"] = 12] = "PKIX_ECDSA_P384_SHA_384"; - PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P521_SHA_512"] = 13] = "PKIX_ECDSA_P521_SHA_512"; - /** PKIX_ED25519 - Ed 25519 */ - PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519"; - PublicKeyDetails[PublicKeyDetails["PKIX_ED25519_PH"] = 8] = "PKIX_ED25519_PH"; - /** - * LMS_SHA256 - LMS and LM-OTS - * - * These keys and signatures may be used by private Sigstore - * deployments, but are not currently supported by the public - * good instance. - * - * USER WARNING: LMS and LM-OTS are both stateful signature schemes. - * Using them correctly requires discretion and careful consideration - * to ensure that individual secret keys are not used more than once. - * In addition, LM-OTS is a single-use scheme, meaning that it - * MUST NOT be used for more than one signature per LM-OTS key. - * If you cannot maintain these invariants, you MUST NOT use these - * schemes. - */ - PublicKeyDetails[PublicKeyDetails["LMS_SHA256"] = 14] = "LMS_SHA256"; - PublicKeyDetails[PublicKeyDetails["LMOTS_SHA256"] = 15] = "LMOTS_SHA256"; -})(PublicKeyDetails = exports.PublicKeyDetails || (exports.PublicKeyDetails = {})); -function publicKeyDetailsFromJSON(object) { - switch (object) { - case 0: - case "PUBLIC_KEY_DETAILS_UNSPECIFIED": - return PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED; - case 1: - case "PKCS1_RSA_PKCS1V5": - return PublicKeyDetails.PKCS1_RSA_PKCS1V5; - case 2: - case "PKCS1_RSA_PSS": - return PublicKeyDetails.PKCS1_RSA_PSS; - case 3: - case "PKIX_RSA_PKCS1V5": - return PublicKeyDetails.PKIX_RSA_PKCS1V5; - case 4: - case "PKIX_RSA_PSS": - return PublicKeyDetails.PKIX_RSA_PSS; - case 9: - case "PKIX_RSA_PKCS1V15_2048_SHA256": - return PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256; - case 10: - case "PKIX_RSA_PKCS1V15_3072_SHA256": - return PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256; - case 11: - case "PKIX_RSA_PKCS1V15_4096_SHA256": - return PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256; - case 16: - case "PKIX_RSA_PSS_2048_SHA256": - return PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256; - case 17: - case "PKIX_RSA_PSS_3072_SHA256": - return PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256; - case 18: - case "PKIX_RSA_PSS_4096_SHA256": - return PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256; - case 6: - case "PKIX_ECDSA_P256_HMAC_SHA_256": - return PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256; - case 5: - case "PKIX_ECDSA_P256_SHA_256": - return PublicKeyDetails.PKIX_ECDSA_P256_SHA_256; - case 12: - case "PKIX_ECDSA_P384_SHA_384": - return PublicKeyDetails.PKIX_ECDSA_P384_SHA_384; - case 13: - case "PKIX_ECDSA_P521_SHA_512": - return PublicKeyDetails.PKIX_ECDSA_P521_SHA_512; - case 7: - case "PKIX_ED25519": - return PublicKeyDetails.PKIX_ED25519; - case 8: - case "PKIX_ED25519_PH": - return PublicKeyDetails.PKIX_ED25519_PH; - case 14: - case "LMS_SHA256": - return PublicKeyDetails.LMS_SHA256; - case 15: - case "LMOTS_SHA256": - return PublicKeyDetails.LMOTS_SHA256; - default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); - } -} -exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON; -function publicKeyDetailsToJSON(object) { - switch (object) { - case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED: - return "PUBLIC_KEY_DETAILS_UNSPECIFIED"; - case PublicKeyDetails.PKCS1_RSA_PKCS1V5: - return "PKCS1_RSA_PKCS1V5"; - case PublicKeyDetails.PKCS1_RSA_PSS: - return "PKCS1_RSA_PSS"; - case PublicKeyDetails.PKIX_RSA_PKCS1V5: - return "PKIX_RSA_PKCS1V5"; - case PublicKeyDetails.PKIX_RSA_PSS: - return "PKIX_RSA_PSS"; - case PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256: - return "PKIX_RSA_PKCS1V15_2048_SHA256"; - case PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256: - return "PKIX_RSA_PKCS1V15_3072_SHA256"; - case PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256: - return "PKIX_RSA_PKCS1V15_4096_SHA256"; - case PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256: - return "PKIX_RSA_PSS_2048_SHA256"; - case PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256: - return "PKIX_RSA_PSS_3072_SHA256"; - case PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256: - return "PKIX_RSA_PSS_4096_SHA256"; - case PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256: - return "PKIX_ECDSA_P256_HMAC_SHA_256"; - case PublicKeyDetails.PKIX_ECDSA_P256_SHA_256: - return "PKIX_ECDSA_P256_SHA_256"; - case PublicKeyDetails.PKIX_ECDSA_P384_SHA_384: - return "PKIX_ECDSA_P384_SHA_384"; - case PublicKeyDetails.PKIX_ECDSA_P521_SHA_512: - return "PKIX_ECDSA_P521_SHA_512"; - case PublicKeyDetails.PKIX_ED25519: - return "PKIX_ED25519"; - case PublicKeyDetails.PKIX_ED25519_PH: - return "PKIX_ED25519_PH"; - case PublicKeyDetails.LMS_SHA256: - return "LMS_SHA256"; - case PublicKeyDetails.LMOTS_SHA256: - return "LMOTS_SHA256"; - default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); - } -} -exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON; -var SubjectAlternativeNameType; -(function (SubjectAlternativeNameType) { - SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; - SubjectAlternativeNameType[SubjectAlternativeNameType["EMAIL"] = 1] = "EMAIL"; - SubjectAlternativeNameType[SubjectAlternativeNameType["URI"] = 2] = "URI"; - /** - * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7 - * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san - * for more details. - */ - SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME"; -})(SubjectAlternativeNameType = exports.SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = {})); -function subjectAlternativeNameTypeFromJSON(object) { - switch (object) { - case 0: - case "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED": - return SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED; - case 1: - case "EMAIL": - return SubjectAlternativeNameType.EMAIL; - case 2: - case "URI": - return SubjectAlternativeNameType.URI; - case 3: - case "OTHER_NAME": - return SubjectAlternativeNameType.OTHER_NAME; - default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); - } -} -exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON; -function subjectAlternativeNameTypeToJSON(object) { - switch (object) { - case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED: - return "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; - case SubjectAlternativeNameType.EMAIL: - return "EMAIL"; - case SubjectAlternativeNameType.URI: - return "URI"; - case SubjectAlternativeNameType.OTHER_NAME: - return "OTHER_NAME"; - default: - throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); - } -} -exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON; -function createBaseHashOutput() { - return { algorithm: 0, digest: Buffer.alloc(0) }; -} -exports.HashOutput = { - fromJSON(object) { - return { - algorithm: isSet(object.algorithm) ? hashAlgorithmFromJSON(object.algorithm) : 0, - digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0), - }; - }, - toJSON(message) { - const obj = {}; - message.algorithm !== undefined && (obj.algorithm = hashAlgorithmToJSON(message.algorithm)); - message.digest !== undefined && - (obj.digest = base64FromBytes(message.digest !== undefined ? message.digest : Buffer.alloc(0))); - return obj; - }, -}; -function createBaseMessageSignature() { - return { messageDigest: undefined, signature: Buffer.alloc(0) }; -} -exports.MessageSignature = { - fromJSON(object) { - return { - messageDigest: isSet(object.messageDigest) ? exports.HashOutput.fromJSON(object.messageDigest) : undefined, - signature: isSet(object.signature) ? Buffer.from(bytesFromBase64(object.signature)) : Buffer.alloc(0), - }; - }, - toJSON(message) { - const obj = {}; - message.messageDigest !== undefined && - (obj.messageDigest = message.messageDigest ? exports.HashOutput.toJSON(message.messageDigest) : undefined); - message.signature !== undefined && - (obj.signature = base64FromBytes(message.signature !== undefined ? message.signature : Buffer.alloc(0))); - return obj; - }, -}; -function createBaseLogId() { - return { keyId: Buffer.alloc(0) }; -} -exports.LogId = { - fromJSON(object) { - return { keyId: isSet(object.keyId) ? Buffer.from(bytesFromBase64(object.keyId)) : Buffer.alloc(0) }; - }, - toJSON(message) { - const obj = {}; - message.keyId !== undefined && - (obj.keyId = base64FromBytes(message.keyId !== undefined ? message.keyId : Buffer.alloc(0))); - return obj; - }, -}; -function createBaseRFC3161SignedTimestamp() { - return { signedTimestamp: Buffer.alloc(0) }; -} -exports.RFC3161SignedTimestamp = { - fromJSON(object) { - return { - signedTimestamp: isSet(object.signedTimestamp) - ? Buffer.from(bytesFromBase64(object.signedTimestamp)) - : Buffer.alloc(0), - }; - }, - toJSON(message) { - const obj = {}; - message.signedTimestamp !== undefined && - (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0))); - return obj; - }, -}; -function createBasePublicKey() { - return { rawBytes: undefined, keyDetails: 0, validFor: undefined }; -} -exports.PublicKey = { - fromJSON(object) { - return { - rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : undefined, - keyDetails: isSet(object.keyDetails) ? publicKeyDetailsFromJSON(object.keyDetails) : 0, - validFor: isSet(object.validFor) ? exports.TimeRange.fromJSON(object.validFor) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.rawBytes !== undefined && - (obj.rawBytes = message.rawBytes !== undefined ? base64FromBytes(message.rawBytes) : undefined); - message.keyDetails !== undefined && (obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails)); - message.validFor !== undefined && - (obj.validFor = message.validFor ? exports.TimeRange.toJSON(message.validFor) : undefined); - return obj; - }, -}; -function createBasePublicKeyIdentifier() { - return { hint: "" }; -} -exports.PublicKeyIdentifier = { - fromJSON(object) { - return { hint: isSet(object.hint) ? String(object.hint) : "" }; - }, - toJSON(message) { - const obj = {}; - message.hint !== undefined && (obj.hint = message.hint); - return obj; - }, -}; -function createBaseObjectIdentifier() { - return { id: [] }; -} -exports.ObjectIdentifier = { - fromJSON(object) { - return { id: Array.isArray(object?.id) ? object.id.map((e) => Number(e)) : [] }; - }, - toJSON(message) { - const obj = {}; - if (message.id) { - obj.id = message.id.map((e) => Math.round(e)); - } - else { - obj.id = []; - } - return obj; - }, -}; -function createBaseObjectIdentifierValuePair() { - return { oid: undefined, value: Buffer.alloc(0) }; -} -exports.ObjectIdentifierValuePair = { - fromJSON(object) { - return { - oid: isSet(object.oid) ? exports.ObjectIdentifier.fromJSON(object.oid) : undefined, - value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0), - }; - }, - toJSON(message) { - const obj = {}; - message.oid !== undefined && (obj.oid = message.oid ? exports.ObjectIdentifier.toJSON(message.oid) : undefined); - message.value !== undefined && - (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0))); - return obj; - }, -}; -function createBaseDistinguishedName() { - return { organization: "", commonName: "" }; -} -exports.DistinguishedName = { - fromJSON(object) { - return { - organization: isSet(object.organization) ? String(object.organization) : "", - commonName: isSet(object.commonName) ? String(object.commonName) : "", - }; - }, - toJSON(message) { - const obj = {}; - message.organization !== undefined && (obj.organization = message.organization); - message.commonName !== undefined && (obj.commonName = message.commonName); - return obj; - }, -}; -function createBaseX509Certificate() { - return { rawBytes: Buffer.alloc(0) }; -} -exports.X509Certificate = { - fromJSON(object) { - return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) }; - }, - toJSON(message) { - const obj = {}; - message.rawBytes !== undefined && - (obj.rawBytes = base64FromBytes(message.rawBytes !== undefined ? message.rawBytes : Buffer.alloc(0))); - return obj; - }, -}; -function createBaseSubjectAlternativeName() { - return { type: 0, identity: undefined }; -} -exports.SubjectAlternativeName = { - fromJSON(object) { - return { - type: isSet(object.type) ? subjectAlternativeNameTypeFromJSON(object.type) : 0, - identity: isSet(object.regexp) - ? { $case: "regexp", regexp: String(object.regexp) } - : isSet(object.value) - ? { $case: "value", value: String(object.value) } - : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.type !== undefined && (obj.type = subjectAlternativeNameTypeToJSON(message.type)); - message.identity?.$case === "regexp" && (obj.regexp = message.identity?.regexp); - message.identity?.$case === "value" && (obj.value = message.identity?.value); - return obj; - }, -}; -function createBaseX509CertificateChain() { - return { certificates: [] }; -} -exports.X509CertificateChain = { - fromJSON(object) { - return { - certificates: Array.isArray(object?.certificates) - ? object.certificates.map((e) => exports.X509Certificate.fromJSON(e)) - : [], - }; - }, - toJSON(message) { - const obj = {}; - if (message.certificates) { - obj.certificates = message.certificates.map((e) => e ? exports.X509Certificate.toJSON(e) : undefined); - } - else { - obj.certificates = []; - } - return obj; - }, -}; -function createBaseTimeRange() { - return { start: undefined, end: undefined }; -} -exports.TimeRange = { - fromJSON(object) { - return { - start: isSet(object.start) ? fromJsonTimestamp(object.start) : undefined, - end: isSet(object.end) ? fromJsonTimestamp(object.end) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.start !== undefined && (obj.start = message.start.toISOString()); - message.end !== undefined && (obj.end = message.end.toISOString()); - return obj; - }, -}; -var tsProtoGlobalThis = (() => { - if (typeof globalThis !== "undefined") { - return globalThis; - } - if (typeof self !== "undefined") { - return self; - } - if (typeof window !== "undefined") { - return window; - } - if (typeof global !== "undefined") { - return global; - } - throw "Unable to locate global object"; -})(); -function bytesFromBase64(b64) { - if (tsProtoGlobalThis.Buffer) { - return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); - } - else { - const bin = tsProtoGlobalThis.atob(b64); - const arr = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; ++i) { - arr[i] = bin.charCodeAt(i); - } - return arr; - } + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } } -function base64FromBytes(arr) { - if (tsProtoGlobalThis.Buffer) { - return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); - } - else { - const bin = []; - arr.forEach((byte) => { - bin.push(String.fromCharCode(byte)); - }); - return tsProtoGlobalThis.btoa(bin.join("")); +module.exports = cmp + + +/***/ }), + +/***/ 3346: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const parse = __nccwpck_require__(45240) +const { safeRe: re, t } = __nccwpck_require__(84894) + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) } -function fromTimestamp(t) { - let millis = Number(t.seconds) * 1000; - millis += t.nanos / 1000000; - return new Date(millis); +module.exports = coerce + + +/***/ }), + +/***/ 69685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) } -function fromJsonTimestamp(o) { - if (o instanceof Date) { - return o; - } - else if (typeof o === "string") { - return new Date(o); +module.exports = compareBuild + + +/***/ }), + +/***/ 90731: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose + + +/***/ }), + +/***/ 77304: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare + + +/***/ }), + +/***/ 84048: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const parse = __nccwpck_require__(45240) + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' } - else { - return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); + + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } + return 'patch' } + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' } -function isSet(value) { - return value !== null && value !== undefined; -} + +module.exports = diff /***/ }), -/***/ 85204: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5113: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const compare = __nccwpck_require__(77304) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0; -/* eslint-disable */ -const sigstore_common_1 = __nccwpck_require__(5334); -function createBaseKindVersion() { - return { kind: "", version: "" }; -} -exports.KindVersion = { - fromJSON(object) { - return { - kind: isSet(object.kind) ? String(object.kind) : "", - version: isSet(object.version) ? String(object.version) : "", - }; - }, - toJSON(message) { - const obj = {}; - message.kind !== undefined && (obj.kind = message.kind); - message.version !== undefined && (obj.version = message.version); - return obj; - }, -}; -function createBaseCheckpoint() { - return { envelope: "" }; -} -exports.Checkpoint = { - fromJSON(object) { - return { envelope: isSet(object.envelope) ? String(object.envelope) : "" }; - }, - toJSON(message) { - const obj = {}; - message.envelope !== undefined && (obj.envelope = message.envelope); - return obj; - }, -}; -function createBaseInclusionProof() { - return { logIndex: "0", rootHash: Buffer.alloc(0), treeSize: "0", hashes: [], checkpoint: undefined }; -} -exports.InclusionProof = { - fromJSON(object) { - return { - logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", - rootHash: isSet(object.rootHash) ? Buffer.from(bytesFromBase64(object.rootHash)) : Buffer.alloc(0), - treeSize: isSet(object.treeSize) ? String(object.treeSize) : "0", - hashes: Array.isArray(object?.hashes) ? object.hashes.map((e) => Buffer.from(bytesFromBase64(e))) : [], - checkpoint: isSet(object.checkpoint) ? exports.Checkpoint.fromJSON(object.checkpoint) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.logIndex !== undefined && (obj.logIndex = message.logIndex); - message.rootHash !== undefined && - (obj.rootHash = base64FromBytes(message.rootHash !== undefined ? message.rootHash : Buffer.alloc(0))); - message.treeSize !== undefined && (obj.treeSize = message.treeSize); - if (message.hashes) { - obj.hashes = message.hashes.map((e) => base64FromBytes(e !== undefined ? e : Buffer.alloc(0))); - } - else { - obj.hashes = []; - } - message.checkpoint !== undefined && - (obj.checkpoint = message.checkpoint ? exports.Checkpoint.toJSON(message.checkpoint) : undefined); - return obj; - }, -}; -function createBaseInclusionPromise() { - return { signedEntryTimestamp: Buffer.alloc(0) }; -} -exports.InclusionPromise = { - fromJSON(object) { - return { - signedEntryTimestamp: isSet(object.signedEntryTimestamp) - ? Buffer.from(bytesFromBase64(object.signedEntryTimestamp)) - : Buffer.alloc(0), - }; - }, - toJSON(message) { - const obj = {}; - message.signedEntryTimestamp !== undefined && - (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0))); - return obj; - }, -}; -function createBaseTransparencyLogEntry() { - return { - logIndex: "0", - logId: undefined, - kindVersion: undefined, - integratedTime: "0", - inclusionPromise: undefined, - inclusionProof: undefined, - canonicalizedBody: Buffer.alloc(0), - }; -} -exports.TransparencyLogEntry = { - fromJSON(object) { - return { - logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", - logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, - kindVersion: isSet(object.kindVersion) ? exports.KindVersion.fromJSON(object.kindVersion) : undefined, - integratedTime: isSet(object.integratedTime) ? String(object.integratedTime) : "0", - inclusionPromise: isSet(object.inclusionPromise) ? exports.InclusionPromise.fromJSON(object.inclusionPromise) : undefined, - inclusionProof: isSet(object.inclusionProof) ? exports.InclusionProof.fromJSON(object.inclusionProof) : undefined, - canonicalizedBody: isSet(object.canonicalizedBody) - ? Buffer.from(bytesFromBase64(object.canonicalizedBody)) - : Buffer.alloc(0), - }; - }, - toJSON(message) { - const obj = {}; - message.logIndex !== undefined && (obj.logIndex = message.logIndex); - message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); - message.kindVersion !== undefined && - (obj.kindVersion = message.kindVersion ? exports.KindVersion.toJSON(message.kindVersion) : undefined); - message.integratedTime !== undefined && (obj.integratedTime = message.integratedTime); - message.inclusionPromise !== undefined && - (obj.inclusionPromise = message.inclusionPromise ? exports.InclusionPromise.toJSON(message.inclusionPromise) : undefined); - message.inclusionProof !== undefined && - (obj.inclusionProof = message.inclusionProof ? exports.InclusionProof.toJSON(message.inclusionProof) : undefined); - message.canonicalizedBody !== undefined && - (obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody !== undefined ? message.canonicalizedBody : Buffer.alloc(0))); - return obj; - }, -}; -var tsProtoGlobalThis = (() => { - if (typeof globalThis !== "undefined") { - return globalThis; - } - if (typeof self !== "undefined") { - return self; - } - if (typeof window !== "undefined") { - return window; - } - if (typeof global !== "undefined") { - return global; - } - throw "Unable to locate global object"; -})(); -function bytesFromBase64(b64) { - if (tsProtoGlobalThis.Buffer) { - return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); - } - else { - const bin = tsProtoGlobalThis.atob(b64); - const arr = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; ++i) { - arr[i] = bin.charCodeAt(i); - } - return arr; - } + +/***/ }), + +/***/ 35012: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt + + +/***/ }), + +/***/ 67745: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte + + +/***/ }), + +/***/ 55303: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } } -function base64FromBytes(arr) { - if (tsProtoGlobalThis.Buffer) { - return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); - } - else { - const bin = []; - arr.forEach((byte) => { - bin.push(String.fromCharCode(byte)); - }); - return tsProtoGlobalThis.btoa(bin.join("")); +module.exports = inc + + +/***/ }), + +/***/ 63691: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt + + +/***/ }), + +/***/ 27672: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte + + +/***/ }), + +/***/ 18610: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major + + +/***/ }), + +/***/ 8550: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor + + +/***/ }), + +/***/ 26487: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq + + +/***/ }), + +/***/ 45240: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null } + throw er + } } -function isSet(value) { - return value !== null && value !== undefined; -} + +module.exports = parse /***/ }), -/***/ 61997: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 43413: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const SemVer = __nccwpck_require__(95548) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0; -/* eslint-disable */ -const sigstore_common_1 = __nccwpck_require__(5334); -function createBaseTransparencyLogInstance() { - return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined }; -} -exports.TransparencyLogInstance = { - fromJSON(object) { - return { - baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "", - hashAlgorithm: isSet(object.hashAlgorithm) ? (0, sigstore_common_1.hashAlgorithmFromJSON)(object.hashAlgorithm) : 0, - publicKey: isSet(object.publicKey) ? sigstore_common_1.PublicKey.fromJSON(object.publicKey) : undefined, - logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, - checkpointKeyId: isSet(object.checkpointKeyId) ? sigstore_common_1.LogId.fromJSON(object.checkpointKeyId) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.baseUrl !== undefined && (obj.baseUrl = message.baseUrl); - message.hashAlgorithm !== undefined && (obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm)); - message.publicKey !== undefined && - (obj.publicKey = message.publicKey ? sigstore_common_1.PublicKey.toJSON(message.publicKey) : undefined); - message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); - message.checkpointKeyId !== undefined && - (obj.checkpointKeyId = message.checkpointKeyId ? sigstore_common_1.LogId.toJSON(message.checkpointKeyId) : undefined); - return obj; - }, -}; -function createBaseCertificateAuthority() { - return { subject: undefined, uri: "", certChain: undefined, validFor: undefined }; -} -exports.CertificateAuthority = { - fromJSON(object) { - return { - subject: isSet(object.subject) ? sigstore_common_1.DistinguishedName.fromJSON(object.subject) : undefined, - uri: isSet(object.uri) ? String(object.uri) : "", - certChain: isSet(object.certChain) ? sigstore_common_1.X509CertificateChain.fromJSON(object.certChain) : undefined, - validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.subject !== undefined && - (obj.subject = message.subject ? sigstore_common_1.DistinguishedName.toJSON(message.subject) : undefined); - message.uri !== undefined && (obj.uri = message.uri); - message.certChain !== undefined && - (obj.certChain = message.certChain ? sigstore_common_1.X509CertificateChain.toJSON(message.certChain) : undefined); - message.validFor !== undefined && - (obj.validFor = message.validFor ? sigstore_common_1.TimeRange.toJSON(message.validFor) : undefined); - return obj; - }, -}; -function createBaseTrustedRoot() { - return { mediaType: "", tlogs: [], certificateAuthorities: [], ctlogs: [], timestampAuthorities: [] }; -} -exports.TrustedRoot = { - fromJSON(object) { - return { - mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", - tlogs: Array.isArray(object?.tlogs) ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], - certificateAuthorities: Array.isArray(object?.certificateAuthorities) - ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) - : [], - ctlogs: Array.isArray(object?.ctlogs) - ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) - : [], - timestampAuthorities: Array.isArray(object?.timestampAuthorities) - ? object.timestampAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) - : [], - }; - }, - toJSON(message) { - const obj = {}; - message.mediaType !== undefined && (obj.mediaType = message.mediaType); - if (message.tlogs) { - obj.tlogs = message.tlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); - } - else { - obj.tlogs = []; - } - if (message.certificateAuthorities) { - obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); - } - else { - obj.certificateAuthorities = []; - } - if (message.ctlogs) { - obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); - } - else { - obj.ctlogs = []; - } - if (message.timestampAuthorities) { - obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); - } - else { - obj.timestampAuthorities = []; - } - return obj; - }, -}; -function createBaseSigningConfig() { - return { caUrl: "", oidcUrl: "", tlogUrls: [], tsaUrls: [] }; -} -exports.SigningConfig = { - fromJSON(object) { - return { - caUrl: isSet(object.caUrl) ? String(object.caUrl) : "", - oidcUrl: isSet(object.oidcUrl) ? String(object.oidcUrl) : "", - tlogUrls: Array.isArray(object?.tlogUrls) ? object.tlogUrls.map((e) => String(e)) : [], - tsaUrls: Array.isArray(object?.tsaUrls) ? object.tsaUrls.map((e) => String(e)) : [], - }; - }, - toJSON(message) { - const obj = {}; - message.caUrl !== undefined && (obj.caUrl = message.caUrl); - message.oidcUrl !== undefined && (obj.oidcUrl = message.oidcUrl); - if (message.tlogUrls) { - obj.tlogUrls = message.tlogUrls.map((e) => e); - } - else { - obj.tlogUrls = []; - } - if (message.tsaUrls) { - obj.tsaUrls = message.tsaUrls.map((e) => e); - } - else { - obj.tsaUrls = []; - } - return obj; - }, -}; -function createBaseClientTrustConfig() { - return { mediaType: "", trustedRoot: undefined, signingConfig: undefined }; + +/***/ }), + +/***/ 94729: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const parse = __nccwpck_require__(45240) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } -exports.ClientTrustConfig = { - fromJSON(object) { - return { - mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", - trustedRoot: isSet(object.trustedRoot) ? exports.TrustedRoot.fromJSON(object.trustedRoot) : undefined, - signingConfig: isSet(object.signingConfig) ? exports.SigningConfig.fromJSON(object.signingConfig) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.mediaType !== undefined && (obj.mediaType = message.mediaType); - message.trustedRoot !== undefined && - (obj.trustedRoot = message.trustedRoot ? exports.TrustedRoot.toJSON(message.trustedRoot) : undefined); - message.signingConfig !== undefined && - (obj.signingConfig = message.signingConfig ? exports.SigningConfig.toJSON(message.signingConfig) : undefined); - return obj; - }, -}; -function isSet(value) { - return value !== null && value !== undefined; +module.exports = prerelease + + +/***/ }), + +/***/ 42810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compare = __nccwpck_require__(77304) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare + + +/***/ }), + +/***/ 91981: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const compareBuild = __nccwpck_require__(69685) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort + + +/***/ }), + +/***/ 10174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const Range = __nccwpck_require__(60031) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) } +module.exports = satisfies /***/ }), -/***/ 99732: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 43151: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const compareBuild = __nccwpck_require__(69685) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_ObserverTimestampOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0; -/* eslint-disable */ -const sigstore_bundle_1 = __nccwpck_require__(70715); -const sigstore_common_1 = __nccwpck_require__(5334); -const sigstore_trustroot_1 = __nccwpck_require__(61997); -function createBaseCertificateIdentity() { - return { issuer: "", san: undefined, oids: [] }; -} -exports.CertificateIdentity = { - fromJSON(object) { - return { - issuer: isSet(object.issuer) ? String(object.issuer) : "", - san: isSet(object.san) ? sigstore_common_1.SubjectAlternativeName.fromJSON(object.san) : undefined, - oids: Array.isArray(object?.oids) ? object.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.fromJSON(e)) : [], - }; - }, - toJSON(message) { - const obj = {}; - message.issuer !== undefined && (obj.issuer = message.issuer); - message.san !== undefined && (obj.san = message.san ? sigstore_common_1.SubjectAlternativeName.toJSON(message.san) : undefined); - if (message.oids) { - obj.oids = message.oids.map((e) => e ? sigstore_common_1.ObjectIdentifierValuePair.toJSON(e) : undefined); - } - else { - obj.oids = []; - } - return obj; - }, -}; -function createBaseCertificateIdentities() { - return { identities: [] }; -} -exports.CertificateIdentities = { - fromJSON(object) { - return { - identities: Array.isArray(object?.identities) - ? object.identities.map((e) => exports.CertificateIdentity.fromJSON(e)) - : [], - }; - }, - toJSON(message) { - const obj = {}; - if (message.identities) { - obj.identities = message.identities.map((e) => e ? exports.CertificateIdentity.toJSON(e) : undefined); - } - else { - obj.identities = []; - } - return obj; - }, -}; -function createBasePublicKeyIdentities() { - return { publicKeys: [] }; -} -exports.PublicKeyIdentities = { - fromJSON(object) { - return { - publicKeys: Array.isArray(object?.publicKeys) ? object.publicKeys.map((e) => sigstore_common_1.PublicKey.fromJSON(e)) : [], - }; - }, - toJSON(message) { - const obj = {}; - if (message.publicKeys) { - obj.publicKeys = message.publicKeys.map((e) => e ? sigstore_common_1.PublicKey.toJSON(e) : undefined); - } - else { - obj.publicKeys = []; - } - return obj; - }, -}; -function createBaseArtifactVerificationOptions() { - return { - signers: undefined, - tlogOptions: undefined, - ctlogOptions: undefined, - tsaOptions: undefined, - integratedTsOptions: undefined, - observerOptions: undefined, - }; -} -exports.ArtifactVerificationOptions = { - fromJSON(object) { - return { - signers: isSet(object.certificateIdentities) - ? { - $case: "certificateIdentities", - certificateIdentities: exports.CertificateIdentities.fromJSON(object.certificateIdentities), - } - : isSet(object.publicKeys) - ? { $case: "publicKeys", publicKeys: exports.PublicKeyIdentities.fromJSON(object.publicKeys) } - : undefined, - tlogOptions: isSet(object.tlogOptions) - ? exports.ArtifactVerificationOptions_TlogOptions.fromJSON(object.tlogOptions) - : undefined, - ctlogOptions: isSet(object.ctlogOptions) - ? exports.ArtifactVerificationOptions_CtlogOptions.fromJSON(object.ctlogOptions) - : undefined, - tsaOptions: isSet(object.tsaOptions) - ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.fromJSON(object.tsaOptions) - : undefined, - integratedTsOptions: isSet(object.integratedTsOptions) - ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.fromJSON(object.integratedTsOptions) - : undefined, - observerOptions: isSet(object.observerOptions) - ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.fromJSON(object.observerOptions) - : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.signers?.$case === "certificateIdentities" && - (obj.certificateIdentities = message.signers?.certificateIdentities - ? exports.CertificateIdentities.toJSON(message.signers?.certificateIdentities) - : undefined); - message.signers?.$case === "publicKeys" && (obj.publicKeys = message.signers?.publicKeys - ? exports.PublicKeyIdentities.toJSON(message.signers?.publicKeys) - : undefined); - message.tlogOptions !== undefined && (obj.tlogOptions = message.tlogOptions - ? exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions) - : undefined); - message.ctlogOptions !== undefined && (obj.ctlogOptions = message.ctlogOptions - ? exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions) - : undefined); - message.tsaOptions !== undefined && (obj.tsaOptions = message.tsaOptions - ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions) - : undefined); - message.integratedTsOptions !== undefined && (obj.integratedTsOptions = message.integratedTsOptions - ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.toJSON(message.integratedTsOptions) - : undefined); - message.observerOptions !== undefined && (obj.observerOptions = message.observerOptions - ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.toJSON(message.observerOptions) - : undefined); - return obj; - }, -}; -function createBaseArtifactVerificationOptions_TlogOptions() { - return { threshold: 0, performOnlineVerification: false, disable: false }; -} -exports.ArtifactVerificationOptions_TlogOptions = { - fromJSON(object) { - return { - threshold: isSet(object.threshold) ? Number(object.threshold) : 0, - performOnlineVerification: isSet(object.performOnlineVerification) - ? Boolean(object.performOnlineVerification) - : false, - disable: isSet(object.disable) ? Boolean(object.disable) : false, - }; - }, - toJSON(message) { - const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.performOnlineVerification !== undefined && - (obj.performOnlineVerification = message.performOnlineVerification); - message.disable !== undefined && (obj.disable = message.disable); - return obj; - }, -}; -function createBaseArtifactVerificationOptions_CtlogOptions() { - return { threshold: 0, disable: false }; -} -exports.ArtifactVerificationOptions_CtlogOptions = { - fromJSON(object) { - return { - threshold: isSet(object.threshold) ? Number(object.threshold) : 0, - disable: isSet(object.disable) ? Boolean(object.disable) : false, - }; - }, - toJSON(message) { - const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); - return obj; - }, -}; -function createBaseArtifactVerificationOptions_TimestampAuthorityOptions() { - return { threshold: 0, disable: false }; -} -exports.ArtifactVerificationOptions_TimestampAuthorityOptions = { - fromJSON(object) { - return { - threshold: isSet(object.threshold) ? Number(object.threshold) : 0, - disable: isSet(object.disable) ? Boolean(object.disable) : false, - }; - }, - toJSON(message) { - const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); - return obj; - }, -}; -function createBaseArtifactVerificationOptions_TlogIntegratedTimestampOptions() { - return { threshold: 0, disable: false }; + +/***/ }), + +/***/ 37105: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const parse = __nccwpck_require__(45240) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null } -exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = { - fromJSON(object) { - return { - threshold: isSet(object.threshold) ? Number(object.threshold) : 0, - disable: isSet(object.disable) ? Boolean(object.disable) : false, - }; - }, - toJSON(message) { - const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); - return obj; - }, -}; -function createBaseArtifactVerificationOptions_ObserverTimestampOptions() { - return { threshold: 0, disable: false }; +module.exports = valid + + +/***/ }), + +/***/ 41437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// just pre-load all the stuff that index.js lazily exports +const internalRe = __nccwpck_require__(84894) +const constants = __nccwpck_require__(83074) +const SemVer = __nccwpck_require__(95548) +const identifiers = __nccwpck_require__(98219) +const parse = __nccwpck_require__(45240) +const valid = __nccwpck_require__(37105) +const clean = __nccwpck_require__(64510) +const inc = __nccwpck_require__(55303) +const diff = __nccwpck_require__(84048) +const major = __nccwpck_require__(18610) +const minor = __nccwpck_require__(8550) +const patch = __nccwpck_require__(43413) +const prerelease = __nccwpck_require__(94729) +const compare = __nccwpck_require__(77304) +const rcompare = __nccwpck_require__(42810) +const compareLoose = __nccwpck_require__(90731) +const compareBuild = __nccwpck_require__(69685) +const sort = __nccwpck_require__(43151) +const rsort = __nccwpck_require__(91981) +const gt = __nccwpck_require__(35012) +const lt = __nccwpck_require__(63691) +const eq = __nccwpck_require__(5113) +const neq = __nccwpck_require__(26487) +const gte = __nccwpck_require__(67745) +const lte = __nccwpck_require__(27672) +const cmp = __nccwpck_require__(23991) +const coerce = __nccwpck_require__(3346) +const Comparator = __nccwpck_require__(39768) +const Range = __nccwpck_require__(60031) +const satisfies = __nccwpck_require__(10174) +const toComparators = __nccwpck_require__(9495) +const maxSatisfying = __nccwpck_require__(9412) +const minSatisfying = __nccwpck_require__(51670) +const minVersion = __nccwpck_require__(52981) +const validRange = __nccwpck_require__(61610) +const outside = __nccwpck_require__(23915) +const gtr = __nccwpck_require__(19691) +const ltr = __nccwpck_require__(38598) +const intersects = __nccwpck_require__(75956) +const simplifyRange = __nccwpck_require__(82757) +const subset = __nccwpck_require__(64) +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, } -exports.ArtifactVerificationOptions_ObserverTimestampOptions = { - fromJSON(object) { - return { - threshold: isSet(object.threshold) ? Number(object.threshold) : 0, - disable: isSet(object.disable) ? Boolean(object.disable) : false, - }; - }, - toJSON(message) { - const obj = {}; - message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); - message.disable !== undefined && (obj.disable = message.disable); - return obj; - }, -}; -function createBaseArtifact() { - return { data: undefined }; + + +/***/ }), + +/***/ 83074: +/***/ ((module) => { + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, } -exports.Artifact = { - fromJSON(object) { - return { - data: isSet(object.artifactUri) - ? { $case: "artifactUri", artifactUri: String(object.artifactUri) } - : isSet(object.artifact) - ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) } - : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.data?.$case === "artifactUri" && (obj.artifactUri = message.data?.artifactUri); - message.data?.$case === "artifact" && - (obj.artifact = message.data?.artifact !== undefined ? base64FromBytes(message.data?.artifact) : undefined); - return obj; - }, -}; -function createBaseInput() { - return { - artifactTrustRoot: undefined, - artifactVerificationOptions: undefined, - bundle: undefined, - artifact: undefined, - }; + + +/***/ }), + +/***/ 86912: +/***/ ((module) => { + +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug + + +/***/ }), + +/***/ 98219: +/***/ ((module) => { + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 } -exports.Input = { - fromJSON(object) { - return { - artifactTrustRoot: isSet(object.artifactTrustRoot) ? sigstore_trustroot_1.TrustedRoot.fromJSON(object.artifactTrustRoot) : undefined, - artifactVerificationOptions: isSet(object.artifactVerificationOptions) - ? exports.ArtifactVerificationOptions.fromJSON(object.artifactVerificationOptions) - : undefined, - bundle: isSet(object.bundle) ? sigstore_bundle_1.Bundle.fromJSON(object.bundle) : undefined, - artifact: isSet(object.artifact) ? exports.Artifact.fromJSON(object.artifact) : undefined, - }; - }, - toJSON(message) { - const obj = {}; - message.artifactTrustRoot !== undefined && - (obj.artifactTrustRoot = message.artifactTrustRoot ? sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot) : undefined); - message.artifactVerificationOptions !== undefined && - (obj.artifactVerificationOptions = message.artifactVerificationOptions - ? exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions) - : undefined); - message.bundle !== undefined && (obj.bundle = message.bundle ? sigstore_bundle_1.Bundle.toJSON(message.bundle) : undefined); - message.artifact !== undefined && (obj.artifact = message.artifact ? exports.Artifact.toJSON(message.artifact) : undefined); - return obj; - }, -}; -var tsProtoGlobalThis = (() => { - if (typeof globalThis !== "undefined") { - return globalThis; - } - if (typeof self !== "undefined") { - return self; - } - if (typeof window !== "undefined") { - return window; - } - if (typeof global !== "undefined") { - return global; - } - throw "Unable to locate global object"; -})(); -function bytesFromBase64(b64) { - if (tsProtoGlobalThis.Buffer) { - return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); - } - else { - const bin = tsProtoGlobalThis.atob(b64); - const arr = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; ++i) { - arr[i] = bin.charCodeAt(i); - } - return arr; - } + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, } -function base64FromBytes(arr) { - if (tsProtoGlobalThis.Buffer) { - return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); + + +/***/ }), + +/***/ 35986: +/***/ ((module) => { + +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value } - else { - const bin = []; - arr.forEach((byte) => { - bin.push(String.fromCharCode(byte)); - }); - return tsProtoGlobalThis.btoa(bin.join("")); + } + + delete (key) { + return this.map.delete(key) + } + + set (key, value) { + const deleted = this.delete(key) + + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } + + this.map.set(key, value) } + + return this + } } -function isSet(value) { - return value !== null && value !== undefined; -} + +module.exports = LRUCache /***/ }), -/***/ 19654: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 65939: +/***/ ((module) => { -"use strict"; +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* -Copyright 2023 The Sigstore Authors. + if (typeof options !== 'object') { + return looseOption + } -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + return options +} +module.exports = parseOptions - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -__exportStar(__nccwpck_require__(47030), exports); -__exportStar(__nccwpck_require__(70715), exports); -__exportStar(__nccwpck_require__(5334), exports); -__exportStar(__nccwpck_require__(85204), exports); -__exportStar(__nccwpck_require__(61997), exports); -__exportStar(__nccwpck_require__(99732), exports); +/***/ }), +/***/ 84894: +/***/ ((module, exports, __nccwpck_require__) => { -/***/ }), +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = __nccwpck_require__(83074) +const debug = __nccwpck_require__(86912) +exports = module.exports = {} -/***/ 43049: -/***/ ((__unused_webpack_module, exports) => { +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const safeSrc = exports.safeSrc = [] +const t = exports.t = {} +let R = 0 -"use strict"; +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseBundleBuilder = void 0; -// BaseBundleBuilder is a base class for BundleBuilder implementations. It -// provides a the basic wokflow for signing and witnessing an artifact. -// Subclasses must implement the `package` method to assemble a valid bundle -// with the generated signature and verification material. -class BaseBundleBuilder { - constructor(options) { - this.signer = options.signer; - this.witnesses = options.witnesses; - } - // Executes the signing/witnessing process for the given artifact. - async create(artifact) { - const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob)); - const bundle = await this.package(artifact, signature); - // Invoke all of the witnesses in parallel - const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key)))); - // Collect the verification material from all of the witnesses - const tlogEntryList = []; - const timestampList = []; - verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => { - tlogEntryList.push(...(tlogEntries ?? [])); - timestampList.push(...(rfc3161Timestamps ?? [])); - }); - // Merge the collected verification material into the bundle - bundle.verificationMaterial.tlogEntries = tlogEntryList; - bundle.verificationMaterial.timestampVerificationData = { - rfc3161Timestamps: timestampList, - }; - return bundle; - } - // Override this function to apply any pre-signing transformations to the - // artifact. The returned buffer will be signed by the signer. The default - // implementation simply returns the artifact data. - async prepare(artifact) { - return artifact.data; - } +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value } -exports.BaseBundleBuilder = BaseBundleBuilder; -// Extracts the public key from a KeyMaterial. Returns either the public key -// or the certificate, depending on the type of key material. -function publicKey(key) { - switch (key.$case) { - case 'publicKey': - return key.publicKey; - case 'x509Certificate': - return key.certificate; - } + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + safeSrc[index] = safe + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. -/***/ }), +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. -/***/ 85192: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') -"use strict"; +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toMessageSignatureBundle = toMessageSignatureBundle; -exports.toDSSEBundle = toDSSEBundle; -/* -Copyright 2023 The Sigstore Authors. +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// ## Main Version +// Three dot-separated numeric identifiers. - http://www.apache.org/licenses/LICENSE-2.0 +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const sigstore = __importStar(__nccwpck_require__(61040)); -const util_1 = __nccwpck_require__(19100); -// Helper functions for assembling the parts of a Sigstore bundle -// Message signature bundle - $case: 'messageSignature' -function toMessageSignatureBundle(artifact, signature) { - const digest = util_1.crypto.digest('sha256', artifact.data); - return sigstore.toMessageSignatureBundle({ - digest, - signature: signature.signature, - certificate: signature.key.$case === 'x509Certificate' - ? util_1.pem.toDER(signature.key.certificate) - : undefined, - keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, - certificateChain: true, - }); -} -// DSSE envelope bundle - $case: 'dsseEnvelope' -function toDSSEBundle(artifact, signature, certificateChain) { - return sigstore.toDSSEBundle({ - artifact: artifact.data, - artifactType: artifact.type, - signature: signature.signature, - certificate: signature.key.$case === 'x509Certificate' - ? util_1.pem.toDER(signature.key.certificate) - : undefined, - keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, - certificateChain, - }); -} +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. -/***/ }), +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) -/***/ 83997: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) -"use strict"; +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DSSEBundleBuilder = void 0; -/* -Copyright 2023 The Sigstore Authors. +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) - http://www.apache.org/licenses/LICENSE-2.0 +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const util_1 = __nccwpck_require__(19100); -const base_1 = __nccwpck_require__(43049); -const bundle_1 = __nccwpck_require__(85192); -// BundleBuilder implementation for DSSE wrapped attestations -class DSSEBundleBuilder extends base_1.BaseBundleBuilder { - constructor(options) { - super(options); - this.certificateChain = options.certificateChain ?? false; - } - // DSSE requires the artifact to be pre-encoded with the payload type - // before the signature is generated. - async prepare(artifact) { - const a = artifactDefaults(artifact); - return util_1.dsse.preAuthEncoding(a.type, a.data); - } - // Packages the artifact and signature into a DSSE bundle - async package(artifact, signature) { - return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.certificateChain); - } -} -exports.DSSEBundleBuilder = DSSEBundleBuilder; -// Defaults the artifact type to an empty string if not provided -function artifactDefaults(artifact) { - return { - ...artifact, - type: artifact.type ?? '', - }; -} +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. -/***/ }), +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) -/***/ 35530: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -"use strict"; +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; -var dsse_1 = __nccwpck_require__(83997); -Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } })); -var message_1 = __nccwpck_require__(8269); -Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } })); +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), -/***/ 8269: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 19691: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +// Determine if version is greater than all the versions possible in the range. +const outside = __nccwpck_require__(23915) +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MessageSignatureBundleBuilder = void 0; -/* -Copyright 2023 The Sigstore Authors. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +/***/ }), - http://www.apache.org/licenses/LICENSE-2.0 +/***/ 75956: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const base_1 = __nccwpck_require__(43049); -const bundle_1 = __nccwpck_require__(85192); -// BundleBuilder implementation for raw message signatures -class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder { - constructor(options) { - super(options); - } - async package(artifact, signature) { - return (0, bundle_1.toMessageSignatureBundle)(artifact, signature); - } +const Range = __nccwpck_require__(60031) +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) } -exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder; +module.exports = intersects /***/ }), -/***/ 97841: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 38598: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const outside = __nccwpck_require__(23915) +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr -/* -Copyright 2023 The Sigstore Authors. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +/***/ }), - http://www.apache.org/licenses/LICENSE-2.0 +/***/ 9412: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InternalError = void 0; -exports.internalError = internalError; -const error_1 = __nccwpck_require__(40369); -class InternalError extends Error { - constructor({ code, message, cause, }) { - super(message); - this.name = this.constructor.name; - this.cause = cause; - this.code = code; +const SemVer = __nccwpck_require__(95548) +const Range = __nccwpck_require__(60031) + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } } + }) + return max } -exports.InternalError = InternalError; -function internalError(err, code, message) { - if (err instanceof error_1.HTTPError) { - message += ` - ${err.message}`; +module.exports = maxSatisfying + + +/***/ }), + +/***/ 51670: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const SemVer = __nccwpck_require__(95548) +const Range = __nccwpck_require__(60031) +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } } - throw new InternalError({ - code: code, - message: message, - cause: err, - }); + }) + return min } +module.exports = minSatisfying /***/ }), -/***/ 40369: -/***/ ((__unused_webpack_module, exports) => { +/***/ 52981: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const SemVer = __nccwpck_require__(95548) +const Range = __nccwpck_require__(60031) +const gt = __nccwpck_require__(35012) -/* -Copyright 2023 The Sigstore Authors. +const minVersion = (range, loose) => { + range = new Range(range, loose) -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } - http://www.apache.org/licenses/LICENSE-2.0 + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HTTPError = void 0; -class HTTPError extends Error { - constructor({ status, message, location, }) { - super(`(${status}) ${message}`); - this.statusCode = status; - this.location = location; + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin } + } + + if (minver && range.test(minver)) { + return minver + } + + return null } -exports.HTTPError = HTTPError; +module.exports = minVersion /***/ }), -/***/ 9823: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 23915: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const SemVer = __nccwpck_require__(95548) +const Comparator = __nccwpck_require__(39768) +const { ANY } = Comparator +const Range = __nccwpck_require__(60031) +const satisfies = __nccwpck_require__(10174) +const gt = __nccwpck_require__(35012) +const lt = __nccwpck_require__(63691) +const lte = __nccwpck_require__(27672) +const gte = __nccwpck_require__(67745) -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fetchWithRetry = fetchWithRetry; -/* -Copyright 2023 The Sigstore Authors. +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } - http://www.apache.org/licenses/LICENSE-2.0 + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const http2_1 = __nccwpck_require__(85675); -const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310)); -const proc_log_1 = __nccwpck_require__(26687); -const promise_retry_1 = __importDefault(__nccwpck_require__(90390)); -const util_1 = __nccwpck_require__(19100); -const error_1 = __nccwpck_require__(40369); -const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants; -async function fetchWithRetry(url, options) { - return (0, promise_retry_1.default)(async (retry, attemptNum) => { - const method = options.method || 'POST'; - const headers = { - [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(), - ...options.headers, - }; - const response = await (0, make_fetch_happen_1.default)(url, { - method, - headers, - body: options.body, - timeout: options.timeout, - retry: false, // We're handling retries ourselves - }).catch((reason) => { - proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`); - return retry(reason); - }); - if (response.ok) { - return response; - } - else { - const error = await errorFromResponse(response); - proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`); - if (retryable(response.status)) { - return retry(error); - } - else { - throw error; - } - } - }, retryOpts(options.retry)); -} -// Translate a Response into an HTTPError instance. This will attempt to parse -// the response body for a message, but will default to the statusText if none -// is found. -const errorFromResponse = async (response) => { - let message = response.statusText; - const location = response.headers.get(HTTP2_HEADER_LOCATION) || undefined; - const contentType = response.headers.get(HTTP2_HEADER_CONTENT_TYPE); - // If response type is JSON, try to parse the body for a message - if (contentType?.includes('application/json')) { - try { - const body = await response.json(); - message = body.message || message; - } - catch (e) { - // ignore - } - } - return new error_1.HTTPError({ - status: response.status, - message: message, - location: location, - }); -}; -// Determine if a status code is retryable. This includes 5xx errors, 408, and -// 429. -const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR; -// Normalize the retry options to the format expected by promise-retry -const retryOpts = (retry) => { - if (typeof retry === 'boolean') { - return { retries: retry ? 1 : 0 }; - } - else if (typeof retry === 'number') { - return { retries: retry }; - } - else { - return { retries: 0, ...retry }; - } -}; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] -/***/ }), + let high = null + let low = null -/***/ 26819: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) -"use strict"; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Fulcio = void 0; -/* -Copyright 2023 The Sigstore Authors. + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +module.exports = outside - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const fetch_1 = __nccwpck_require__(9823); -/** - * Fulcio API client. - */ -class Fulcio { - constructor(options) { - this.options = options; +/***/ }), + +/***/ 82757: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __nccwpck_require__(10174) +const compare = __nccwpck_require__(77304) +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null } - async createSigningCertificate(request) { - const { baseURL, retry, timeout } = this.options; - const url = `${baseURL}/api/v2/signingCert`; - const response = await (0, fetch_1.fetchWithRetry)(url, { - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(request), - timeout, - retry, - }); - return response.json(); + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range } -exports.Fulcio = Fulcio; /***/ }), -/***/ 32688: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 64: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const Range = __nccwpck_require__(60031) +const Comparator = __nccwpck_require__(39768) +const { ANY } = Comparator +const satisfies = __nccwpck_require__(10174) +const compare = __nccwpck_require__(77304) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Rekor = void 0; -/* -Copyright 2023 The Sigstore Authors. +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } - http://www.apache.org/licenses/LICENSE-2.0 + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const fetch_1 = __nccwpck_require__(9823); -/** - * Rekor API client. - */ -class Rekor { - constructor(options) { - this.options = options; - } - /** - * Create a new entry in the Rekor log. - * @param propsedEntry {ProposedEntry} Data to create a new entry - * @returns {Promise} The created entry - */ - async createEntry(propsedEntry) { - const { baseURL, timeout, retry } = this.options; - const url = `${baseURL}/api/v1/log/entries`; - const response = await (0, fetch_1.fetchWithRetry)(url, { - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json', - }, - body: JSON.stringify(propsedEntry), - timeout, - retry, - }); - const data = await response.json(); - return entryFromResponse(data); - } - /** - * Get an entry from the Rekor log. - * @param uuid {string} The UUID of the entry to retrieve - * @returns {Promise} The retrieved entry - */ - async getEntry(uuid) { - const { baseURL, timeout, retry } = this.options; - const url = `${baseURL}/api/v1/log/entries/${uuid}`; - const response = await (0, fetch_1.fetchWithRetry)(url, { - method: 'GET', - headers: { - Accept: 'application/json', - }, - timeout, - retry, - }); - const data = await response.json(); - return entryFromResponse(data); + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } } -} -exports.Rekor = Rekor; -// Unpack the response from the Rekor API into a more convenient format. -function entryFromResponse(data) { - const entries = Object.entries(data); - if (entries.length != 1) { - throw new Error('Received multiple entries in Rekor response'); + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false } - // Grab UUID and entry data from the response - const [uuid, entry] = entries[0]; - return { - ...entry, - uuid, - }; + } + return true } +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] -/***/ }), +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } -/***/ 78963: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } -"use strict"; + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TimestampAuthority = void 0; -/* -Copyright 2023 The Sigstore Authors. + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + if (eqSet.size > 1) { + return null + } - http://www.apache.org/licenses/LICENSE-2.0 + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const fetch_1 = __nccwpck_require__(9823); -class TimestampAuthority { - constructor(options) { - this.options = options; + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null } - async createTimestamp(request) { - const { baseURL, timeout, retry } = this.options; - const url = `${baseURL}/api/v1/timestamp`; - const response = await (0, fetch_1.fetchWithRetry)(url, { - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(request), - timeout, - retry, - }); - return response.buffer(); + + if (lt && !satisfies(eq, String(lt), options)) { + return null } -} -exports.TimestampAuthority = TimestampAuthority; + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } -/***/ }), + return true + } -/***/ 92092: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } -"use strict"; + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CIContextProvider = void 0; -/* -Copyright 2023 The Sigstore Authors. + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } - http://www.apache.org/licenses/LICENSE-2.0 + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310)); -// Collection of all the CI-specific providers we have implemented -const providers = [getGHAToken, getEnv]; -/** - * CIContextProvider is a composite identity provider which will iterate - * over all of the CI-specific providers and return the token from the first - * one that resolves. - */ -class CIContextProvider { - /* istanbul ignore next */ - constructor(audience = 'sigstore') { - this.audience = audience; - } - // Invoke all registered ProviderFuncs and return the value of whichever one - // resolves first. - async getToken() { - return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available')); - } + return true } -exports.CIContextProvider = CIContextProvider; -/** - * getGHAToken can retrieve an OIDC token when running in a GitHub Actions - * workflow - */ -async function getGHAToken(audience) { - // Check to see if we're running in GitHub Actions - if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || - !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { - return Promise.reject('no token available'); - } - // Construct URL to request token w/ appropriate audience - const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL); - url.searchParams.append('audience', audience); - const response = await (0, make_fetch_happen_1.default)(url.href, { - retry: 2, - headers: { - Accept: 'application/json', - Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, - }, - }); - return response.json().then((data) => data.value); + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a } -/** - * getEnv can retrieve an OIDC token from an environment variable. - * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar - */ -async function getEnv() { - if (!process.env.SIGSTORE_ID_TOKEN) { - return Promise.reject('no token available'); - } - return process.env.SIGSTORE_ID_TOKEN; + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a } +module.exports = subset + /***/ }), -/***/ 55022: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 9495: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const Range = __nccwpck_require__(60031) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CIContextProvider = void 0; -/* -Copyright 2023 The Sigstore Authors. +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +module.exports = toComparators - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var ci_1 = __nccwpck_require__(92092); -Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return ci_1.CIContextProvider; } })); +/***/ }), + +/***/ 61610: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const Range = __nccwpck_require__(60031) +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange /***/ }), -/***/ 15179: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 77864: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; -var bundler_1 = __nccwpck_require__(35530); -Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } })); -Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } })); -var error_1 = __nccwpck_require__(97841); -Object.defineProperty(exports, "InternalError", ({ enumerable: true, get: function () { return error_1.InternalError; } })); -var identity_1 = __nccwpck_require__(55022); -Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return identity_1.CIContextProvider; } })); -var signer_1 = __nccwpck_require__(34342); -Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } })); -Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return signer_1.FulcioSigner; } })); -var witness_1 = __nccwpck_require__(55383); -Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } })); -Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return witness_1.RekorWitness; } })); -Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return witness_1.TSAWitness; } })); +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/auth.js +var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +var REGEX_IS_INSTALLATION = /^ghs_/; +var REGEX_IS_USER_TO_SERVER = /^ghu_/; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 5875: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 61897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CAClient = void 0; -/* -Copyright 2023 The Sigstore Authors. +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(dist_src_exports); +var import_universal_user_agent = __nccwpck_require__(33843); +var import_before_after_hook = __nccwpck_require__(52732); +var import_request = __nccwpck_require__(66255); +var import_graphql = __nccwpck_require__(70007); +var import_auth_token = __nccwpck_require__(77864); - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/version.js +var VERSION = "5.1.0"; -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const error_1 = __nccwpck_require__(97841); -const fulcio_1 = __nccwpck_require__(26819); -class CAClient { - constructor(options) { - this.fulcio = new fulcio_1.Fulcio({ - baseURL: options.fulcioBaseURL, - retry: options.retry, - timeout: options.timeout, +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var Octokit = class { + static { + this.VERSION = VERSION; + } + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static { + this.plugins = []; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static { + this.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + } + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new import_before_after_hook.Collection(); + const requestDefaults = { + baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = import_request.request.defaults(requestDefaults); + this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); + this.log = Object.assign( + { + debug: noop, + info: noop, + warn: consoleWarn, + error: consoleError + }, + options.log + ); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" }); + } else { + const auth = (0, import_auth_token.createTokenAuth)(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; } - async createSigningCertificate(identityToken, publicKey, challenge) { - const request = toCertificateRequest(identityToken, publicKey, challenge); - try { - const resp = await this.fulcio.createSigningCertificate(request); - // Account for the fact that the response may contain either a - // signedCertificateEmbeddedSct or a signedCertificateDetachedSct. - const cert = resp.signedCertificateEmbeddedSct - ? resp.signedCertificateEmbeddedSct - : resp.signedCertificateDetachedSct; - return cert.chain.certificates; - } - catch (err) { - (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate'); - } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); } -} -exports.CAClient = CAClient; -function toCertificateRequest(identityToken, publicKey, challenge) { - return { - credentials: { - oidcIdentityToken: identityToken, - }, - publicKeyRequest: { - publicKey: { - algorithm: 'ECDSA', - content: publicKey, - }, - proofOfPossession: challenge.toString('base64'), - }, - }; -} + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 97064: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 54471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.EphemeralSigner = void 0; -/* -Copyright 2023 The Sigstore Authors. +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(33843); -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const crypto_1 = __importDefault(__nccwpck_require__(76982)); -const EC_KEYPAIR_TYPE = 'ec'; -const P256_CURVE = 'P-256'; -// Signer implementation which uses an ephemeral keypair to sign artifacts. -// The private key lives only in memory and is tied to the lifetime of the -// EphemeralSigner instance. -class EphemeralSigner { - constructor() { - this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, { - namedCurve: P256_CURVE, - }); - } - async sign(data) { - const signature = crypto_1.default.sign(null, data, this.keypair.privateKey); - const publicKey = this.keypair.publicKey - .export({ format: 'pem', type: 'spki' }) - .toString('ascii'); - return { - signature: signature, - key: { $case: 'publicKey', publicKey }, - }; - } +// pkg/dist-src/version.js +var VERSION = "9.0.4"; + +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; + +// pkg/dist-src/util/lowercase-keys.js +function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); } -exports.EphemeralSigner = EphemeralSigner; +// pkg/dist-src/util/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} -/***/ }), +// pkg/dist-src/util/merge-deep.js +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} -/***/ 26303: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} -"use strict"; +// pkg/dist-src/merge.js +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; -/* -Copyright 2023 The Sigstore Authors. +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); +} +function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); + if (!matches) { + return []; + } + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); +} - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; +} -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const error_1 = __nccwpck_require__(97841); -const util_1 = __nccwpck_require__(19100); -const ca_1 = __nccwpck_require__(5875); -const ephemeral_1 = __nccwpck_require__(97064); -exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev'; -// Signer implementation which can be used to decorate another signer -// with a Fulcio-issued signing certificate for the signer's public key. -// Must be instantiated with an identity provider which can provide a JWT -// which represents the identity to be bound to the signing certificate. -class FulcioSigner { - constructor(options) { - this.ca = new ca_1.CAClient({ - ...options, - fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL, - }); - this.identityProvider = options.identityProvider; - this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner(); +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } - async sign(data) { - // Retrieve identity token from the supplied identity provider - const identityToken = await this.getIdentityToken(); - // Extract challenge claim from OIDC token - let subject; - try { - subject = util_1.oidc.extractJWTSubject(identityToken); + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); } - catch (err) { - throw new error_1.InternalError({ - code: 'IDENTITY_TOKEN_PARSE_ERROR', - message: `invalid identity token: ${identityToken}`, - cause: err, - }); + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); } - // Construct challenge value by signing the subject claim - const challenge = await this.keyHolder.sign(Buffer.from(subject)); - if (challenge.key.$case !== 'publicKey') { - throw new error_1.InternalError({ - code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', - message: 'unexpected format for signing key', - }); + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } - // Create signing certificate - const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature); - // Generate artifact signature - const signature = await this.keyHolder.sign(data); - // Specifically returning only the first certificate in the chain - // as the key. - return { - signature: signature.signature, - key: { - $case: 'x509Certificate', - certificate: certificates[0], - }, - }; + } } - async getIdentityToken() { - try { - return await this.identityProvider.getToken(); + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); } - catch (err) { - throw new error_1.InternalError({ - code: 'IDENTITY_TOKEN_READ_ERROR', - message: 'error retrieving identity token', - cause: err, - }); + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} + +// pkg/dist-src/parse.js +function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); } -exports.FulcioSigner = FulcioSigner; - - -/***/ }), - -/***/ 34342: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; - -/* istanbul ignore file */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/with-defaults.js +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var fulcio_1 = __nccwpck_require__(26303); -Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } })); -Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return fulcio_1.FulcioSigner; } })); +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 19100: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 70007: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var core_1 = __nccwpck_require__(83917); -Object.defineProperty(exports, "crypto", ({ enumerable: true, get: function () { return core_1.crypto; } })); -Object.defineProperty(exports, "dsse", ({ enumerable: true, get: function () { return core_1.dsse; } })); -Object.defineProperty(exports, "encoding", ({ enumerable: true, get: function () { return core_1.encoding; } })); -Object.defineProperty(exports, "json", ({ enumerable: true, get: function () { return core_1.json; } })); -Object.defineProperty(exports, "pem", ({ enumerable: true, get: function () { return core_1.pem; } })); -exports.oidc = __importStar(__nccwpck_require__(81963)); -exports.ua = __importStar(__nccwpck_require__(81268)); - - -/***/ }), - -/***/ 81963: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -"use strict"; +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(dist_src_exports); +var import_request3 = __nccwpck_require__(66255); +var import_universal_user_agent = __nccwpck_require__(33843); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.extractJWTSubject = extractJWTSubject; -/* -Copyright 2023 The Sigstore Authors. +// pkg/dist-src/version.js +var VERSION = "7.0.2"; -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(66255); - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(66255); -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const core_1 = __nccwpck_require__(83917); -function extractJWTSubject(jwt) { - const parts = jwt.split('.', 3); - const payload = JSON.parse(core_1.encoding.base64Decode(parts[1])); - switch (payload.iss) { - case 'https://accounts.google.com': - case 'https://oauth2.sigstore.dev/auth': - return payload.email; - default: - return payload.sub; - } +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } - - -/***/ }), - -/***/ 81268: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getUserAgent = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const os_1 = __importDefault(__nccwpck_require__(70857)); -// Format User-Agent: / () -// source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent -const getUserAgent = () => { - const packageVersion = (__nccwpck_require__(85896)/* .version */ .rE); - const nodeVersion = process.version; - const platformName = os_1.default.platform(); - const archName = os_1.default.arch(); - return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`; +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } }; -exports.getUserAgent = getUserAgent; - - -/***/ }), - -/***/ 55383: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* istanbul ignore file */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var tlog_1 = __nccwpck_require__(2566); -Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } })); -Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return tlog_1.RekorWitness; } })); -var tsa_1 = __nccwpck_require__(66936); -Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return tsa_1.TSAWitness; } })); - - -/***/ }), - -/***/ 42815: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TLogClient = void 0; -/* -Copyright 2023 The Sigstore Authors. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const error_1 = __nccwpck_require__(97841); -const error_2 = __nccwpck_require__(40369); -const rekor_1 = __nccwpck_require__(32688); -class TLogClient { - constructor(options) { - this.fetchOnConflict = options.fetchOnConflict ?? false; - this.rekor = new rekor_1.Rekor({ - baseURL: options.rekorBaseURL, - retry: options.retry, - timeout: options.timeout, - }); +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); } - async createEntry(proposedEntry) { - let entry; - try { - entry = await this.rekor.createEntry(proposedEntry); - } - catch (err) { - // If the entry already exists, fetch it (if enabled) - if (entryExistsError(err) && this.fetchOnConflict) { - // Grab the UUID of the existing entry from the location header - /* istanbul ignore next */ - const uuid = err.location.split('/').pop() || ''; - try { - entry = await this.rekor.getEntry(uuid); - } - catch (err) { - (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry'); - } - } - else { - (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry'); - } - } - return entry; + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) + continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); } -} -exports.TLogClient = TLogClient; -function entryExistsError(value) { - return (value instanceof error_2.HTTPError && - value.statusCode === 409 && - value.location !== undefined); -} - - -/***/ }), - -/***/ 97890: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toProposedEntry = toProposedEntry; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const bundle_1 = __nccwpck_require__(61040); -const util_1 = __nccwpck_require__(19100); -const SHA256_ALGORITHM = 'sha256'; -function toProposedEntry(content, publicKey, -// TODO: Remove this parameter once have completely switched to 'dsse' entries -entryType = 'dsse') { - switch (content.$case) { - case 'dsseEnvelope': - // TODO: Remove this conditional once have completely ditched "intoto" entries - if (entryType === 'intoto') { - return toProposedIntotoEntry(content.dsseEnvelope, publicKey); - } - return toProposedDSSEEntry(content.dsseEnvelope, publicKey); - case 'messageSignature': - return toProposedHashedRekordEntry(content.messageSignature, publicKey); + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; } -} -// Returns a properly formatted Rekor "hashedrekord" entry for the given digest -// and signature -function toProposedHashedRekordEntry(messageSignature, publicKey) { - const hexDigest = messageSignature.messageDigest.digest.toString('hex'); - const b64Signature = messageSignature.signature.toString('base64'); - const b64Key = util_1.encoding.base64Encode(publicKey); - return { - apiVersion: '0.0.1', - kind: 'hashedrekord', - spec: { - data: { - hash: { - algorithm: SHA256_ALGORITHM, - value: hexDigest, - }, - }, - signature: { - content: b64Signature, - publicKey: { - content: b64Key, - }, - }, - }, - }; -} -// Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope -// and signature -function toProposedDSSEEntry(envelope, publicKey) { - const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope)); - const encodedKey = util_1.encoding.base64Encode(publicKey); - return { - apiVersion: '0.0.1', - kind: 'dsse', - spec: { - proposedContent: { - envelope: envelopeJSON, - verifiers: [encodedKey], - }, - }, - }; -} -// Returns a properly formatted Rekor "intoto" entry for the given DSSE -// envelope and signature -function toProposedIntotoEntry(envelope, publicKey) { - // Calculate the value for the payloadHash field in the Rekor entry - const payloadHash = util_1.crypto - .digest(SHA256_ALGORITHM, envelope.payload) - .toString('hex'); - // Calculate the value for the hash field in the Rekor entry - const envelopeHash = calculateDSSEHash(envelope, publicKey); - // Collect values for re-creating the DSSE envelope. - // Double-encode payload and signature cause that's what Rekor expects - const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64')); - const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64')); - const keyid = envelope.signatures[0].keyid; - const encodedKey = util_1.encoding.base64Encode(publicKey); - // Create the envelope portion of the entry. Note the inclusion of the - // publicKey in the signature struct is not a standard part of a DSSE - // envelope, but is required by Rekor. - const dsse = { - payloadType: envelope.payloadType, - payload: payload, - signatures: [{ sig, publicKey: encodedKey }], - }; - // If the keyid is an empty string, Rekor seems to remove it altogether. We - // need to do the same here so that we can properly recreate the entry for - // verification. - if (keyid.length > 0) { - dsse.signatures[0].keyid = keyid; + if (!result.variables) { + result.variables = {}; } - return { - apiVersion: '0.0.2', - kind: 'intoto', - spec: { - content: { - envelope: dsse, - hash: { algorithm: SHA256_ALGORITHM, value: envelopeHash }, - payloadHash: { algorithm: SHA256_ALGORITHM, value: payloadHash }, - }, - }, - }; -} -// Calculates the hash of a DSSE envelope for inclusion in a Rekor entry. -// There is no standard way to do this, so the scheme we're using as as -// follows: -// * payload is base64 encoded -// * signature is base64 encoded (only the first signature is used) -// * keyid is included ONLY if it is NOT an empty string -// * The resulting JSON is canonicalized and hashed to a hex string -function calculateDSSEHash(envelope, publicKey) { - const dsse = { - payloadType: envelope.payloadType, - payload: envelope.payload.toString('base64'), - signatures: [ - { sig: envelope.signatures[0].sig.toString('base64'), publicKey }, - ], - }; - // If the keyid is an empty string, Rekor seems to remove it altogether. - if (envelope.signatures[0].keyid.length > 0) { - dsse.signatures[0].keyid = envelope.signatures[0].keyid; + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); } - return util_1.crypto - .digest(SHA256_ALGORITHM, util_1.json.canonicalize(dsse)) - .toString('hex'); + return response.data.data; + }); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} + +// pkg/dist-src/index.js +var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); } +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 2566: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 38082: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; -/* -Copyright 2023 The Sigstore Authors. +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/version.js +var VERSION = "9.2.2"; -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const util_1 = __nccwpck_require__(19100); -const client_1 = __nccwpck_require__(42815); -const entry_1 = __nccwpck_require__(97890); -exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev'; -class RekorWitness { - constructor(options) { - this.entryType = options.entryType; - this.tlog = new client_1.TLogClient({ - ...options, - rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL, - }); - } - async testify(content, publicKey) { - const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType); - const entry = await this.tlog.createEntry(proposedEntry); - return toTransparencyLogEntry(entry); - } -} -exports.RekorWitness = RekorWitness; -function toTransparencyLogEntry(entry) { - const logID = Buffer.from(entry.logID, 'hex'); - // Parse entry body so we can extract the kind and version. - const bodyJSON = util_1.encoding.base64Decode(entry.body); - const entryBody = JSON.parse(bodyJSON); - const promise = entry?.verification?.signedEntryTimestamp - ? inclusionPromise(entry.verification.signedEntryTimestamp) - : undefined; - const proof = entry?.verification?.inclusionProof - ? inclusionProof(entry.verification.inclusionProof) - : undefined; - const tlogEntry = { - logIndex: entry.logIndex.toString(), - logId: { - keyId: logID, - }, - integratedTime: entry.integratedTime.toString(), - kindVersion: { - kind: entryBody.kind, - version: entryBody.apiVersion, - }, - inclusionPromise: promise, - inclusionProof: proof, - canonicalizedBody: Buffer.from(entry.body, 'base64'), - }; - return { - tlogEntries: [tlogEntry], - }; -} -function inclusionPromise(promise) { - return { - signedEntryTimestamp: Buffer.from(promise, 'base64'), - }; -} -function inclusionProof(proof) { +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { return { - logIndex: proof.logIndex.toString(), - treeSize: proof.treeSize.toString(), - rootHash: Buffer.from(proof.rootHash, 'hex'), - hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')), - checkpoint: { - envelope: proof.checkpoint, - }, + ...response, + data: [] }; + } + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) + return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + return response; } - -/***/ }), - -/***/ 97409: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TSAClient = void 0; -/* -Copyright 2023 The Sigstore Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const error_1 = __nccwpck_require__(97841); -const tsa_1 = __nccwpck_require__(78963); -const util_1 = __nccwpck_require__(19100); -const SHA256_ALGORITHM = 'sha256'; -class TSAClient { - constructor(options) { - this.tsa = new tsa_1.TimestampAuthority({ - baseURL: options.tsaBaseURL, - retry: options.retry, - timeout: options.timeout, - }); - } - async createTimestamp(signature) { - const request = { - artifactHash: util_1.crypto - .digest(SHA256_ALGORITHM, signature) - .toString('base64'), - hashAlgorithm: SHA256_ALGORITHM, - }; +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) + return { done: true }; try { - return await this.tsa.createTimestamp(request); - } - catch (err) { - (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp'); + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) + throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; } - } + } + }) + }; } -exports.TSAClient = TSAClient; - - -/***/ }), - -/***/ 66936: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TSAWitness = void 0; -/* -Copyright 2023 The Sigstore Authors. +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); - http://www.apache.org/licenses/LICENSE-2.0 +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const client_1 = __nccwpck_require__(97409); -class TSAWitness { - constructor(options) { - this.tsa = new client_1.TSAClient({ - tsaBaseURL: options.tsaBaseURL, - retry: options.retry, - timeout: options.timeout, - }); - } - async testify(content) { - const signature = extractSignature(content); - const timestamp = await this.tsa.createTimestamp(signature); - return { - rfc3161Timestamps: [{ signedTimestamp: timestamp }], - }; - } +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } } -exports.TSAWitness = TSAWitness; -function extractSignature(content) { - switch (content.$case) { - case 'dsseEnvelope': - return content.dsseEnvelope.signatures[0].sig; - case 'messageSignature': - return content.messageSignature.signature; - } + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; } +paginateRest.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 15183: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 84935: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods }); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/version.js +var VERSION = "10.3.0"; + +// pkg/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotForBusinessSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotForBusinessSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" + } + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployment"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.req = exports.json = exports.toBuffer = void 0; -const http = __importStar(__nccwpck_require__(58611)); -const https = __importStar(__nccwpck_require__(65692)); -async function toBuffer(stream) { - let length = 0; - const chunks = []; - for await (const chunk of stream) { - length += chunk.length; - chunks.push(chunk); - } - return Buffer.concat(chunks, length); -} -exports.toBuffer = toBuffer; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -async function json(stream) { - const buf = await toBuffer(stream); - const str = buf.toString('utf8'); - try { - return JSON.parse(str); - } - catch (_err) { - const err = _err; - err.message += ` (input: ${str})`; - throw err; - } -} -exports.json = json; -function req(url, opts = {}) { - const href = typeof url === 'string' ? url : url.href; - const req = (href.startsWith('https:') ? https : http).request(url, opts); - const promise = new Promise((resolve, reject) => { - req - .once('response', resolve) - .once('error', reject) - .end(); - }); - req.then = promise.then.bind(promise); - return req; -} -exports.req = req; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 98894: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; +var endpoints_default = Endpoints; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Agent = void 0; -const net = __importStar(__nccwpck_require__(69278)); -const http = __importStar(__nccwpck_require__(58611)); -const https_1 = __nccwpck_require__(65692); -__exportStar(__nccwpck_require__(15183), exports); -const INTERNAL = Symbol('AgentBaseInternalState'); -class Agent extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; - } - /** - * Determine whether this is an `http` or `https` request. - */ - isSecureEndpoint(options) { - if (options) { - // First check the `secureEndpoint` property explicitly, since this - // means that a parent `Agent` is "passing through" to this instance. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof options.secureEndpoint === 'boolean') { - return options.secureEndpoint; - } - // If no explicit `secure` endpoint, check if `protocol` property is - // set. This will usually be the case since using a full string URL - // or `URL` instance should be the most common usage. - if (typeof options.protocol === 'string') { - return options.protocol === 'https:'; - } - } - // Finally, if no `protocol` property was set, then fall back to - // checking the stack trace of the current call stack, and try to - // detect the "https" module. - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack - .split('\n') - .some((l) => l.indexOf('(https.js:') !== -1 || - l.indexOf('node:https:') !== -1); - } - // In order to support async signatures in `connect()` and Node's native - // connection pooling in `http.Agent`, the array of sockets for each origin - // has to be updated synchronously. This is so the length of the array is - // accurate when `addRequest()` is next called. We achieve this by creating a - // fake socket and adding it to `sockets[origin]` and incrementing - // `totalSocketCount`. - incrementSockets(name) { - // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no - // need to create a fake socket because Node.js native connection pooling - // will never be invoked. - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; - } - // All instances of `sockets` are expected TypeScript errors. The - // alternative is to add it as a private property of this class but that - // will break TypeScript subclassing. - if (!this.sockets[name]) { - // @ts-expect-error `sockets` is readonly in `@types/node` - this.sockets[name] = []; - } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` - this.totalSocketCount++; - return fakeSocket; - } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; - } - const sockets = this.sockets[name]; - const index = sockets.indexOf(socket); - if (index !== -1) { - sockets.splice(index, 1); - // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` - this.totalSocketCount--; - if (sockets.length === 0) { - // @ts-expect-error `sockets` is readonly in `@types/node` - delete this.sockets[name]; - } - } - } - // In order to properly update the socket pool, we need to call `getName()` on - // the core `https.Agent` if it is a secureEndpoint. - getName(options) { - const secureEndpoint = typeof options.secureEndpoint === 'boolean' - ? options.secureEndpoint - : this.isSecureEndpoint(options); - if (secureEndpoint) { - // @ts-expect-error `getName()` isn't defined in `@types/node` - return https_1.Agent.prototype.getName.call(this, options); - } - // @ts-expect-error `getName()` isn't defined in `@types/node` - return super.getName(options); - } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options), - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve() - .then(() => this.connect(req, connectOpts)) - .then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - // @ts-expect-error `addRequest()` isn't defined in `@types/node` - return socket.addRequest(req, connectOpts); - } - this[INTERNAL].currentSocket = socket; - // @ts-expect-error `createSocket()` isn't defined in `@types/node` - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); - } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = undefined; - if (!socket) { - throw new Error('No socket was returned in the `connect()` function'); - } - return socket; - } - get defaultPort() { - return (this[INTERNAL].defaultPort ?? - (this.protocol === 'https:' ? 443 : 80)); - } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; - } - } - get protocol() { - return (this[INTERNAL].protocol ?? - (this.isSecureEndpoint() ? 'https:' : 'http:')); - } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; - } +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } } -exports.Agent = Agent; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 59380: -/***/ ((module) => { - -"use strict"; - -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - if(a===b) { - return [ai, bi]; +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; } - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; } - - if (begs.length) { - result = [ left, right ]; + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); } + return cache[methodName]; } - - return result; -} - - -/***/ }), - -/***/ 52732: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(11063); -var addHook = __nccwpck_require__(22027); -var removeHook = __nccwpck_require__(59934); - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); - -function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); -} - -function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} - -function HookCollection() { - var state = { - registry: {}, - }; - - var hook = register.bind(null, state); - bindApi(hook, state); - - return hook; -} - -var collectionHookDeprecationMessageDisplayed = false; -function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } - return HookCollection(); + return newMethods; } - -Hook.Singular = HookSingular.bind(); -Hook.Collection = HookCollection.bind(); - -module.exports = Hook; -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook; -module.exports.Singular = Hook.Singular; -module.exports.Collection = Hook.Collection; - - -/***/ }), - -/***/ 22027: -/***/ ((module) => { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args); } + return Object.assign(withDecorations, requestWithDefaults); +} - state.registry[name].push({ - hook: hook, - orig: orig, - }); +// pkg/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; } +legacyRestEndpointMethods.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 11063: -/***/ ((module) => { +/***/ 33450: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = register; +"use strict"; -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__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: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - if (!options) { - options = {}; - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + VERSION: () => VERSION, + retry: () => retry +}); +module.exports = __toCommonJS(dist_src_exports); +var import_core = __nccwpck_require__(61897); - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); +// pkg/dist-src/error-request.js +async function errorRequest(state, octokit, error, options) { + if (!error.request || !error.request.request) { + throw error; } + if (error.status >= 400 && !state.doNotRetry.includes(error.status)) { + const retries = options.request.retries != null ? options.request.retries : state.retries; + const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); + throw octokit.retry.retryRequest(error, retries, retryAfter); + } + throw error; +} - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); +// pkg/dist-src/wrap-request.js +var import_light = __toESM(__nccwpck_require__(63251)); +var import_request_error = __nccwpck_require__(93708); +async function wrapRequest(state, octokit, request, options) { + const limiter = new import_light.default(); + limiter.on("failed", function(error, info) { + const maxRetries = ~~error.request.request.retries; + const after = ~~error.request.request.retryAfter; + options.request.retryCount = info.retryCount + 1; + if (maxRetries > info.retryCount) { + return after * state.retryAfterBaseValue; } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); }); + return limiter.schedule( + requestWithGraphqlErrorHandling.bind(null, state, octokit, request), + options + ); } - - -/***/ }), - -/***/ 59934: -/***/ ((module) => { - -module.exports = removeHook; - -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; +async function requestWithGraphqlErrorHandling(state, octokit, request, options) { + const response = await request(request, options); + if (response.data && response.data.errors && /Something went wrong while executing your query/.test( + response.data.errors[0].message + )) { + const error = new import_request_error.RequestError(response.data.errors[0].message, 500, { + request: options, + response + }); + return errorRequest(state, octokit, error, options); } + return response; +} - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); - - if (index === -1) { - return; +// pkg/dist-src/index.js +var VERSION = "6.0.1"; +function retry(octokit, octokitOptions) { + const state = Object.assign( + { + enabled: true, + retryAfterBaseValue: 1e3, + doNotRetry: [400, 401, 403, 404, 422, 451], + retries: 3 + }, + octokitOptions.retry + ); + if (state.enabled) { + octokit.hook.error("request", errorRequest.bind(null, state, octokit)); + octokit.hook.wrap("request", wrapRequest.bind(null, state, octokit)); } - - state.registry[name].splice(index, 1); + return { + retry: { + retryRequest: (error, retries, retryAfter) => { + error.request.request = Object.assign({}, error.request.request, { + retries, + retryAfter + }); + return error; + } + } + }; } +retry.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); /***/ }), -/***/ 63251: -/***/ (function(module) { - -/** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } - - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; - - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; - - var parser = { - load: load, - overwrite: overwrite - }; - - var DLList; - - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } - - push(value) { - var node; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node = { - value, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } - - shift() { - var value; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value; - } - - first() { - if (this._first != null) { - return this._first.value; - } - } - - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } - - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } - - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } - - }; - - var DLList_1 = DLList; - - var Events; - - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } - - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } - - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } - - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } - - }; - - var Events_1 = Events; - - var DLList$1, Events$1, Queues; - - DLList$1 = DLList_1; - - Events$1 = Events_1; - - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(this); - } - - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } - - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } - - push(job) { - return this._lists[job.options.priority].push(job); - } - - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } - - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } - - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } - - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } - - }; - - var Queues_1 = Queues; - - var BottleneckError; - - BottleneckError = class BottleneckError extends Error {}; - - var BottleneckError_1 = BottleneckError; +/***/ 93708: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; +"use strict"; - NUM_PRIORITIES = 10; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__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: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - DEFAULT_PRIORITY = 5; +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + RequestError: () => RequestError +}); +module.exports = __toCommonJS(dist_src_exports); +var import_deprecation = __nccwpck_require__(14150); +var import_once = __toESM(__nccwpck_require__(55560)); +var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } +/***/ 66255: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } +"use strict"; - _randomIndex() { - return Math.random().toString(36).slice(2); - } +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); - return true; - } else { - return false; - } - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + request: () => request +}); +module.exports = __toCommonJS(dist_src_exports); +var import_endpoint = __nccwpck_require__(54471); +var import_universal_user_agent = __nccwpck_require__(33843); - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || (expected === "DONE" && status === null))) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } +// pkg/dist-src/version.js +var VERSION = "8.2.0"; - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", {args: this.args, options: this.options}); - } +// pkg/dist-src/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); - } +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(93708); - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", {args: this.args, options: this.options}); - } +// pkg/dist-src/get-buffer-response.js +function getBufferResponse(response) { + return response.arrayBuffer(); +} - async doExecute(chained, clearGlobalState, run, free) { - var error, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - this.Events.trigger("executing", eventInfo); - try { - passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error = error1; - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - } +// pkg/dist-src/fetch-wrapper.js +function fetchWrapper(requestOptions) { + var _a, _b, _c; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + headers: requestOptions.headers, + signal: (_c = requestOptions.request) == null ? void 0 : _c.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error) => { + if (error instanceof import_request_error.RequestError) + throw error; + else if (error.name === "AbortError") + throw error; + let message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (/application\/json/.test(contentType)) { + return response.json().catch(() => response.text()).catch(() => ""); + } + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + return getBufferResponse(response); +} +function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } +// pkg/dist-src/with-defaults.js +function withDefaults(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); +} - async _onFailure(error, eventInfo, clearGlobalState, run, free) { - var retry, retryAfter; - if (clearGlobalState()) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error); - } - } - } +// pkg/dist-src/index.js +var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } - }; +/***/ }), - var Job_1 = Job; +/***/ 18456: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var BottleneckError$2, LocalDatastore, parser$2; +"use strict"; - parser$2 = parser; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toMessageSignatureBundle = toMessageSignatureBundle; +exports.toDSSEBundle = toDSSEBundle; +/* +Copyright 2023 The Sigstore Authors. - BottleneckError$2 = BottleneckError_1; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } + http://www.apache.org/licenses/LICENSE-2.0 - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { - return typeof (base = (this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const protobuf_specs_1 = __nccwpck_require__(74799); +const bundle_1 = __nccwpck_require__(37742); +// Message signature bundle - $case: 'messageSignature' +function toMessageSignatureBundle(options) { + return { + mediaType: options.certificateChain + ? bundle_1.BUNDLE_V02_MEDIA_TYPE + : bundle_1.BUNDLE_V03_MEDIA_TYPE, + content: { + $case: 'messageSignature', + messageSignature: { + messageDigest: { + algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256, + digest: options.digest, + }, + signature: options.signature, + }, + }, + verificationMaterial: toVerificationMaterial(options), + }; +} +// DSSE envelope bundle - $case: 'dsseEnvelope' +function toDSSEBundle(options) { + return { + mediaType: options.certificateChain + ? bundle_1.BUNDLE_V02_MEDIA_TYPE + : bundle_1.BUNDLE_V03_MEDIA_TYPE, + content: { + $case: 'dsseEnvelope', + dsseEnvelope: toEnvelope(options), + }, + verificationMaterial: toVerificationMaterial(options), + }; +} +function toEnvelope(options) { + return { + payloadType: options.artifactType, + payload: options.artifact, + signatures: [toSignature(options)], + }; +} +function toSignature(options) { + return { + keyid: options.keyHint || '', + sig: options.signature, + }; +} +// Verification material +function toVerificationMaterial(options) { + return { + content: toKeyContent(options), + tlogEntries: [], + timestampVerificationData: { rfc3161Timestamps: [] }, + }; +} +function toKeyContent(options) { + if (options.certificate) { + if (options.certificateChain) { + return { + $case: 'x509CertificateChain', + x509CertificateChain: { + certificates: [{ rawBytes: options.certificate }], + }, + }; + } + else { + return { + $case: 'certificate', + certificate: { rawBytes: options.certificate }, + }; + } + } + else { + return { + $case: 'publicKey', + publicKey: { + hint: options.keyHint || '', + }, + }; + } +} - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } +/***/ }), - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } +/***/ 37742: +/***/ ((__unused_webpack_module, exports) => { - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } +"use strict"; - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0; +exports.isBundleWithCertificateChain = isBundleWithCertificateChain; +exports.isBundleWithPublicKey = isBundleWithPublicKey; +exports.isBundleWithMessageSignature = isBundleWithMessageSignature; +exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope; +exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1'; +exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2'; +exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3'; +exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json'; +// Type guards for bundle variants. +function isBundleWithCertificateChain(b) { + return b.verificationMaterial.content.$case === 'x509CertificateChain'; +} +function isBundleWithPublicKey(b) { + return b.verificationMaterial.content.$case === 'publicKey'; +} +function isBundleWithMessageSignature(b) { + return b.content.$case === 'messageSignature'; +} +function isBundleWithDsseEnvelope(b) { + return b.content.$case === 'dsseEnvelope'; +} - async __running__() { - await this.yieldLoop(); - return this._running; - } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } +/***/ }), - async __done__() { - await this.yieldLoop(); - return this._done; - } +/***/ 47714: +/***/ ((__unused_webpack_module, exports) => { - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } +"use strict"; - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ValidationError = void 0; +/* +Copyright 2023 The Sigstore Authors. - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } + http://www.apache.org/licenses/LICENSE-2.0 - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +class ValidationError extends Error { + constructor(message, fields) { + super(message); + this.fields = fields; + } +} +exports.ValidationError = ValidationError; - isBlocked(now) { - return this._unblockTime >= now; - } - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } +/***/ }), - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } +/***/ 61040: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } +"use strict"; - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0; +/* +Copyright 2023 The Sigstore Authors. - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } + http://www.apache.org/licenses/LICENSE-2.0 - }; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var build_1 = __nccwpck_require__(18456); +Object.defineProperty(exports, "toDSSEBundle", ({ enumerable: true, get: function () { return build_1.toDSSEBundle; } })); +Object.defineProperty(exports, "toMessageSignatureBundle", ({ enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } })); +var bundle_1 = __nccwpck_require__(37742); +Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } })); +Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } })); +Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } })); +Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } })); +Object.defineProperty(exports, "isBundleWithCertificateChain", ({ enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } })); +Object.defineProperty(exports, "isBundleWithDsseEnvelope", ({ enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } })); +Object.defineProperty(exports, "isBundleWithMessageSignature", ({ enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } })); +Object.defineProperty(exports, "isBundleWithPublicKey", ({ enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } })); +var error_1 = __nccwpck_require__(47714); +Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return error_1.ValidationError; } })); +var serialized_1 = __nccwpck_require__(23404); +Object.defineProperty(exports, "bundleFromJSON", ({ enumerable: true, get: function () { return serialized_1.bundleFromJSON; } })); +Object.defineProperty(exports, "bundleToJSON", ({ enumerable: true, get: function () { return serialized_1.bundleToJSON; } })); +Object.defineProperty(exports, "envelopeFromJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } })); +Object.defineProperty(exports, "envelopeToJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeToJSON; } })); +var validate_1 = __nccwpck_require__(9352); +Object.defineProperty(exports, "assertBundle", ({ enumerable: true, get: function () { return validate_1.assertBundle; } })); +Object.defineProperty(exports, "assertBundleLatest", ({ enumerable: true, get: function () { return validate_1.assertBundleLatest; } })); +Object.defineProperty(exports, "assertBundleV01", ({ enumerable: true, get: function () { return validate_1.assertBundleV01; } })); +Object.defineProperty(exports, "assertBundleV02", ({ enumerable: true, get: function () { return validate_1.assertBundleV02; } })); +Object.defineProperty(exports, "isBundleV01", ({ enumerable: true, get: function () { return validate_1.isBundleV01; } })); - var LocalDatastore_1 = LocalDatastore; - var BottleneckError$3, States; +/***/ }), - BottleneckError$3 = BottleneckError_1; +/***/ 23404: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } +"use strict"; - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0; +/* +Copyright 2023 The Sigstore Authors. - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } + http://www.apache.org/licenses/LICENSE-2.0 - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const protobuf_specs_1 = __nccwpck_require__(74799); +const bundle_1 = __nccwpck_require__(37742); +const validate_1 = __nccwpck_require__(9352); +const bundleFromJSON = (obj) => { + const bundle = protobuf_specs_1.Bundle.fromJSON(obj); + switch (bundle.mediaType) { + case bundle_1.BUNDLE_V01_MEDIA_TYPE: + (0, validate_1.assertBundleV01)(bundle); + break; + case bundle_1.BUNDLE_V02_MEDIA_TYPE: + (0, validate_1.assertBundleV02)(bundle); + break; + default: + (0, validate_1.assertBundleLatest)(bundle); + break; + } + return bundle; +}; +exports.bundleFromJSON = bundleFromJSON; +const bundleToJSON = (bundle) => { + return protobuf_specs_1.Bundle.toJSON(bundle); +}; +exports.bundleToJSON = bundleToJSON; +const envelopeFromJSON = (obj) => { + return protobuf_specs_1.Envelope.fromJSON(obj); +}; +exports.envelopeFromJSON = envelopeFromJSON; +const envelopeToJSON = (envelope) => { + return protobuf_specs_1.Envelope.toJSON(envelope); +}; +exports.envelopeToJSON = envelopeToJSON; - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); - } - ref = this._jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this._jobs); - } - } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } +/***/ }), - }; +/***/ 9352: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var States_1 = States; +"use strict"; - var DLList$2, Sync; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertBundle = assertBundle; +exports.assertBundleV01 = assertBundleV01; +exports.isBundleV01 = isBundleV01; +exports.assertBundleV02 = assertBundleV02; +exports.assertBundleLatest = assertBundleLatest; +/* +Copyright 2023 The Sigstore Authors. - DLList$2 = DLList_1; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } + http://www.apache.org/licenses/LICENSE-2.0 - isEmpty() { - return this._queue.length === 0; - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = __nccwpck_require__(47714); +// Performs basic validation of a Sigstore bundle to ensure that all required +// fields are populated. This is not a complete validation of the bundle, but +// rather a check that the bundle is in a valid state to be processed by the +// rest of the code. +function assertBundle(b) { + const invalidValues = validateBundleBase(b); + if (invalidValues.length > 0) { + throw new error_1.ValidationError('invalid bundle', invalidValues); + } +} +// Asserts that the given bundle conforms to the v0.1 bundle format. +function assertBundleV01(b) { + const invalidValues = []; + invalidValues.push(...validateBundleBase(b)); + invalidValues.push(...validateInclusionPromise(b)); + if (invalidValues.length > 0) { + throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues); + } +} +// Type guard to determine if Bundle is a v0.1 bundle. +function isBundleV01(b) { + try { + assertBundleV01(b); + return true; + } + catch (e) { + return false; + } +} +// Asserts that the given bundle conforms to the v0.2 bundle format. +function assertBundleV02(b) { + const invalidValues = []; + invalidValues.push(...validateBundleBase(b)); + invalidValues.push(...validateInclusionProof(b)); + if (invalidValues.length > 0) { + throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues); + } +} +// Asserts that the given bundle conforms to the newest (0.3) bundle format. +function assertBundleLatest(b) { + const invalidValues = []; + invalidValues.push(...validateBundleBase(b)); + invalidValues.push(...validateInclusionProof(b)); + invalidValues.push(...validateNoCertificateChain(b)); + if (invalidValues.length > 0) { + throw new error_1.ValidationError('invalid bundle', invalidValues); + } +} +function validateBundleBase(b) { + const invalidValues = []; + // Media type validation + if (b.mediaType === undefined || + (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) && + !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) { + invalidValues.push('mediaType'); + } + // Content-related validation + if (b.content === undefined) { + invalidValues.push('content'); + } + else { + switch (b.content.$case) { + case 'messageSignature': + if (b.content.messageSignature.messageDigest === undefined) { + invalidValues.push('content.messageSignature.messageDigest'); + } + else { + if (b.content.messageSignature.messageDigest.digest.length === 0) { + invalidValues.push('content.messageSignature.messageDigest.digest'); + } + } + if (b.content.messageSignature.signature.length === 0) { + invalidValues.push('content.messageSignature.signature'); + } + break; + case 'dsseEnvelope': + if (b.content.dsseEnvelope.payload.length === 0) { + invalidValues.push('content.dsseEnvelope.payload'); + } + if (b.content.dsseEnvelope.signatures.length !== 1) { + invalidValues.push('content.dsseEnvelope.signatures'); + } + else { + if (b.content.dsseEnvelope.signatures[0].sig.length === 0) { + invalidValues.push('content.dsseEnvelope.signatures[0].sig'); + } + } + break; + } + } + // Verification material-related validation + if (b.verificationMaterial === undefined) { + invalidValues.push('verificationMaterial'); + } + else { + if (b.verificationMaterial.content === undefined) { + invalidValues.push('verificationMaterial.content'); + } + else { + switch (b.verificationMaterial.content.$case) { + case 'x509CertificateChain': + if (b.verificationMaterial.content.x509CertificateChain.certificates + .length === 0) { + invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates'); + } + b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => { + if (cert.rawBytes.length === 0) { + invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`); + } + }); + break; + case 'certificate': + if (b.verificationMaterial.content.certificate.rawBytes.length === 0) { + invalidValues.push('verificationMaterial.content.certificate.rawBytes'); + } + break; + } + } + if (b.verificationMaterial.tlogEntries === undefined) { + invalidValues.push('verificationMaterial.tlogEntries'); + } + else { + if (b.verificationMaterial.tlogEntries.length > 0) { + b.verificationMaterial.tlogEntries.forEach((entry, i) => { + if (entry.logId === undefined) { + invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`); + } + if (entry.kindVersion === undefined) { + invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`); + } + }); + } + } + } + return invalidValues; +} +// Necessary for V01 bundles +function validateInclusionPromise(b) { + const invalidValues = []; + if (b.verificationMaterial && + b.verificationMaterial.tlogEntries?.length > 0) { + b.verificationMaterial.tlogEntries.forEach((entry, i) => { + if (entry.inclusionPromise === undefined) { + invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`); + } + }); + } + return invalidValues; +} +// Necessary for V02 and later bundles +function validateInclusionProof(b) { + const invalidValues = []; + if (b.verificationMaterial && + b.verificationMaterial.tlogEntries?.length > 0) { + b.verificationMaterial.tlogEntries.forEach((entry, i) => { + if (entry.inclusionProof === undefined) { + invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`); + } + else { + if (entry.inclusionProof.checkpoint === undefined) { + invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`); + } + } + }); + } + return invalidValues; +} +// Necessary for V03 and later bundles +function validateNoCertificateChain(b) { + const invalidValues = []; + /* istanbul ignore next */ + if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') { + invalidValues.push('verificationMaterial.content.$case'); + } + return invalidValues; +} - async _tryToRun() { - var args, cb, error, reject, resolve, returned, task; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - ({task, args, resolve, reject} = this._queue.shift()); - cb = (await (async function() { - try { - returned = (await task(...args)); - return function() { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function() { - return reject(error); - }; - } - })()); - this._running--; - this._tryToRun(); - return cb(); - } - } - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function(_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - this._queue.push({task, args, resolve, reject}); - this._tryToRun(); - return promise; - } +/***/ }), - }; +/***/ 99101: +/***/ ((__unused_webpack_module, exports) => { - var Sync_1 = Sync; +"use strict"; - var version = "2.19.5"; - var version$1 = { - version: version - }; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Signature = exports.Envelope = void 0; +function createBaseEnvelope() { + return { payload: Buffer.alloc(0), payloadType: "", signatures: [] }; +} +exports.Envelope = { + fromJSON(object) { + return { + payload: isSet(object.payload) ? Buffer.from(bytesFromBase64(object.payload)) : Buffer.alloc(0), + payloadType: isSet(object.payloadType) ? String(object.payloadType) : "", + signatures: Array.isArray(object?.signatures) ? object.signatures.map((e) => exports.Signature.fromJSON(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + message.payload !== undefined && + (obj.payload = base64FromBytes(message.payload !== undefined ? message.payload : Buffer.alloc(0))); + message.payloadType !== undefined && (obj.payloadType = message.payloadType); + if (message.signatures) { + obj.signatures = message.signatures.map((e) => e ? exports.Signature.toJSON(e) : undefined); + } + else { + obj.signatures = []; + } + return obj; + }, +}; +function createBaseSignature() { + return { sig: Buffer.alloc(0), keyid: "" }; +} +exports.Signature = { + fromJSON(object) { + return { + sig: isSet(object.sig) ? Buffer.from(bytesFromBase64(object.sig)) : Buffer.alloc(0), + keyid: isSet(object.keyid) ? String(object.keyid) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.sig !== undefined && (obj.sig = base64FromBytes(message.sig !== undefined ? message.sig : Buffer.alloc(0))); + message.keyid !== undefined && (obj.keyid = message.keyid); + return obj; + }, +}; +var tsProtoGlobalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (tsProtoGlobalThis.Buffer) { + return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); + } + else { + const bin = tsProtoGlobalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (tsProtoGlobalThis.Buffer) { + return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return tsProtoGlobalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +/***/ }), - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +/***/ 53433: +/***/ ((__unused_webpack_module, exports) => { - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +"use strict"; - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Timestamp = void 0; +function createBaseTimestamp() { + return { seconds: "0", nanos: 0 }; +} +exports.Timestamp = { + fromJSON(object) { + return { + seconds: isSet(object.seconds) ? String(object.seconds) : "0", + nanos: isSet(object.nanos) ? Number(object.nanos) : 0, + }; + }, + toJSON(message) { + const obj = {}; + message.seconds !== undefined && (obj.seconds = message.seconds); + message.nanos !== undefined && (obj.nanos = Math.round(message.nanos)); + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} - parser$3 = parser; - Events$2 = Events_1; +/***/ }), - RedisConnection$1 = require$$2; +/***/ 38970: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - IORedisConnection$1 = require$$3; +"use strict"; - Scripts$1 = require$$4; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0; +/* eslint-disable */ +const envelope_1 = __nccwpck_require__(99101); +const sigstore_common_1 = __nccwpck_require__(48575); +const sigstore_rekor_1 = __nccwpck_require__(13243); +function createBaseTimestampVerificationData() { + return { rfc3161Timestamps: [] }; +} +exports.TimestampVerificationData = { + fromJSON(object) { + return { + rfc3161Timestamps: Array.isArray(object?.rfc3161Timestamps) + ? object.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.rfc3161Timestamps) { + obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => e ? sigstore_common_1.RFC3161SignedTimestamp.toJSON(e) : undefined); + } + else { + obj.rfc3161Timestamps = []; + } + return obj; + }, +}; +function createBaseVerificationMaterial() { + return { content: undefined, tlogEntries: [], timestampVerificationData: undefined }; +} +exports.VerificationMaterial = { + fromJSON(object) { + return { + content: isSet(object.publicKey) + ? { $case: "publicKey", publicKey: sigstore_common_1.PublicKeyIdentifier.fromJSON(object.publicKey) } + : isSet(object.x509CertificateChain) + ? { + $case: "x509CertificateChain", + x509CertificateChain: sigstore_common_1.X509CertificateChain.fromJSON(object.x509CertificateChain), + } + : isSet(object.certificate) + ? { $case: "certificate", certificate: sigstore_common_1.X509Certificate.fromJSON(object.certificate) } + : undefined, + tlogEntries: Array.isArray(object?.tlogEntries) + ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e)) + : [], + timestampVerificationData: isSet(object.timestampVerificationData) + ? exports.TimestampVerificationData.fromJSON(object.timestampVerificationData) + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.content?.$case === "publicKey" && + (obj.publicKey = message.content?.publicKey ? sigstore_common_1.PublicKeyIdentifier.toJSON(message.content?.publicKey) : undefined); + message.content?.$case === "x509CertificateChain" && + (obj.x509CertificateChain = message.content?.x509CertificateChain + ? sigstore_common_1.X509CertificateChain.toJSON(message.content?.x509CertificateChain) + : undefined); + message.content?.$case === "certificate" && + (obj.certificate = message.content?.certificate + ? sigstore_common_1.X509Certificate.toJSON(message.content?.certificate) + : undefined); + if (message.tlogEntries) { + obj.tlogEntries = message.tlogEntries.map((e) => e ? sigstore_rekor_1.TransparencyLogEntry.toJSON(e) : undefined); + } + else { + obj.tlogEntries = []; + } + message.timestampVerificationData !== undefined && + (obj.timestampVerificationData = message.timestampVerificationData + ? exports.TimestampVerificationData.toJSON(message.timestampVerificationData) + : undefined); + return obj; + }, +}; +function createBaseBundle() { + return { mediaType: "", verificationMaterial: undefined, content: undefined }; +} +exports.Bundle = { + fromJSON(object) { + return { + mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", + verificationMaterial: isSet(object.verificationMaterial) + ? exports.VerificationMaterial.fromJSON(object.verificationMaterial) + : undefined, + content: isSet(object.messageSignature) + ? { $case: "messageSignature", messageSignature: sigstore_common_1.MessageSignature.fromJSON(object.messageSignature) } + : isSet(object.dsseEnvelope) + ? { $case: "dsseEnvelope", dsseEnvelope: envelope_1.Envelope.fromJSON(object.dsseEnvelope) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.mediaType !== undefined && (obj.mediaType = message.mediaType); + message.verificationMaterial !== undefined && (obj.verificationMaterial = message.verificationMaterial + ? exports.VerificationMaterial.toJSON(message.verificationMaterial) + : undefined); + message.content?.$case === "messageSignature" && (obj.messageSignature = message.content?.messageSignature + ? sigstore_common_1.MessageSignature.toJSON(message.content?.messageSignature) + : undefined); + message.content?.$case === "dsseEnvelope" && + (obj.dsseEnvelope = message.content?.dsseEnvelope ? envelope_1.Envelope.toJSON(message.content?.dsseEnvelope) : undefined); + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +/***/ }), - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } +/***/ 48575: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } +"use strict"; - keys() { - return Object.keys(this.instances); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0; +/* eslint-disable */ +const timestamp_1 = __nccwpck_require__(53433); +/** + * Only a subset of the secure hash standard algorithms are supported. + * See for more + * details. + * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force + * any proto JSON serialization to emit the used hash algorithm, as default + * option is to *omit* the default value of an enum (which is the first + * value, represented by '0'. + */ +var HashAlgorithm; +(function (HashAlgorithm) { + HashAlgorithm[HashAlgorithm["HASH_ALGORITHM_UNSPECIFIED"] = 0] = "HASH_ALGORITHM_UNSPECIFIED"; + HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256"; + HashAlgorithm[HashAlgorithm["SHA2_384"] = 2] = "SHA2_384"; + HashAlgorithm[HashAlgorithm["SHA2_512"] = 3] = "SHA2_512"; + HashAlgorithm[HashAlgorithm["SHA3_256"] = 4] = "SHA3_256"; + HashAlgorithm[HashAlgorithm["SHA3_384"] = 5] = "SHA3_384"; +})(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {})); +function hashAlgorithmFromJSON(object) { + switch (object) { + case 0: + case "HASH_ALGORITHM_UNSPECIFIED": + return HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED; + case 1: + case "SHA2_256": + return HashAlgorithm.SHA2_256; + case 2: + case "SHA2_384": + return HashAlgorithm.SHA2_384; + case 3: + case "SHA2_512": + return HashAlgorithm.SHA2_512; + case 4: + case "SHA3_256": + return HashAlgorithm.SHA3_256; + case 5: + case "SHA3_384": + return HashAlgorithm.SHA3_384; + default: + throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); + } +} +exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON; +function hashAlgorithmToJSON(object) { + switch (object) { + case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED: + return "HASH_ALGORITHM_UNSPECIFIED"; + case HashAlgorithm.SHA2_256: + return "SHA2_256"; + case HashAlgorithm.SHA2_384: + return "SHA2_384"; + case HashAlgorithm.SHA2_512: + return "SHA2_512"; + case HashAlgorithm.SHA3_256: + return "SHA3_256"; + case HashAlgorithm.SHA3_384: + return "SHA3_384"; + default: + throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); + } +} +exports.hashAlgorithmToJSON = hashAlgorithmToJSON; +/** + * Details of a specific public key, capturing the the key encoding method, + * and signature algorithm. + * + * PublicKeyDetails captures the public key/hash algorithm combinations + * recommended in the Sigstore ecosystem. + * + * This is modelled as a linear set as we want to provide a small number of + * opinionated options instead of allowing every possible permutation. + * + * Any changes to this enum MUST be reflected in the algorithm registry. + * See: docs/algorithm-registry.md + * + * To avoid the possibility of contradicting formats such as PKCS1 with + * ED25519 the valid permutations are listed as a linear set instead of a + * cartesian set (i.e one combined variable instead of two, one for encoding + * and one for the signature algorithm). + */ +var PublicKeyDetails; +(function (PublicKeyDetails) { + PublicKeyDetails[PublicKeyDetails["PUBLIC_KEY_DETAILS_UNSPECIFIED"] = 0] = "PUBLIC_KEY_DETAILS_UNSPECIFIED"; + /** + * PKCS1_RSA_PKCS1V5 - RSA + * + * @deprecated + */ + PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PKCS1V5"] = 1] = "PKCS1_RSA_PKCS1V5"; + /** + * PKCS1_RSA_PSS - See RFC8017 + * + * @deprecated + */ + PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PSS"] = 2] = "PKCS1_RSA_PSS"; + /** @deprecated */ + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V5"] = 3] = "PKIX_RSA_PKCS1V5"; + /** @deprecated */ + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS"] = 4] = "PKIX_RSA_PSS"; + /** PKIX_RSA_PKCS1V15_2048_SHA256 - RSA public key in PKIX format, PKCS#1v1.5 signature */ + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_2048_SHA256"] = 9] = "PKIX_RSA_PKCS1V15_2048_SHA256"; + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_3072_SHA256"] = 10] = "PKIX_RSA_PKCS1V15_3072_SHA256"; + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V15_4096_SHA256"] = 11] = "PKIX_RSA_PKCS1V15_4096_SHA256"; + /** PKIX_RSA_PSS_2048_SHA256 - RSA public key in PKIX format, RSASSA-PSS signature */ + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_2048_SHA256"] = 16] = "PKIX_RSA_PSS_2048_SHA256"; + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_3072_SHA256"] = 17] = "PKIX_RSA_PSS_3072_SHA256"; + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS_4096_SHA256"] = 18] = "PKIX_RSA_PSS_4096_SHA256"; + /** + * PKIX_ECDSA_P256_HMAC_SHA_256 - ECDSA + * + * @deprecated + */ + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_HMAC_SHA_256"] = 6] = "PKIX_ECDSA_P256_HMAC_SHA_256"; + /** PKIX_ECDSA_P256_SHA_256 - See NIST FIPS 186-4 */ + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_SHA_256"] = 5] = "PKIX_ECDSA_P256_SHA_256"; + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P384_SHA_384"] = 12] = "PKIX_ECDSA_P384_SHA_384"; + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P521_SHA_512"] = 13] = "PKIX_ECDSA_P521_SHA_512"; + /** PKIX_ED25519 - Ed 25519 */ + PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519"; + PublicKeyDetails[PublicKeyDetails["PKIX_ED25519_PH"] = 8] = "PKIX_ED25519_PH"; + /** + * LMS_SHA256 - LMS and LM-OTS + * + * These keys and signatures may be used by private Sigstore + * deployments, but are not currently supported by the public + * good instance. + * + * USER WARNING: LMS and LM-OTS are both stateful signature schemes. + * Using them correctly requires discretion and careful consideration + * to ensure that individual secret keys are not used more than once. + * In addition, LM-OTS is a single-use scheme, meaning that it + * MUST NOT be used for more than one signature per LM-OTS key. + * If you cannot maintain these invariants, you MUST NOT use these + * schemes. + */ + PublicKeyDetails[PublicKeyDetails["LMS_SHA256"] = 14] = "LMS_SHA256"; + PublicKeyDetails[PublicKeyDetails["LMOTS_SHA256"] = 15] = "LMOTS_SHA256"; +})(PublicKeyDetails = exports.PublicKeyDetails || (exports.PublicKeyDetails = {})); +function publicKeyDetailsFromJSON(object) { + switch (object) { + case 0: + case "PUBLIC_KEY_DETAILS_UNSPECIFIED": + return PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED; + case 1: + case "PKCS1_RSA_PKCS1V5": + return PublicKeyDetails.PKCS1_RSA_PKCS1V5; + case 2: + case "PKCS1_RSA_PSS": + return PublicKeyDetails.PKCS1_RSA_PSS; + case 3: + case "PKIX_RSA_PKCS1V5": + return PublicKeyDetails.PKIX_RSA_PKCS1V5; + case 4: + case "PKIX_RSA_PSS": + return PublicKeyDetails.PKIX_RSA_PSS; + case 9: + case "PKIX_RSA_PKCS1V15_2048_SHA256": + return PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256; + case 10: + case "PKIX_RSA_PKCS1V15_3072_SHA256": + return PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256; + case 11: + case "PKIX_RSA_PKCS1V15_4096_SHA256": + return PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256; + case 16: + case "PKIX_RSA_PSS_2048_SHA256": + return PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256; + case 17: + case "PKIX_RSA_PSS_3072_SHA256": + return PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256; + case 18: + case "PKIX_RSA_PSS_4096_SHA256": + return PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256; + case 6: + case "PKIX_ECDSA_P256_HMAC_SHA_256": + return PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256; + case 5: + case "PKIX_ECDSA_P256_SHA_256": + return PublicKeyDetails.PKIX_ECDSA_P256_SHA_256; + case 12: + case "PKIX_ECDSA_P384_SHA_384": + return PublicKeyDetails.PKIX_ECDSA_P384_SHA_384; + case 13: + case "PKIX_ECDSA_P521_SHA_512": + return PublicKeyDetails.PKIX_ECDSA_P521_SHA_512; + case 7: + case "PKIX_ED25519": + return PublicKeyDetails.PKIX_ED25519; + case 8: + case "PKIX_ED25519_PH": + return PublicKeyDetails.PKIX_ED25519_PH; + case 14: + case "LMS_SHA256": + return PublicKeyDetails.LMS_SHA256; + case 15: + case "LMOTS_SHA256": + return PublicKeyDetails.LMOTS_SHA256; + default: + throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); + } +} +exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON; +function publicKeyDetailsToJSON(object) { + switch (object) { + case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED: + return "PUBLIC_KEY_DETAILS_UNSPECIFIED"; + case PublicKeyDetails.PKCS1_RSA_PKCS1V5: + return "PKCS1_RSA_PKCS1V5"; + case PublicKeyDetails.PKCS1_RSA_PSS: + return "PKCS1_RSA_PSS"; + case PublicKeyDetails.PKIX_RSA_PKCS1V5: + return "PKIX_RSA_PKCS1V5"; + case PublicKeyDetails.PKIX_RSA_PSS: + return "PKIX_RSA_PSS"; + case PublicKeyDetails.PKIX_RSA_PKCS1V15_2048_SHA256: + return "PKIX_RSA_PKCS1V15_2048_SHA256"; + case PublicKeyDetails.PKIX_RSA_PKCS1V15_3072_SHA256: + return "PKIX_RSA_PKCS1V15_3072_SHA256"; + case PublicKeyDetails.PKIX_RSA_PKCS1V15_4096_SHA256: + return "PKIX_RSA_PKCS1V15_4096_SHA256"; + case PublicKeyDetails.PKIX_RSA_PSS_2048_SHA256: + return "PKIX_RSA_PSS_2048_SHA256"; + case PublicKeyDetails.PKIX_RSA_PSS_3072_SHA256: + return "PKIX_RSA_PSS_3072_SHA256"; + case PublicKeyDetails.PKIX_RSA_PSS_4096_SHA256: + return "PKIX_RSA_PSS_4096_SHA256"; + case PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256: + return "PKIX_ECDSA_P256_HMAC_SHA_256"; + case PublicKeyDetails.PKIX_ECDSA_P256_SHA_256: + return "PKIX_ECDSA_P256_SHA_256"; + case PublicKeyDetails.PKIX_ECDSA_P384_SHA_384: + return "PKIX_ECDSA_P384_SHA_384"; + case PublicKeyDetails.PKIX_ECDSA_P521_SHA_512: + return "PKIX_ECDSA_P521_SHA_512"; + case PublicKeyDetails.PKIX_ED25519: + return "PKIX_ED25519"; + case PublicKeyDetails.PKIX_ED25519_PH: + return "PKIX_ED25519_PH"; + case PublicKeyDetails.LMS_SHA256: + return "LMS_SHA256"; + case PublicKeyDetails.LMOTS_SHA256: + return "LMOTS_SHA256"; + default: + throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); + } +} +exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON; +var SubjectAlternativeNameType; +(function (SubjectAlternativeNameType) { + SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; + SubjectAlternativeNameType[SubjectAlternativeNameType["EMAIL"] = 1] = "EMAIL"; + SubjectAlternativeNameType[SubjectAlternativeNameType["URI"] = 2] = "URI"; + /** + * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7 + * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san + * for more details. + */ + SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME"; +})(SubjectAlternativeNameType = exports.SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = {})); +function subjectAlternativeNameTypeFromJSON(object) { + switch (object) { + case 0: + case "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED": + return SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED; + case 1: + case "EMAIL": + return SubjectAlternativeNameType.EMAIL; + case 2: + case "URI": + return SubjectAlternativeNameType.URI; + case 3: + case "OTHER_NAME": + return SubjectAlternativeNameType.OTHER_NAME; + default: + throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); + } +} +exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON; +function subjectAlternativeNameTypeToJSON(object) { + switch (object) { + case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED: + return "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; + case SubjectAlternativeNameType.EMAIL: + return "EMAIL"; + case SubjectAlternativeNameType.URI: + return "URI"; + case SubjectAlternativeNameType.OTHER_NAME: + return "OTHER_NAME"; + default: + throw new tsProtoGlobalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); + } +} +exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON; +function createBaseHashOutput() { + return { algorithm: 0, digest: Buffer.alloc(0) }; +} +exports.HashOutput = { + fromJSON(object) { + return { + algorithm: isSet(object.algorithm) ? hashAlgorithmFromJSON(object.algorithm) : 0, + digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.algorithm !== undefined && (obj.algorithm = hashAlgorithmToJSON(message.algorithm)); + message.digest !== undefined && + (obj.digest = base64FromBytes(message.digest !== undefined ? message.digest : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseMessageSignature() { + return { messageDigest: undefined, signature: Buffer.alloc(0) }; +} +exports.MessageSignature = { + fromJSON(object) { + return { + messageDigest: isSet(object.messageDigest) ? exports.HashOutput.fromJSON(object.messageDigest) : undefined, + signature: isSet(object.signature) ? Buffer.from(bytesFromBase64(object.signature)) : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.messageDigest !== undefined && + (obj.messageDigest = message.messageDigest ? exports.HashOutput.toJSON(message.messageDigest) : undefined); + message.signature !== undefined && + (obj.signature = base64FromBytes(message.signature !== undefined ? message.signature : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseLogId() { + return { keyId: Buffer.alloc(0) }; +} +exports.LogId = { + fromJSON(object) { + return { keyId: isSet(object.keyId) ? Buffer.from(bytesFromBase64(object.keyId)) : Buffer.alloc(0) }; + }, + toJSON(message) { + const obj = {}; + message.keyId !== undefined && + (obj.keyId = base64FromBytes(message.keyId !== undefined ? message.keyId : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseRFC3161SignedTimestamp() { + return { signedTimestamp: Buffer.alloc(0) }; +} +exports.RFC3161SignedTimestamp = { + fromJSON(object) { + return { + signedTimestamp: isSet(object.signedTimestamp) + ? Buffer.from(bytesFromBase64(object.signedTimestamp)) + : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.signedTimestamp !== undefined && + (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0))); + return obj; + }, +}; +function createBasePublicKey() { + return { rawBytes: undefined, keyDetails: 0, validFor: undefined }; +} +exports.PublicKey = { + fromJSON(object) { + return { + rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : undefined, + keyDetails: isSet(object.keyDetails) ? publicKeyDetailsFromJSON(object.keyDetails) : 0, + validFor: isSet(object.validFor) ? exports.TimeRange.fromJSON(object.validFor) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.rawBytes !== undefined && + (obj.rawBytes = message.rawBytes !== undefined ? base64FromBytes(message.rawBytes) : undefined); + message.keyDetails !== undefined && (obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails)); + message.validFor !== undefined && + (obj.validFor = message.validFor ? exports.TimeRange.toJSON(message.validFor) : undefined); + return obj; + }, +}; +function createBasePublicKeyIdentifier() { + return { hint: "" }; +} +exports.PublicKeyIdentifier = { + fromJSON(object) { + return { hint: isSet(object.hint) ? String(object.hint) : "" }; + }, + toJSON(message) { + const obj = {}; + message.hint !== undefined && (obj.hint = message.hint); + return obj; + }, +}; +function createBaseObjectIdentifier() { + return { id: [] }; +} +exports.ObjectIdentifier = { + fromJSON(object) { + return { id: Array.isArray(object?.id) ? object.id.map((e) => Number(e)) : [] }; + }, + toJSON(message) { + const obj = {}; + if (message.id) { + obj.id = message.id.map((e) => Math.round(e)); + } + else { + obj.id = []; + } + return obj; + }, +}; +function createBaseObjectIdentifierValuePair() { + return { oid: undefined, value: Buffer.alloc(0) }; +} +exports.ObjectIdentifierValuePair = { + fromJSON(object) { + return { + oid: isSet(object.oid) ? exports.ObjectIdentifier.fromJSON(object.oid) : undefined, + value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.oid !== undefined && (obj.oid = message.oid ? exports.ObjectIdentifier.toJSON(message.oid) : undefined); + message.value !== undefined && + (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseDistinguishedName() { + return { organization: "", commonName: "" }; +} +exports.DistinguishedName = { + fromJSON(object) { + return { + organization: isSet(object.organization) ? String(object.organization) : "", + commonName: isSet(object.commonName) ? String(object.commonName) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.organization !== undefined && (obj.organization = message.organization); + message.commonName !== undefined && (obj.commonName = message.commonName); + return obj; + }, +}; +function createBaseX509Certificate() { + return { rawBytes: Buffer.alloc(0) }; +} +exports.X509Certificate = { + fromJSON(object) { + return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) }; + }, + toJSON(message) { + const obj = {}; + message.rawBytes !== undefined && + (obj.rawBytes = base64FromBytes(message.rawBytes !== undefined ? message.rawBytes : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseSubjectAlternativeName() { + return { type: 0, identity: undefined }; +} +exports.SubjectAlternativeName = { + fromJSON(object) { + return { + type: isSet(object.type) ? subjectAlternativeNameTypeFromJSON(object.type) : 0, + identity: isSet(object.regexp) + ? { $case: "regexp", regexp: String(object.regexp) } + : isSet(object.value) + ? { $case: "value", value: String(object.value) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.type !== undefined && (obj.type = subjectAlternativeNameTypeToJSON(message.type)); + message.identity?.$case === "regexp" && (obj.regexp = message.identity?.regexp); + message.identity?.$case === "value" && (obj.value = message.identity?.value); + return obj; + }, +}; +function createBaseX509CertificateChain() { + return { certificates: [] }; +} +exports.X509CertificateChain = { + fromJSON(object) { + return { + certificates: Array.isArray(object?.certificates) + ? object.certificates.map((e) => exports.X509Certificate.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.certificates) { + obj.certificates = message.certificates.map((e) => e ? exports.X509Certificate.toJSON(e) : undefined); + } + else { + obj.certificates = []; + } + return obj; + }, +}; +function createBaseTimeRange() { + return { start: undefined, end: undefined }; +} +exports.TimeRange = { + fromJSON(object) { + return { + start: isSet(object.start) ? fromJsonTimestamp(object.start) : undefined, + end: isSet(object.end) ? fromJsonTimestamp(object.end) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.start !== undefined && (obj.start = message.start.toISOString()); + message.end !== undefined && (obj.end = message.end.toISOString()); + return obj; + }, +}; +var tsProtoGlobalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (tsProtoGlobalThis.Buffer) { + return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); + } + else { + const bin = tsProtoGlobalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (tsProtoGlobalThis.Buffer) { + return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return tsProtoGlobalThis.btoa(bin.join("")); + } +} +function fromTimestamp(t) { + let millis = Number(t.seconds) * 1000; + millis += t.nanos / 1000000; + return new Date(millis); +} +function fromJsonTimestamp(o) { + if (o instanceof Date) { + return o; + } + else if (typeof o === "string") { + return new Date(o); + } + else { + return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } +/***/ }), - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } +/***/ 13243: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } +"use strict"; - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0; +/* eslint-disable */ +const sigstore_common_1 = __nccwpck_require__(48575); +function createBaseKindVersion() { + return { kind: "", version: "" }; +} +exports.KindVersion = { + fromJSON(object) { + return { + kind: isSet(object.kind) ? String(object.kind) : "", + version: isSet(object.version) ? String(object.version) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.kind !== undefined && (obj.kind = message.kind); + message.version !== undefined && (obj.version = message.version); + return obj; + }, +}; +function createBaseCheckpoint() { + return { envelope: "" }; +} +exports.Checkpoint = { + fromJSON(object) { + return { envelope: isSet(object.envelope) ? String(object.envelope) : "" }; + }, + toJSON(message) { + const obj = {}; + message.envelope !== undefined && (obj.envelope = message.envelope); + return obj; + }, +}; +function createBaseInclusionProof() { + return { logIndex: "0", rootHash: Buffer.alloc(0), treeSize: "0", hashes: [], checkpoint: undefined }; +} +exports.InclusionProof = { + fromJSON(object) { + return { + logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", + rootHash: isSet(object.rootHash) ? Buffer.from(bytesFromBase64(object.rootHash)) : Buffer.alloc(0), + treeSize: isSet(object.treeSize) ? String(object.treeSize) : "0", + hashes: Array.isArray(object?.hashes) ? object.hashes.map((e) => Buffer.from(bytesFromBase64(e))) : [], + checkpoint: isSet(object.checkpoint) ? exports.Checkpoint.fromJSON(object.checkpoint) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.logIndex !== undefined && (obj.logIndex = message.logIndex); + message.rootHash !== undefined && + (obj.rootHash = base64FromBytes(message.rootHash !== undefined ? message.rootHash : Buffer.alloc(0))); + message.treeSize !== undefined && (obj.treeSize = message.treeSize); + if (message.hashes) { + obj.hashes = message.hashes.map((e) => base64FromBytes(e !== undefined ? e : Buffer.alloc(0))); + } + else { + obj.hashes = []; + } + message.checkpoint !== undefined && + (obj.checkpoint = message.checkpoint ? exports.Checkpoint.toJSON(message.checkpoint) : undefined); + return obj; + }, +}; +function createBaseInclusionPromise() { + return { signedEntryTimestamp: Buffer.alloc(0) }; +} +exports.InclusionPromise = { + fromJSON(object) { + return { + signedEntryTimestamp: isSet(object.signedEntryTimestamp) + ? Buffer.from(bytesFromBase64(object.signedEntryTimestamp)) + : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.signedEntryTimestamp !== undefined && + (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseTransparencyLogEntry() { + return { + logIndex: "0", + logId: undefined, + kindVersion: undefined, + integratedTime: "0", + inclusionPromise: undefined, + inclusionProof: undefined, + canonicalizedBody: Buffer.alloc(0), + }; +} +exports.TransparencyLogEntry = { + fromJSON(object) { + return { + logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", + logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, + kindVersion: isSet(object.kindVersion) ? exports.KindVersion.fromJSON(object.kindVersion) : undefined, + integratedTime: isSet(object.integratedTime) ? String(object.integratedTime) : "0", + inclusionPromise: isSet(object.inclusionPromise) ? exports.InclusionPromise.fromJSON(object.inclusionPromise) : undefined, + inclusionProof: isSet(object.inclusionProof) ? exports.InclusionProof.fromJSON(object.inclusionProof) : undefined, + canonicalizedBody: isSet(object.canonicalizedBody) + ? Buffer.from(bytesFromBase64(object.canonicalizedBody)) + : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.logIndex !== undefined && (obj.logIndex = message.logIndex); + message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); + message.kindVersion !== undefined && + (obj.kindVersion = message.kindVersion ? exports.KindVersion.toJSON(message.kindVersion) : undefined); + message.integratedTime !== undefined && (obj.integratedTime = message.integratedTime); + message.inclusionPromise !== undefined && + (obj.inclusionPromise = message.inclusionPromise ? exports.InclusionPromise.toJSON(message.inclusionPromise) : undefined); + message.inclusionProof !== undefined && + (obj.inclusionProof = message.inclusionProof ? exports.InclusionProof.toJSON(message.inclusionProof) : undefined); + message.canonicalizedBody !== undefined && + (obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody !== undefined ? message.canonicalizedBody : Buffer.alloc(0))); + return obj; + }, +}; +var tsProtoGlobalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (tsProtoGlobalThis.Buffer) { + return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); + } + else { + const bin = tsProtoGlobalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (tsProtoGlobalThis.Buffer) { + return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return tsProtoGlobalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} - return Group; - }).call(commonjsGlobal); +/***/ }), - var Group_1 = Group; +/***/ 94810: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var Batcher, Events$3, parser$4; +"use strict"; - parser$4 = parser; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0; +/* eslint-disable */ +const sigstore_common_1 = __nccwpck_require__(48575); +function createBaseTransparencyLogInstance() { + return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined }; +} +exports.TransparencyLogInstance = { + fromJSON(object) { + return { + baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "", + hashAlgorithm: isSet(object.hashAlgorithm) ? (0, sigstore_common_1.hashAlgorithmFromJSON)(object.hashAlgorithm) : 0, + publicKey: isSet(object.publicKey) ? sigstore_common_1.PublicKey.fromJSON(object.publicKey) : undefined, + logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, + checkpointKeyId: isSet(object.checkpointKeyId) ? sigstore_common_1.LogId.fromJSON(object.checkpointKeyId) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.baseUrl !== undefined && (obj.baseUrl = message.baseUrl); + message.hashAlgorithm !== undefined && (obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm)); + message.publicKey !== undefined && + (obj.publicKey = message.publicKey ? sigstore_common_1.PublicKey.toJSON(message.publicKey) : undefined); + message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); + message.checkpointKeyId !== undefined && + (obj.checkpointKeyId = message.checkpointKeyId ? sigstore_common_1.LogId.toJSON(message.checkpointKeyId) : undefined); + return obj; + }, +}; +function createBaseCertificateAuthority() { + return { subject: undefined, uri: "", certChain: undefined, validFor: undefined }; +} +exports.CertificateAuthority = { + fromJSON(object) { + return { + subject: isSet(object.subject) ? sigstore_common_1.DistinguishedName.fromJSON(object.subject) : undefined, + uri: isSet(object.uri) ? String(object.uri) : "", + certChain: isSet(object.certChain) ? sigstore_common_1.X509CertificateChain.fromJSON(object.certChain) : undefined, + validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.subject !== undefined && + (obj.subject = message.subject ? sigstore_common_1.DistinguishedName.toJSON(message.subject) : undefined); + message.uri !== undefined && (obj.uri = message.uri); + message.certChain !== undefined && + (obj.certChain = message.certChain ? sigstore_common_1.X509CertificateChain.toJSON(message.certChain) : undefined); + message.validFor !== undefined && + (obj.validFor = message.validFor ? sigstore_common_1.TimeRange.toJSON(message.validFor) : undefined); + return obj; + }, +}; +function createBaseTrustedRoot() { + return { mediaType: "", tlogs: [], certificateAuthorities: [], ctlogs: [], timestampAuthorities: [] }; +} +exports.TrustedRoot = { + fromJSON(object) { + return { + mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", + tlogs: Array.isArray(object?.tlogs) ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], + certificateAuthorities: Array.isArray(object?.certificateAuthorities) + ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) + : [], + ctlogs: Array.isArray(object?.ctlogs) + ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) + : [], + timestampAuthorities: Array.isArray(object?.timestampAuthorities) + ? object.timestampAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.mediaType !== undefined && (obj.mediaType = message.mediaType); + if (message.tlogs) { + obj.tlogs = message.tlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); + } + else { + obj.tlogs = []; + } + if (message.certificateAuthorities) { + obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); + } + else { + obj.certificateAuthorities = []; + } + if (message.ctlogs) { + obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); + } + else { + obj.ctlogs = []; + } + if (message.timestampAuthorities) { + obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); + } + else { + obj.timestampAuthorities = []; + } + return obj; + }, +}; +function createBaseSigningConfig() { + return { caUrl: "", oidcUrl: "", tlogUrls: [], tsaUrls: [] }; +} +exports.SigningConfig = { + fromJSON(object) { + return { + caUrl: isSet(object.caUrl) ? String(object.caUrl) : "", + oidcUrl: isSet(object.oidcUrl) ? String(object.oidcUrl) : "", + tlogUrls: Array.isArray(object?.tlogUrls) ? object.tlogUrls.map((e) => String(e)) : [], + tsaUrls: Array.isArray(object?.tsaUrls) ? object.tsaUrls.map((e) => String(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + message.caUrl !== undefined && (obj.caUrl = message.caUrl); + message.oidcUrl !== undefined && (obj.oidcUrl = message.oidcUrl); + if (message.tlogUrls) { + obj.tlogUrls = message.tlogUrls.map((e) => e); + } + else { + obj.tlogUrls = []; + } + if (message.tsaUrls) { + obj.tsaUrls = message.tsaUrls.map((e) => e); + } + else { + obj.tsaUrls = []; + } + return obj; + }, +}; +function createBaseClientTrustConfig() { + return { mediaType: "", trustedRoot: undefined, signingConfig: undefined }; +} +exports.ClientTrustConfig = { + fromJSON(object) { + return { + mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", + trustedRoot: isSet(object.trustedRoot) ? exports.TrustedRoot.fromJSON(object.trustedRoot) : undefined, + signingConfig: isSet(object.signingConfig) ? exports.SigningConfig.fromJSON(object.signingConfig) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.mediaType !== undefined && (obj.mediaType = message.mediaType); + message.trustedRoot !== undefined && + (obj.trustedRoot = message.trustedRoot ? exports.TrustedRoot.toJSON(message.trustedRoot) : undefined); + message.signingConfig !== undefined && + (obj.signingConfig = message.signingConfig ? exports.SigningConfig.toJSON(message.signingConfig) : undefined); + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} - Events$3 = Events_1; - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } +/***/ }), - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } +/***/ 30445: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } +"use strict"; - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_ObserverTimestampOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0; +/* eslint-disable */ +const sigstore_bundle_1 = __nccwpck_require__(38970); +const sigstore_common_1 = __nccwpck_require__(48575); +const sigstore_trustroot_1 = __nccwpck_require__(94810); +function createBaseCertificateIdentity() { + return { issuer: "", san: undefined, oids: [] }; +} +exports.CertificateIdentity = { + fromJSON(object) { + return { + issuer: isSet(object.issuer) ? String(object.issuer) : "", + san: isSet(object.san) ? sigstore_common_1.SubjectAlternativeName.fromJSON(object.san) : undefined, + oids: Array.isArray(object?.oids) ? object.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.fromJSON(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + message.issuer !== undefined && (obj.issuer = message.issuer); + message.san !== undefined && (obj.san = message.san ? sigstore_common_1.SubjectAlternativeName.toJSON(message.san) : undefined); + if (message.oids) { + obj.oids = message.oids.map((e) => e ? sigstore_common_1.ObjectIdentifierValuePair.toJSON(e) : undefined); + } + else { + obj.oids = []; + } + return obj; + }, +}; +function createBaseCertificateIdentities() { + return { identities: [] }; +} +exports.CertificateIdentities = { + fromJSON(object) { + return { + identities: Array.isArray(object?.identities) + ? object.identities.map((e) => exports.CertificateIdentity.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.identities) { + obj.identities = message.identities.map((e) => e ? exports.CertificateIdentity.toJSON(e) : undefined); + } + else { + obj.identities = []; + } + return obj; + }, +}; +function createBasePublicKeyIdentities() { + return { publicKeys: [] }; +} +exports.PublicKeyIdentities = { + fromJSON(object) { + return { + publicKeys: Array.isArray(object?.publicKeys) ? object.publicKeys.map((e) => sigstore_common_1.PublicKey.fromJSON(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.publicKeys) { + obj.publicKeys = message.publicKeys.map((e) => e ? sigstore_common_1.PublicKey.toJSON(e) : undefined); + } + else { + obj.publicKeys = []; + } + return obj; + }, +}; +function createBaseArtifactVerificationOptions() { + return { + signers: undefined, + tlogOptions: undefined, + ctlogOptions: undefined, + tsaOptions: undefined, + integratedTsOptions: undefined, + observerOptions: undefined, + }; +} +exports.ArtifactVerificationOptions = { + fromJSON(object) { + return { + signers: isSet(object.certificateIdentities) + ? { + $case: "certificateIdentities", + certificateIdentities: exports.CertificateIdentities.fromJSON(object.certificateIdentities), + } + : isSet(object.publicKeys) + ? { $case: "publicKeys", publicKeys: exports.PublicKeyIdentities.fromJSON(object.publicKeys) } + : undefined, + tlogOptions: isSet(object.tlogOptions) + ? exports.ArtifactVerificationOptions_TlogOptions.fromJSON(object.tlogOptions) + : undefined, + ctlogOptions: isSet(object.ctlogOptions) + ? exports.ArtifactVerificationOptions_CtlogOptions.fromJSON(object.ctlogOptions) + : undefined, + tsaOptions: isSet(object.tsaOptions) + ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.fromJSON(object.tsaOptions) + : undefined, + integratedTsOptions: isSet(object.integratedTsOptions) + ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.fromJSON(object.integratedTsOptions) + : undefined, + observerOptions: isSet(object.observerOptions) + ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.fromJSON(object.observerOptions) + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.signers?.$case === "certificateIdentities" && + (obj.certificateIdentities = message.signers?.certificateIdentities + ? exports.CertificateIdentities.toJSON(message.signers?.certificateIdentities) + : undefined); + message.signers?.$case === "publicKeys" && (obj.publicKeys = message.signers?.publicKeys + ? exports.PublicKeyIdentities.toJSON(message.signers?.publicKeys) + : undefined); + message.tlogOptions !== undefined && (obj.tlogOptions = message.tlogOptions + ? exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions) + : undefined); + message.ctlogOptions !== undefined && (obj.ctlogOptions = message.ctlogOptions + ? exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions) + : undefined); + message.tsaOptions !== undefined && (obj.tsaOptions = message.tsaOptions + ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions) + : undefined); + message.integratedTsOptions !== undefined && (obj.integratedTsOptions = message.integratedTsOptions + ? exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions.toJSON(message.integratedTsOptions) + : undefined); + message.observerOptions !== undefined && (obj.observerOptions = message.observerOptions + ? exports.ArtifactVerificationOptions_ObserverTimestampOptions.toJSON(message.observerOptions) + : undefined); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_TlogOptions() { + return { threshold: 0, performOnlineVerification: false, disable: false }; +} +exports.ArtifactVerificationOptions_TlogOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + performOnlineVerification: isSet(object.performOnlineVerification) + ? Boolean(object.performOnlineVerification) + : false, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.performOnlineVerification !== undefined && + (obj.performOnlineVerification = message.performOnlineVerification); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_CtlogOptions() { + return { threshold: 0, disable: false }; +} +exports.ArtifactVerificationOptions_CtlogOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_TimestampAuthorityOptions() { + return { threshold: 0, disable: false }; +} +exports.ArtifactVerificationOptions_TimestampAuthorityOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_TlogIntegratedTimestampOptions() { + return { threshold: 0, disable: false }; +} +exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_ObserverTimestampOptions() { + return { threshold: 0, disable: false }; +} +exports.ArtifactVerificationOptions_ObserverTimestampOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifact() { + return { data: undefined }; +} +exports.Artifact = { + fromJSON(object) { + return { + data: isSet(object.artifactUri) + ? { $case: "artifactUri", artifactUri: String(object.artifactUri) } + : isSet(object.artifact) + ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.data?.$case === "artifactUri" && (obj.artifactUri = message.data?.artifactUri); + message.data?.$case === "artifact" && + (obj.artifact = message.data?.artifact !== undefined ? base64FromBytes(message.data?.artifact) : undefined); + return obj; + }, +}; +function createBaseInput() { + return { + artifactTrustRoot: undefined, + artifactVerificationOptions: undefined, + bundle: undefined, + artifact: undefined, + }; +} +exports.Input = { + fromJSON(object) { + return { + artifactTrustRoot: isSet(object.artifactTrustRoot) ? sigstore_trustroot_1.TrustedRoot.fromJSON(object.artifactTrustRoot) : undefined, + artifactVerificationOptions: isSet(object.artifactVerificationOptions) + ? exports.ArtifactVerificationOptions.fromJSON(object.artifactVerificationOptions) + : undefined, + bundle: isSet(object.bundle) ? sigstore_bundle_1.Bundle.fromJSON(object.bundle) : undefined, + artifact: isSet(object.artifact) ? exports.Artifact.fromJSON(object.artifact) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.artifactTrustRoot !== undefined && + (obj.artifactTrustRoot = message.artifactTrustRoot ? sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot) : undefined); + message.artifactVerificationOptions !== undefined && + (obj.artifactVerificationOptions = message.artifactVerificationOptions + ? exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions) + : undefined); + message.bundle !== undefined && (obj.bundle = message.bundle ? sigstore_bundle_1.Bundle.toJSON(message.bundle) : undefined); + message.artifact !== undefined && (obj.artifact = message.artifact ? exports.Artifact.toJSON(message.artifact) : undefined); + return obj; + }, +}; +var tsProtoGlobalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (tsProtoGlobalThis.Buffer) { + return Uint8Array.from(tsProtoGlobalThis.Buffer.from(b64, "base64")); + } + else { + const bin = tsProtoGlobalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (tsProtoGlobalThis.Buffer) { + return tsProtoGlobalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return tsProtoGlobalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - return Batcher; +/***/ }), - }).call(commonjsGlobal); +/***/ 74799: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - var Batcher_1 = Batcher; +"use strict"; - var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* +Copyright 2023 The Sigstore Authors. - var require$$8 = getCjsExportFromNamespace(version$2); +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, - splice = [].splice; + http://www.apache.org/licenses/LICENSE-2.0 - NUM_PRIORITIES$1 = 10; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +__exportStar(__nccwpck_require__(99101), exports); +__exportStar(__nccwpck_require__(38970), exports); +__exportStar(__nccwpck_require__(48575), exports); +__exportStar(__nccwpck_require__(13243), exports); +__exportStar(__nccwpck_require__(94810), exports); +__exportStar(__nccwpck_require__(30445), exports); - DEFAULT_PRIORITY$1 = 5; - parser$5 = parser; +/***/ }), - Queues$1 = Queues_1; +/***/ 11121: +/***/ ((__unused_webpack_module, exports) => { - Job$1 = Job_1; +"use strict"; - LocalDatastore$1 = LocalDatastore_1; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ASN1TypeError = exports.ASN1ParseError = void 0; +/* +Copyright 2023 The Sigstore Authors. - RedisDatastore$1 = require$$4$1; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - Events$4 = Events_1; + http://www.apache.org/licenses/LICENSE-2.0 - States$1 = States_1; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +class ASN1ParseError extends Error { +} +exports.ASN1ParseError = ASN1ParseError; +class ASN1TypeError extends Error { +} +exports.ASN1TypeError = ASN1TypeError; - Sync$1 = Sync_1; - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } +/***/ }), - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } +/***/ 86027: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ready() { - return this._store.ready; - } +"use strict"; - clients() { - return this._store.clients; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ASN1Obj = void 0; +/* +Copyright 2023 The Sigstore Authors. - channel() { - return `b_${this.id}`; - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + http://www.apache.org/licenses/LICENSE-2.0 - publish(message) { - return this._store.__publish__(message); - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var obj_1 = __nccwpck_require__(50990); +Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return obj_1.ASN1Obj; } })); - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } - chain(_limiter) { - this._limiter = _limiter; - return this; - } +/***/ }), - queued(priority) { - return this._queues.queued(priority); - } +/***/ 84243: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - clusterQueued() { - return this._store.__queued__(); - } +"use strict"; - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } +/* +Copyright 2023 The Sigstore Authors. - running() { - return this._store.__running__(); - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - done() { - return this._store.__done__(); - } + http://www.apache.org/licenses/LICENSE-2.0 - jobStatus(id) { - return this._states.jobStatus(id); - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decodeLength = decodeLength; +exports.encodeLength = encodeLength; +const error_1 = __nccwpck_require__(11121); +// Decodes the length of a DER-encoded ANS.1 element from the supplied stream. +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes +function decodeLength(stream) { + const buf = stream.getUint8(); + // If the most significant bit is UNSET the length is just the value of the + // byte. + if ((buf & 0x80) === 0x00) { + return buf; + } + // Otherwise, the lower 7 bits of the first byte indicate the number of bytes + // that follow to encode the length. + const byteCount = buf & 0x7f; + // Ensure the encoded length can safely fit in a JS number. + if (byteCount > 6) { + throw new error_1.ASN1ParseError('length exceeds 6 byte limit'); + } + // Iterate over the bytes that encode the length. + let len = 0; + for (let i = 0; i < byteCount; i++) { + len = len * 256 + stream.getUint8(); + } + // This is a valid ASN.1 length encoding, but we don't support it. + if (len === 0) { + throw new error_1.ASN1ParseError('indefinite length encoding not supported'); + } + return len; +} +// Translates the supplied value to a DER-encoded length. +function encodeLength(len) { + if (len < 128) { + return Buffer.from([len]); + } + // Bitwise operations on large numbers are not supported in JS, so we need to + // use BigInts. + let val = BigInt(len); + const bytes = []; + while (val > 0n) { + bytes.unshift(Number(val & 255n)); + val = val >> 8n; + } + return Buffer.from([0x80 | bytes.length, ...bytes]); +} - jobs(status) { - return this._states.statusJobs(status); - } - counts() { - return this._states.statusCounts(); - } +/***/ }), - _randomIndex() { - return Math.random().toString(36).slice(2); - } +/***/ 50990: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - check(weight = 1) { - return this._store.__check__(weight); - } +"use strict"; - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ASN1Obj = void 0; +/* +Copyright 2023 The Sigstore Authors. - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({running} = (await this._store.__free__(index, options.weight))); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } + http://www.apache.org/licenses/LICENSE-2.0 - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(index, next, wait); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const stream_1 = __nccwpck_require__(1673); +const error_1 = __nccwpck_require__(11121); +const length_1 = __nccwpck_require__(84243); +const parse_1 = __nccwpck_require__(81044); +const tag_1 = __nccwpck_require__(59343); +class ASN1Obj { + constructor(tag, value, subs) { + this.tag = tag; + this.value = value; + this.subs = subs; + } + // Constructs an ASN.1 object from a Buffer of DER-encoded bytes. + static parseBuffer(buf) { + return parseStream(new stream_1.ByteStream(buf)); + } + toDER() { + const valueStream = new stream_1.ByteStream(); + if (this.subs.length > 0) { + for (const sub of this.subs) { + valueStream.appendView(sub.toDER()); + } + } + else { + valueStream.appendView(this.value); + } + const value = valueStream.buffer; + // Concat tag/length/value + const obj = new stream_1.ByteStream(); + obj.appendChar(this.tag.toDER()); + obj.appendView((0, length_1.encodeLength)(value.length)); + obj.appendView(value); + return obj.buffer; + } + ///////////////////////////////////////////////////////////////////////////// + // Convenience methods for parsing ASN.1 primitives into JS types + // Returns the ASN.1 object's value as a boolean. Throws an error if the + // object is not a boolean. + toBoolean() { + if (!this.tag.isBoolean()) { + throw new error_1.ASN1TypeError('not a boolean'); + } + return (0, parse_1.parseBoolean)(this.value); + } + // Returns the ASN.1 object's value as a BigInt. Throws an error if the + // object is not an integer. + toInteger() { + if (!this.tag.isInteger()) { + throw new error_1.ASN1TypeError('not an integer'); + } + return (0, parse_1.parseInteger)(this.value); + } + // Returns the ASN.1 object's value as an OID string. Throws an error if the + // object is not an OID. + toOID() { + if (!this.tag.isOID()) { + throw new error_1.ASN1TypeError('not an OID'); + } + return (0, parse_1.parseOID)(this.value); + } + // Returns the ASN.1 object's value as a Date. Throws an error if the object + // is not either a UTCTime or a GeneralizedTime. + toDate() { + switch (true) { + case this.tag.isUTCTime(): + return (0, parse_1.parseTime)(this.value, true); + case this.tag.isGeneralizedTime(): + return (0, parse_1.parseTime)(this.value, false); + default: + throw new error_1.ASN1TypeError('not a date'); + } + } + // Returns the ASN.1 object's value as a number[] where each number is the + // value of a bit in the bit string. Throws an error if the object is not a + // bit string. + toBitString() { + if (!this.tag.isBitString()) { + throw new error_1.ASN1TypeError('not a bit string'); + } + return (0, parse_1.parseBitString)(this.value); + } +} +exports.ASN1Obj = ASN1Obj; +///////////////////////////////////////////////////////////////////////////// +// Internal stream parsing functions +function parseStream(stream) { + // Parse tag, length, and value from stream + const tag = new tag_1.ASN1Tag(stream.getUint8()); + const len = (0, length_1.decodeLength)(stream); + const value = stream.slice(stream.position, len); + const start = stream.position; + let subs = []; + // If the object is constructed, parse its children. Sometimes, children + // are embedded in OCTESTRING objects, so we need to check those + // for children as well. + if (tag.constructed) { + subs = collectSubs(stream, len); + } + else if (tag.isOctetString()) { + // Attempt to parse children of OCTETSTRING objects. If anything fails, + // assume the object is not constructed and treat as primitive. + try { + subs = collectSubs(stream, len); + } + catch (e) { + // Fail silently and treat as primitive + } + } + // If there are no children, move stream cursor to the end of the object + if (subs.length === 0) { + stream.seek(start + len); + } + return new ASN1Obj(tag, value, subs); +} +function collectSubs(stream, len) { + // Calculate end of object content + const end = stream.position + len; + // Make sure there are enough bytes left in the stream. This should never + // happen, cause it'll get caught when the stream is sliced in parseStream. + // Leaving as an extra check just in case. + /* istanbul ignore if */ + if (end > stream.length) { + throw new error_1.ASN1ParseError('invalid length'); + } + // Parse all children + const subs = []; + while (stream.position < end) { + subs.push(parseStream(stream)); + } + // When we're done parsing children, we should be at the end of the object + if (stream.position !== end) { + throw new error_1.ASN1ParseError('invalid length'); + } + return subs; +} - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({message}); - }); - } +/***/ }), - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = function(index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } +/***/ 81044: +/***/ ((__unused_webpack_module, exports) => { - async _addToQueue(job) { - var args, blocked, error, options, reachedHWM, shifted, strategy; - ({args, options} = job); - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - } catch (error1) { - error = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); - job.doDrop({error}); - return false; - } - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - shifted.doDrop(); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } +"use strict"; - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseInteger = parseInteger; +exports.parseStringASCII = parseStringASCII; +exports.parseTime = parseTime; +exports.parseOID = parseOID; +exports.parseBoolean = parseBoolean; +exports.parseBitString = parseBitString; +/* +Copyright 2023 The Sigstore Authors. - submit(...args) { - var cb, fn, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args) => { - return new this.Promise(function(resolve, reject) { - return fn(...args, function(...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function(args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - schedule(...args) { - var job, options, task; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = {}; - } else { - [options, task, ...args] = args; - } - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } + http://www.apache.org/licenses/LICENSE-2.0 - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = function(options, ...args) { - return schedule(options, fn, ...args); - }; - return wrapped; - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; +const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/; +// Parse a BigInt from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer +function parseInteger(buf) { + let pos = 0; + const end = buf.length; + let val = buf[pos]; + const neg = val > 0x7f; + // Consume any padding bytes + const pad = neg ? 0xff : 0x00; + while (val == pad && ++pos < end) { + val = buf[pos]; + } + // Calculate remaining bytes to read + const len = end - pos; + if (len === 0) + return BigInt(neg ? -1 : 0); + // Handle two's complement for negative numbers + val = neg ? val - 256 : val; + // Parse remaining bytes + let n = BigInt(val); + for (let i = pos + 1; i < end; ++i) { + n = n * BigInt(256) + BigInt(buf[i]); + } + return n; +} +// Parse an ASCII string from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean +function parseStringASCII(buf) { + return buf.toString('ascii'); +} +// Parse a Date from the DER-encoded buffer +// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1 +function parseTime(buf, shortYear) { + const timeStr = parseStringASCII(buf); + // Parse the time string into matches - captured groups start at index 1 + const m = shortYear + ? RE_TIME_SHORT_YEAR.exec(timeStr) + : RE_TIME_LONG_YEAR.exec(timeStr); + if (!m) { + throw new Error('invalid time'); + } + // Translate dates with a 2-digit year to 4 digits per the spec + if (shortYear) { + let year = Number(m[1]); + year += year >= 50 ? 1900 : 2000; + m[1] = year.toString(); + } + // Translate to ISO8601 format and parse + return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`); +} +// Parse an OID from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier +function parseOID(buf) { + let pos = 0; + const end = buf.length; + // Consume first byte which encodes the first two OID components + let n = buf[pos++]; + const first = Math.floor(n / 40); + const second = n % 40; + let oid = `${first}.${second}`; + // Consume remaining bytes + let val = 0; + for (; pos < end; ++pos) { + n = buf[pos]; + val = (val << 7) + (n & 0x7f); + // If the left-most bit is NOT set, then this is the last byte in the + // sequence and we can add the value to the OID and reset the accumulator + if ((n & 0x80) === 0) { + oid += `.${val}`; + val = 0; + } + } + return oid; +} +// Parse a boolean from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean +function parseBoolean(buf) { + return buf[0] !== 0; +} +// Parse a bit string from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string +function parseBitString(buf) { + // First byte tell us how many unused bits are in the last byte + const unused = buf[0]; + const start = 1; + const end = buf.length; + const bits = []; + for (let i = start; i < end; ++i) { + const byte = buf[i]; + // The skip value is only used for the last byte + const skip = i === end - 1 ? unused : 0; + // Iterate over each bit in the byte (most significant first) + for (let j = 7; j >= skip; --j) { + // Read the bit and add it to the bit string + bits.push((byte >> j) & 0x01); + } + } + return bits; +} - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } - currentReservoir() { - return this._store.__currentReservoir__(); - } +/***/ }), - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +/***/ 59343: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } - Bottleneck.default = Bottleneck; +"use strict"; - Bottleneck.Events = Events$4; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ASN1Tag = void 0; +/* +Copyright 2023 The Sigstore Authors. - Bottleneck.version = Bottleneck.prototype.version = require$$8.version; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; + http://www.apache.org/licenses/LICENSE-2.0 - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = __nccwpck_require__(11121); +const UNIVERSAL_TAG = { + BOOLEAN: 0x01, + INTEGER: 0x02, + BIT_STRING: 0x03, + OCTET_STRING: 0x04, + OBJECT_IDENTIFIER: 0x06, + SEQUENCE: 0x10, + SET: 0x11, + PRINTABLE_STRING: 0x13, + UTC_TIME: 0x17, + GENERALIZED_TIME: 0x18, +}; +const TAG_CLASS = { + UNIVERSAL: 0x00, + APPLICATION: 0x01, + CONTEXT_SPECIFIC: 0x02, + PRIVATE: 0x03, +}; +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes +class ASN1Tag { + constructor(enc) { + // Bits 0 through 4 are the tag number + this.number = enc & 0x1f; + // Bit 5 is the constructed bit + this.constructed = (enc & 0x20) === 0x20; + // Bit 6 & 7 are the class + this.class = enc >> 6; + if (this.number === 0x1f) { + throw new error_1.ASN1ParseError('long form tags not supported'); + } + if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) { + throw new error_1.ASN1ParseError('unsupported tag 0x00'); + } + } + isUniversal() { + return this.class === TAG_CLASS.UNIVERSAL; + } + isContextSpecific(num) { + const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC; + return num !== undefined ? res && this.number === num : res; + } + isBoolean() { + return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN; + } + isInteger() { + return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER; + } + isBitString() { + return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING; + } + isOctetString() { + return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING; + } + isOID() { + return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER); + } + isUTCTime() { + return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME; + } + isGeneralizedTime() { + return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME; + } + toDER() { + return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6); + } +} +exports.ASN1Tag = ASN1Tag; - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; +/***/ }), - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; +/***/ 69368: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; +"use strict"; - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createPublicKey = createPublicKey; +exports.digest = digest; +exports.verify = verify; +exports.bufferEqual = bufferEqual; +/* +Copyright 2023 The Sigstore Authors. - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; + http://www.apache.org/licenses/LICENSE-2.0 - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const crypto_1 = __importDefault(__nccwpck_require__(76982)); +function createPublicKey(key, type = 'spki') { + if (typeof key === 'string') { + return crypto_1.default.createPublicKey(key); + } + else { + return crypto_1.default.createPublicKey({ key, format: 'der', type: type }); + } +} +function digest(algorithm, ...data) { + const hash = crypto_1.default.createHash(algorithm); + for (const d of data) { + hash.update(d); + } + return hash.digest(); +} +function verify(data, key, signature, algorithm) { + // The try/catch is to work around an issue in Node 14.x where verify throws + // an error in some scenarios if the signature is invalid. + try { + return crypto_1.default.verify(algorithm, data, key, signature); + } + catch (e) { + /* istanbul ignore next */ + return false; + } +} +function bufferEqual(a, b) { + try { + return crypto_1.default.timingSafeEqual(a, b); + } + catch { + /* istanbul ignore next */ + return false; + } +} - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; +/***/ }), - return Bottleneck; +/***/ 49032: +/***/ ((__unused_webpack_module, exports) => { - }).call(commonjsGlobal); +"use strict"; - var Bottleneck_1 = Bottleneck; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.preAuthEncoding = preAuthEncoding; +/* +Copyright 2023 The Sigstore Authors. - var lib = Bottleneck_1; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - return lib; + http://www.apache.org/licenses/LICENSE-2.0 -}))); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const PAE_PREFIX = 'DSSEv1'; +// DSSE Pre-Authentication Encoding +function preAuthEncoding(payloadType, payload) { + const prefix = [ + PAE_PREFIX, + payloadType.length, + payloadType, + payload.length, + '', + ].join(' '); + return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]); +} /***/ }), -/***/ 94691: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 52788: +/***/ ((__unused_webpack_module, exports) => { -var concatMap = __nccwpck_require__(97087); -var balanced = __nccwpck_require__(59380); +"use strict"; -module.exports = expandTop; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.base64Encode = base64Encode; +exports.base64Decode = base64Decode; +/* +Copyright 2023 The Sigstore Authors. -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + http://www.apache.org/licenses/LICENSE-2.0 -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const BASE64_ENCODING = 'base64'; +const UTF8_ENCODING = 'utf-8'; +function base64Encode(str) { + return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING); } - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function base64Decode(str) { + return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING); } -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); +/***/ }), - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +/***/ 83917: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } +"use strict"; - parts.push.apply(parts, p); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0; +/* +Copyright 2023 The Sigstore Authors. - return parts; -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -function expandTop(str) { - if (!str) - return []; + http://www.apache.org/licenses/LICENSE-2.0 - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var asn1_1 = __nccwpck_require__(86027); +Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return asn1_1.ASN1Obj; } })); +exports.crypto = __importStar(__nccwpck_require__(69368)); +exports.dsse = __importStar(__nccwpck_require__(49032)); +exports.encoding = __importStar(__nccwpck_require__(52788)); +exports.json = __importStar(__nccwpck_require__(13327)); +exports.pem = __importStar(__nccwpck_require__(1055)); +var rfc3161_1 = __nccwpck_require__(20994); +Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } })); +var stream_1 = __nccwpck_require__(1673); +Object.defineProperty(exports, "ByteStream", ({ enumerable: true, get: function () { return stream_1.ByteStream; } })); +var x509_1 = __nccwpck_require__(49358); +Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } })); +Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return x509_1.X509Certificate; } })); +Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return x509_1.X509SCTExtension; } })); - return expand(escapeBraces(str), true).map(unescapeBraces); -} -function identity(e) { - return e; -} +/***/ }), -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +/***/ 13327: +/***/ ((__unused_webpack_module, exports) => { -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +"use strict"; -function expand(str, isTop) { - var expansions = []; +/* +Copyright 2023 The Sigstore Authors. - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } + http://www.apache.org/licenses/LICENSE-2.0 - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.canonicalize = canonicalize; +// JSON canonicalization per https://github.com/cyberphone/json-canonicalization +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function canonicalize(object) { + let buffer = ''; + if (object === null || typeof object !== 'object' || object.toJSON != null) { + // Primitives or toJSONable objects + buffer += JSON.stringify(object); } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; + else if (Array.isArray(object)) { + // Array - maintain element order + buffer += '['; + let first = true; + object.forEach((element) => { + if (!first) { + buffer += ','; + } + first = false; + // recursive call + buffer += canonicalize(element); + }); + buffer += ']'; } - var pad = n.some(isPadded); + else { + // Object - Sort properties before serializing + buffer += '{'; + let first = true; + Object.keys(object) + .sort() + .forEach((property) => { + if (!first) { + buffer += ','; + } + first = false; + buffer += JSON.stringify(property); + buffer += ':'; + // recursive call + buffer += canonicalize(object[property]); + }); + buffer += '}'; + } + return buffer; +} - N = []; - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } +/***/ }), - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } +/***/ 91817: +/***/ ((__unused_webpack_module, exports) => { - return expansions; -} +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0; +exports.ECDSA_SIGNATURE_ALGOS = { + '1.2.840.10045.4.3.1': 'sha224', + '1.2.840.10045.4.3.2': 'sha256', + '1.2.840.10045.4.3.3': 'sha384', + '1.2.840.10045.4.3.4': 'sha512', +}; +exports.SHA2_HASH_ALGOS = { + '2.16.840.1.101.3.4.2.1': 'sha256', + '2.16.840.1.101.3.4.2.2': 'sha384', + '2.16.840.1.101.3.4.2.3': 'sha512', +}; /***/ }), -/***/ 40233: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1055: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toDER = toDER; +exports.fromDER = fromDER; +/* +Copyright 2023 The Sigstore Authors. -const contentVer = (__nccwpck_require__(4038)/* ["cache-version"].content */ .MH.Q) -const hashToSegments = __nccwpck_require__(99704) -const path = __nccwpck_require__(16928) -const ssri = __nccwpck_require__(68951) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -// Current format of content file path: -// -// sha512-BaSE64Hex= -> -// ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee -// -module.exports = contentPath + http://www.apache.org/licenses/LICENSE-2.0 -function contentPath (cache, integrity) { - const sri = ssri.parse(integrity, { single: true }) - // contentPath is the *strongest* algo given - return path.join( - contentDir(cache), - sri.algorithm, - ...hashToSegments(sri.hexDigest()) - ) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const PEM_HEADER = /-----BEGIN (.*)-----/; +const PEM_FOOTER = /-----END (.*)-----/; +function toDER(certificate) { + let der = ''; + certificate.split('\n').forEach((line) => { + if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) { + return; + } + der += line; + }); + return Buffer.from(der, 'base64'); } - -module.exports.contentDir = contentDir - -function contentDir (cache) { - return path.join(cache, `content-v${contentVer}`) +// Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM +// encoding dictates that each certificate should have a trailing newline after +// the footer. +function fromDER(certificate, type = 'CERTIFICATE') { + // Base64-encode the certificate. + const der = certificate.toString('base64'); + // Split the certificate into lines of 64 characters. + const lines = der.match(/.{1,64}/g) || ''; + return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`] + .join('\n') + .concat('\n'); } /***/ }), -/***/ 39398: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97512: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RFC3161TimestampVerificationError = void 0; +/* +Copyright 2023 The Sigstore Authors. -const fs = __nccwpck_require__(91943) -const fsm = __nccwpck_require__(25032) -const ssri = __nccwpck_require__(68951) -const contentPath = __nccwpck_require__(40233) -const Pipeline = __nccwpck_require__(52899) - -module.exports = read - -const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 -async function read (cache, integrity, opts = {}) { - const { size } = opts - const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { - // get size - const stat = size ? { size } : await fs.stat(cpath) - return { stat, cpath, sri } - }) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - if (stat.size > MAX_SINGLE_READ_SIZE) { - return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() - } + http://www.apache.org/licenses/LICENSE-2.0 - const data = await fs.readFile(cpath, { encoding: null }) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +class RFC3161TimestampVerificationError extends Error { +} +exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError; - if (stat.size !== data.length) { - throw sizeError(stat.size, data.length) - } - if (!ssri.checkData(data, sri)) { - throw integrityError(sri, cpath) - } +/***/ }), - return data -} +/***/ 20994: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const readPipeline = (cpath, size, sri, stream) => { - stream.push( - new fsm.ReadStream(cpath, { - size, - readSize: MAX_SINGLE_READ_SIZE, - }), - ssri.integrityStream({ - integrity: sri, - size, - }) - ) - return stream -} +"use strict"; -module.exports.stream = readStream -module.exports.readStream = readStream +/* +Copyright 2023 The Sigstore Authors. -function readStream (cache, integrity, opts = {}) { - const { size } = opts - const stream = new Pipeline() - // Set all this up to run on the stream and then just return the stream - Promise.resolve().then(async () => { - const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { - // get size - const stat = size ? { size } : await fs.stat(cpath) - return { stat, cpath, sri } - }) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - return readPipeline(cpath, stat.size, sri, stream) - }).catch(err => stream.emit('error', err)) + http://www.apache.org/licenses/LICENSE-2.0 - return stream -} +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RFC3161Timestamp = void 0; +var timestamp_1 = __nccwpck_require__(92714); +Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } })); -module.exports.copy = copy -function copy (cache, integrity, dest) { - return withContentSri(cache, integrity, (cpath) => { - return fs.copyFile(cpath, dest) - }) -} +/***/ }), -module.exports.hasContent = hasContent +/***/ 92714: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -async function hasContent (cache, integrity) { - if (!integrity) { - return false - } +"use strict"; - try { - return await withContentSri(cache, integrity, async (cpath, sri) => { - const stat = await fs.stat(cpath) - return { size: stat.size, sri, stat } - }) - } catch (err) { - if (err.code === 'ENOENT') { - return false +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RFC3161Timestamp = void 0; +/* +Copyright 2023 The Sigstore Authors. - if (err.code === 'EPERM') { - /* istanbul ignore else */ - if (process.platform !== 'win32') { - throw err - } else { - return false - } - } - } -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -async function withContentSri (cache, integrity, fn) { - const sri = ssri.parse(integrity) - // If `integrity` has multiple entries, pick the first digest - // with available local data. - const algo = sri.pickAlgorithm() - const digests = sri[algo] + http://www.apache.org/licenses/LICENSE-2.0 - if (digests.length <= 1) { - const cpath = contentPath(cache, digests[0]) - return fn(cpath, digests[0]) - } else { - // Can't use race here because a generic error can happen before - // a ENOENT error, and can happen before a valid result - const results = await Promise.all(digests.map(async (meta) => { - try { - return await withContentSri(cache, meta, fn) - } catch (err) { - if (err.code === 'ENOENT') { - return Object.assign( - new Error('No matching content found for ' + sri.toString()), - { code: 'ENOENT' } - ) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const asn1_1 = __nccwpck_require__(86027); +const crypto = __importStar(__nccwpck_require__(69368)); +const oid_1 = __nccwpck_require__(91817); +const error_1 = __nccwpck_require__(97512); +const tstinfo_1 = __nccwpck_require__(62925); +const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2'; +const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4'; +const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4'; +class RFC3161Timestamp { + constructor(asn1) { + this.root = asn1; + } + static parse(der) { + const asn1 = asn1_1.ASN1Obj.parseBuffer(der); + return new RFC3161Timestamp(asn1); + } + get status() { + return this.pkiStatusInfoObj.subs[0].toInteger(); + } + get contentType() { + return this.contentTypeObj.toOID(); + } + get eContentType() { + return this.eContentTypeObj.toOID(); + } + get signingTime() { + return this.tstInfo.genTime; + } + get signerIssuer() { + return this.signerSidObj.subs[0].value; + } + get signerSerialNumber() { + return this.signerSidObj.subs[1].value; + } + get signerDigestAlgorithm() { + const oid = this.signerDigestAlgorithmObj.subs[0].toOID(); + return oid_1.SHA2_HASH_ALGOS[oid]; + } + get signatureAlgorithm() { + const oid = this.signatureAlgorithmObj.subs[0].toOID(); + return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; + } + get signatureValue() { + return this.signatureValueObj.value; + } + get tstInfo() { + // Need to unpack tstInfo from an OCTET STRING + return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]); + } + verify(data, publicKey) { + if (!this.timeStampTokenObj) { + throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing'); } - return err - } - })) - // Return the first non error if it is found - const result = results.find((r) => !(r instanceof Error)) - if (result) { - return result + // Check for expected ContentInfo content type + if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) { + throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`); + } + // Check for expected encapsulated content type + if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) { + throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`); + } + // Check that the tstInfo references the correct artifact + this.tstInfo.verify(data); + // Check that the signed message digest matches the tstInfo + this.verifyMessageDigest(); + // Check that the signature is valid for the signed attributes + this.verifySignature(publicKey); } - - // Throw the No matching content found error - const enoentError = results.find((r) => r.code === 'ENOENT') - if (enoentError) { - throw enoentError + verifyMessageDigest() { + // Check that the tstInfo matches the signed data + const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw); + const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value; + if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) { + throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo'); + } + } + verifySignature(key) { + // Encode the signed attributes for verification + const signedAttrs = this.signedAttrsObj.toDER(); + signedAttrs[0] = 0x31; // Change context-specific tag to SET + // Check that the signature is valid for the signed attributes + const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm); + if (!verified) { + throw new error_1.RFC3161TimestampVerificationError('signature verification failed'); + } + } + // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 + get pkiStatusInfoObj() { + // pkiStatusInfo is the first element of the timestamp response sequence + return this.root.subs[0]; + } + // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 + get timeStampTokenObj() { + // timeStampToken is the first element of the timestamp response sequence + return this.root.subs[1]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-3 + get contentTypeObj() { + return this.timeStampTokenObj.subs[0]; + } + // https://www.rfc-editor.org/rfc/rfc5652#section-3 + get signedDataObj() { + const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); + return obj.subs[0]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 + get encapContentInfoObj() { + return this.signedDataObj.subs[2]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1 + get signerInfosObj() { + // SignerInfos is the last element of the signed data sequence + const sd = this.signedDataObj; + return sd.subs[sd.subs.length - 1]; + } + // https://www.rfc-editor.org/rfc/rfc5652#section-5.1 + get signerInfoObj() { + // Only supporting one signer + return this.signerInfosObj.subs[0]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 + get eContentTypeObj() { + return this.encapContentInfoObj.subs[0]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2 + get eContentObj() { + return this.encapContentInfoObj.subs[1]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 + get signedAttrsObj() { + const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00)); + return signedAttrs; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 + get messageDigestAttributeObj() { + const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() && + sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY); + return messageDigest; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 + get signerSidObj() { + return this.signerInfoObj.subs[1]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 + get signerDigestAlgorithmObj() { + // Signature is the 2nd element of the signerInfoObj object + return this.signerInfoObj.subs[2]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 + get signatureAlgorithmObj() { + // Signature is the 4th element of the signerInfoObj object + return this.signerInfoObj.subs[4]; + } + // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3 + get signatureValueObj() { + // Signature is the 6th element of the signerInfoObj object + return this.signerInfoObj.subs[5]; } - - // Throw generic error - throw results.find((r) => r instanceof Error) - } -} - -function sizeError (expected, found) { - /* eslint-disable-next-line max-len */ - const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) - err.expected = expected - err.found = found - err.code = 'EBADSIZE' - return err -} - -function integrityError (sri, path) { - const err = new Error(`Integrity verification failed for ${sri} (${path})`) - err.code = 'EINTEGRITY' - err.sri = sri - err.path = path - return err } +exports.RFC3161Timestamp = RFC3161Timestamp; /***/ }), -/***/ 92447: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 62925: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -const fs = __nccwpck_require__(91943) -const contentPath = __nccwpck_require__(40233) -const { hasContent } = __nccwpck_require__(39398) - -module.exports = rm - -async function rm (cache, integrity) { - const content = await hasContent(cache, integrity) - // ~pretty~ sure we can't end up with a content lacking sri, but be safe - if (content && content.sri) { - await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) - return true - } else { - return false - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TSTInfo = void 0; +const crypto = __importStar(__nccwpck_require__(69368)); +const oid_1 = __nccwpck_require__(91817); +const error_1 = __nccwpck_require__(97512); +class TSTInfo { + constructor(asn1) { + this.root = asn1; + } + get version() { + return this.root.subs[0].toInteger(); + } + get genTime() { + return this.root.subs[4].toDate(); + } + get messageImprintHashAlgorithm() { + const oid = this.messageImprintObj.subs[0].subs[0].toOID(); + return oid_1.SHA2_HASH_ALGOS[oid]; + } + get messageImprintHashedMessage() { + return this.messageImprintObj.subs[1].value; + } + get raw() { + return this.root.toDER(); + } + verify(data) { + const digest = crypto.digest(this.messageImprintHashAlgorithm, data); + if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) { + throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact'); + } + } + // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2 + get messageImprintObj() { + return this.root.subs[2]; + } } +exports.TSTInfo = TSTInfo; /***/ }), -/***/ 93699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1673: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ByteStream = void 0; +/* +Copyright 2023 The Sigstore Authors. -const events = __nccwpck_require__(24434) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -const contentPath = __nccwpck_require__(40233) -const fs = __nccwpck_require__(91943) -const { moveFile } = __nccwpck_require__(88437) -const { Minipass } = __nccwpck_require__(78275) -const Pipeline = __nccwpck_require__(52899) -const Flush = __nccwpck_require__(37633) -const path = __nccwpck_require__(16928) -const ssri = __nccwpck_require__(68951) -const uniqueFilename = __nccwpck_require__(46019) -const fsm = __nccwpck_require__(25032) + http://www.apache.org/licenses/LICENSE-2.0 -module.exports = write +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +class StreamError extends Error { +} +class ByteStream { + constructor(buffer) { + this.start = 0; + if (buffer) { + this.buf = buffer; + this.view = Buffer.from(buffer); + } + else { + this.buf = new ArrayBuffer(0); + this.view = Buffer.from(this.buf); + } + } + get buffer() { + return this.view.subarray(0, this.start); + } + get length() { + return this.view.byteLength; + } + get position() { + return this.start; + } + seek(position) { + this.start = position; + } + // Returns a Buffer containing the specified number of bytes starting at the + // given start position. + slice(start, len) { + const end = start + len; + if (end > this.length) { + throw new StreamError('request past end of buffer'); + } + return this.view.subarray(start, end); + } + appendChar(char) { + this.ensureCapacity(1); + this.view[this.start] = char; + this.start += 1; + } + appendUint16(num) { + this.ensureCapacity(2); + const value = new Uint16Array([num]); + const view = new Uint8Array(value.buffer); + this.view[this.start] = view[1]; + this.view[this.start + 1] = view[0]; + this.start += 2; + } + appendUint24(num) { + this.ensureCapacity(3); + const value = new Uint32Array([num]); + const view = new Uint8Array(value.buffer); + this.view[this.start] = view[2]; + this.view[this.start + 1] = view[1]; + this.view[this.start + 2] = view[0]; + this.start += 3; + } + appendView(view) { + this.ensureCapacity(view.length); + this.view.set(view, this.start); + this.start += view.length; + } + getBlock(size) { + if (size <= 0) { + return Buffer.alloc(0); + } + if (this.start + size > this.view.length) { + throw new Error('request past end of buffer'); + } + const result = this.view.subarray(this.start, this.start + size); + this.start += size; + return result; + } + getUint8() { + return this.getBlock(1)[0]; + } + getUint16() { + const block = this.getBlock(2); + return (block[0] << 8) | block[1]; + } + ensureCapacity(size) { + if (this.start + size > this.view.byteLength) { + const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0); + this.realloc(this.view.byteLength + blockSize); + } + } + realloc(size) { + const newArray = new ArrayBuffer(size); + const newView = Buffer.from(newArray); + // Copy the old buffer into the new one + newView.set(this.view); + this.buf = newArray; + this.view = newView; + } +} +exports.ByteStream = ByteStream; +ByteStream.BLOCK_SIZE = 1024; -// Cache of move operations in process so we don't duplicate -const moveOperations = new Map() -async function write (cache, data, opts = {}) { - const { algorithms, size, integrity } = opts +/***/ }), - if (typeof size === 'number' && data.length !== size) { - throw sizeError(size, data.length) - } +/***/ 83566: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) - if (integrity && !ssri.checkData(data, integrity, opts)) { - throw checksumError(integrity, sri) - } +"use strict"; - for (const algo in sri) { - const tmp = await makeTmp(cache, opts) - const hash = sri[algo].toString() - try { - await fs.writeFile(tmp.target, data, { flag: 'wx' }) - await moveToDestination(tmp, cache, hash, opts) - } finally { - if (!tmp.moved) { - await fs.rm(tmp.target, { recursive: true, force: true }) - } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - } - return { integrity: sri, size: data.length } -} + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; +/* +Copyright 2023 The Sigstore Authors. -module.exports.stream = writeStream +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -// writes proxied to the 'inputStream' that is passed to the Promise -// 'end' is deferred until content is handled. -class CacacheWriteStream extends Flush { - constructor (cache, opts) { - super() - this.opts = opts - this.cache = cache - this.inputStream = new Minipass() - this.inputStream.on('error', er => this.emit('error', er)) - this.inputStream.on('drain', () => this.emit('drain')) - this.handleContentP = null - } + http://www.apache.org/licenses/LICENSE-2.0 - write (chunk, encoding, cb) { - if (!this.handleContentP) { - this.handleContentP = handleContent( - this.inputStream, - this.cache, - this.opts - ) - this.handleContentP.catch(error => this.emit('error', error)) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const asn1_1 = __nccwpck_require__(86027); +const crypto = __importStar(__nccwpck_require__(69368)); +const oid_1 = __nccwpck_require__(91817); +const pem = __importStar(__nccwpck_require__(1055)); +const ext_1 = __nccwpck_require__(96389); +const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14'; +const EXTENSION_OID_KEY_USAGE = '2.5.29.15'; +const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17'; +const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19'; +const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35'; +exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2'; +class X509Certificate { + constructor(asn1) { + this.root = asn1; } - return this.inputStream.write(chunk, encoding, cb) - } - - flush (cb) { - this.inputStream.end(() => { - if (!this.handleContentP) { - const e = new Error('Cache input stream was empty') - e.code = 'ENODATA' - // empty streams are probably emitting end right away. - // defer this one tick by rejecting a promise on it. - return Promise.reject(e).catch(cb) - } - // eslint-disable-next-line promise/catch-or-return - this.handleContentP.then( - (res) => { - res.integrity && this.emit('integrity', res.integrity) - // eslint-disable-next-line promise/always-return - res.size !== null && this.emit('size', res.size) - cb() - }, - (er) => cb(er) - ) - }) - } -} - -function writeStream (cache, opts = {}) { - return new CacacheWriteStream(cache, opts) -} - -async function handleContent (inputStream, cache, opts) { - const tmp = await makeTmp(cache, opts) - try { - const res = await pipeToTmp(inputStream, cache, tmp.target, opts) - await moveToDestination( - tmp, - cache, - res.integrity, - opts - ) - return res - } finally { - if (!tmp.moved) { - await fs.rm(tmp.target, { recursive: true, force: true }) + static parse(cert) { + const der = typeof cert === 'string' ? pem.toDER(cert) : cert; + const asn1 = asn1_1.ASN1Obj.parseBuffer(der); + return new X509Certificate(asn1); + } + get tbsCertificate() { + return this.tbsCertificateObj; + } + get version() { + // version number is the first element of the version context specific tag + const ver = this.versionObj.subs[0].toInteger(); + return `v${(ver + BigInt(1)).toString()}`; + } + get serialNumber() { + return this.serialNumberObj.value; + } + get notBefore() { + // notBefore is the first element of the validity sequence + return this.validityObj.subs[0].toDate(); + } + get notAfter() { + // notAfter is the second element of the validity sequence + return this.validityObj.subs[1].toDate(); + } + get issuer() { + return this.issuerObj.value; + } + get subject() { + return this.subjectObj.value; + } + get publicKey() { + return this.subjectPublicKeyInfoObj.toDER(); + } + get signatureAlgorithm() { + const oid = this.signatureAlgorithmObj.subs[0].toOID(); + return oid_1.ECDSA_SIGNATURE_ALGOS[oid]; + } + get signatureValue() { + // Signature value is a bit string, so we need to skip the first byte + return this.signatureValueObj.value.subarray(1); + } + get subjectAltName() { + const ext = this.extSubjectAltName; + return ext?.uri || /* istanbul ignore next */ ext?.rfc822Name; + } + get extensions() { + // The extension list is the first (and only) element of the extensions + // context specific tag + /* istanbul ignore next */ + const extSeq = this.extensionsObj?.subs[0]; + /* istanbul ignore next */ + return extSeq?.subs || []; + } + get extKeyUsage() { + const ext = this.findExtension(EXTENSION_OID_KEY_USAGE); + return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined; + } + get extBasicConstraints() { + const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS); + return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined; + } + get extSubjectAltName() { + const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME); + return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined; + } + get extAuthorityKeyID() { + const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID); + return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined; + } + get extSubjectKeyID() { + const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID); + return ext + ? new ext_1.X509SubjectKeyIDExtension(ext) + : /* istanbul ignore next */ undefined; + } + get extSCT() { + const ext = this.findExtension(exports.EXTENSION_OID_SCT); + return ext ? new ext_1.X509SCTExtension(ext) : undefined; + } + get isCA() { + const ca = this.extBasicConstraints?.isCA || false; + // If the KeyUsage extension is present, keyCertSign must be set + if (this.extKeyUsage) { + return ca && this.extKeyUsage.keyCertSign; + } + // TODO: test coverage for this case + /* istanbul ignore next */ + return ca; + } + extension(oid) { + const ext = this.findExtension(oid); + return ext ? new ext_1.X509Extension(ext) : undefined; + } + verify(issuerCertificate) { + // Use the issuer's public key if provided, otherwise use the subject's + const publicKey = issuerCertificate?.publicKey || this.publicKey; + const key = crypto.createPublicKey(publicKey); + return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm); + } + validForDate(date) { + return this.notBefore <= date && date <= this.notAfter; + } + equals(other) { + return this.root.toDER().equals(other.root.toDER()); + } + // Creates a copy of the certificate with a new buffer + clone() { + const der = this.root.toDER(); + const clone = Buffer.alloc(der.length); + der.copy(clone); + return X509Certificate.parse(clone); + } + findExtension(oid) { + // Find the extension with the given OID. The OID will always be the first + // element of the extension sequence + return this.extensions.find((ext) => ext.subs[0].toOID() === oid); + } + ///////////////////////////////////////////////////////////////////////////// + // The following properties use the documented x509 structure to locate the + // desired ASN.1 object + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1 + get tbsCertificateObj() { + // tbsCertificate is the first element of the certificate sequence + return this.root.subs[0]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2 + get signatureAlgorithmObj() { + // signatureAlgorithm is the second element of the certificate sequence + return this.root.subs[1]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3 + get signatureValueObj() { + // signatureValue is the third element of the certificate sequence + return this.root.subs[2]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1 + get versionObj() { + // version is the first element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[0]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2 + get serialNumberObj() { + // serialNumber is the second element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[1]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4 + get issuerObj() { + // issuer is the fourth element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[3]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5 + get validityObj() { + // version is the fifth element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[4]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6 + get subjectObj() { + // subject is the sixth element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[5]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7 + get subjectPublicKeyInfoObj() { + // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[6]; + } + // Extensions can't be located by index because their position varies. Instead, + // we need to find the extensions context specific tag + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9 + get extensionsObj() { + return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03)); } - } -} - -async function pipeToTmp (inputStream, cache, tmpTarget, opts) { - const outStream = new fsm.WriteStream(tmpTarget, { - flags: 'wx', - }) - - if (opts.integrityEmitter) { - // we need to create these all simultaneously since they can fire in any order - const [integrity, size] = await Promise.all([ - events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), - events.once(opts.integrityEmitter, 'size').then(res => res[0]), - new Pipeline(inputStream, outStream).promise(), - ]) - return { integrity, size } - } - - let integrity - let size - const hashStream = ssri.integrityStream({ - integrity: opts.integrity, - algorithms: opts.algorithms, - size: opts.size, - }) - hashStream.on('integrity', i => { - integrity = i - }) - hashStream.on('size', s => { - size = s - }) - - const pipeline = new Pipeline(inputStream, hashStream, outStream) - await pipeline.promise() - return { integrity, size } -} - -async function makeTmp (cache, opts) { - const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) - await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) - return { - target: tmpTarget, - moved: false, - } -} - -async function moveToDestination (tmp, cache, sri) { - const destination = contentPath(cache, sri) - const destDir = path.dirname(destination) - if (moveOperations.has(destination)) { - return moveOperations.get(destination) - } - moveOperations.set( - destination, - fs.mkdir(destDir, { recursive: true }) - .then(async () => { - await moveFile(tmp.target, destination, { overwrite: false }) - tmp.moved = true - return tmp.moved - }) - .catch(err => { - if (!err.message.startsWith('The destination file exists')) { - throw Object.assign(err, { code: 'EEXIST' }) - } - }).finally(() => { - moveOperations.delete(destination) - }) - - ) - return moveOperations.get(destination) -} - -function sizeError (expected, found) { - /* eslint-disable-next-line max-len */ - const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) - err.expected = expected - err.found = found - err.code = 'EBADSIZE' - return err -} - -function checksumError (expected, found) { - const err = new Error(`Integrity check failed: - Wanted: ${expected} - Found: ${found}`) - err.code = 'EINTEGRITY' - err.expected = expected - err.found = found - return err } +exports.X509Certificate = X509Certificate; /***/ }), -/***/ 26575: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 96389: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const crypto = __nccwpck_require__(76982) -const { - appendFile, - mkdir, - readFile, - readdir, - rm, - writeFile, -} = __nccwpck_require__(91943) -const { Minipass } = __nccwpck_require__(78275) -const path = __nccwpck_require__(16928) -const ssri = __nccwpck_require__(68951) -const uniqueFilename = __nccwpck_require__(46019) - -const contentPath = __nccwpck_require__(40233) -const hashToSegments = __nccwpck_require__(99704) -const indexV = (__nccwpck_require__(4038)/* ["cache-version"].index */ .MH.P) -const { moveFile } = __nccwpck_require__(88437) - -const lsStreamConcurrency = 5 - -module.exports.NotFoundError = class NotFoundError extends Error { - constructor (cache, key) { - super(`No cache entry for ${key} found in ${cache}`) - this.code = 'ENOENT' - this.cache = cache - this.key = key - } -} - -module.exports.compact = compact - -async function compact (cache, key, matchFn, opts = {}) { - const bucket = bucketPath(cache, key) - const entries = await bucketEntries(bucket) - const newEntries = [] - // we loop backwards because the bottom-most result is the newest - // since we add new entries with appendFile - for (let i = entries.length - 1; i >= 0; --i) { - const entry = entries[i] - // a null integrity could mean either a delete was appended - // or the user has simply stored an index that does not map - // to any content. we determine if the user wants to keep the - // null integrity based on the validateEntry function passed in options. - // if the integrity is null and no validateEntry is provided, we break - // as we consider the null integrity to be a deletion of everything - // that came before it. - if (entry.integrity === null && !opts.validateEntry) { - break +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0; +const stream_1 = __nccwpck_require__(1673); +const sct_1 = __nccwpck_require__(6144); +// https://www.rfc-editor.org/rfc/rfc5280#section-4.1 +class X509Extension { + constructor(asn1) { + this.root = asn1; } - - // if this entry is valid, and it is either the first entry or - // the newEntries array doesn't already include an entry that - // matches this one based on the provided matchFn, then we add - // it to the beginning of our list - if ((!opts.validateEntry || opts.validateEntry(entry) === true) && - (newEntries.length === 0 || - !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { - newEntries.unshift(entry) + get oid() { + return this.root.subs[0].toOID(); } - } - - const newIndex = '\n' + newEntries.map((entry) => { - const stringified = JSON.stringify(entry) - const hash = hashEntry(stringified) - return `${hash}\t${stringified}` - }).join('\n') - - const setup = async () => { - const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) - await mkdir(path.dirname(target), { recursive: true }) - return { - target, - moved: false, + get critical() { + // The critical field is optional and will be the second element of the + // extension sequence if present. Default to false if not present. + return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false; } - } - - const teardown = async (tmp) => { - if (!tmp.moved) { - return rm(tmp.target, { recursive: true, force: true }) + get value() { + return this.extnValueObj.value; + } + get valueObj() { + return this.extnValueObj; + } + get extnValueObj() { + // The extnValue field will be the last element of the extension sequence + return this.root.subs[this.root.subs.length - 1]; } - } - - const write = async (tmp) => { - await writeFile(tmp.target, newIndex, { flag: 'wx' }) - await mkdir(path.dirname(bucket), { recursive: true }) - // we use @npmcli/move-file directly here because we - // want to overwrite the existing file - await moveFile(tmp.target, bucket) - tmp.moved = true - } - - // write the file atomically - const tmp = await setup() - try { - await write(tmp) - } finally { - await teardown(tmp) - } - - // we reverse the list we generated such that the newest - // entries come first in order to make looping through them easier - // the true passed to formatEntry tells it to keep null - // integrity values, if they made it this far it's because - // validateEntry returned true, and as such we should return it - return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) } - -module.exports.insert = insert - -async function insert (cache, key, integrity, opts = {}) { - const { metadata, size, time } = opts - const bucket = bucketPath(cache, key) - const entry = { - key, - integrity: integrity && ssri.stringify(integrity), - time: time || Date.now(), - size, - metadata, - } - try { - await mkdir(path.dirname(bucket), { recursive: true }) - const stringified = JSON.stringify(entry) - // NOTE - Cleverness ahoy! - // - // This works because it's tremendously unlikely for an entry to corrupt - // another while still preserving the string length of the JSON in - // question. So, we just slap the length in there and verify it on read. - // - // Thanks to @isaacs for the whiteboarding session that ended up with - // this. - await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) - } catch (err) { - if (err.code === 'ENOENT') { - return undefined +exports.X509Extension = X509Extension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9 +class X509BasicConstraintsExtension extends X509Extension { + get isCA() { + return this.sequence.subs[0]?.toBoolean() ?? false; + } + get pathLenConstraint() { + return this.sequence.subs.length > 1 + ? this.sequence.subs[1].toInteger() + : undefined; + } + // The extnValue field contains a single sequence wrapping the isCA and + // pathLenConstraint. + get sequence() { + return this.extnValueObj.subs[0]; } - - throw err - } - return formatEntry(cache, entry) } - -module.exports.find = find - -async function find (cache, key) { - const bucket = bucketPath(cache, key) - try { - const entries = await bucketEntries(bucket) - return entries.reduce((latest, next) => { - if (next && next.key === key) { - return formatEntry(cache, next) - } else { - return latest - } - }, null) - } catch (err) { - if (err.code === 'ENOENT') { - return null - } else { - throw err +exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3 +class X509KeyUsageExtension extends X509Extension { + get digitalSignature() { + return this.bitString[0] === 1; + } + get keyCertSign() { + return this.bitString[5] === 1; + } + get crlSign() { + return this.bitString[6] === 1; + } + // The extnValue field contains a single bit string which is a bit mask + // indicating which key usages are enabled. + get bitString() { + return this.extnValueObj.subs[0].toBitString(); } - } } - -module.exports["delete"] = del - -function del (cache, key, opts = {}) { - if (!opts.removeFully) { - return insert(cache, key, null, opts) - } - - const bucket = bucketPath(cache, key) - return rm(bucket, { recursive: true, force: true }) +exports.X509KeyUsageExtension = X509KeyUsageExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6 +class X509SubjectAlternativeNameExtension extends X509Extension { + get rfc822Name() { + return this.findGeneralName(0x01)?.value.toString('ascii'); + } + get uri() { + return this.findGeneralName(0x06)?.value.toString('ascii'); + } + // Retrieve the value of an otherName with the given OID. + otherName(oid) { + const otherName = this.findGeneralName(0x00); + if (otherName === undefined) { + return undefined; + } + // The otherName is a sequence containing an OID and a value. + // Need to check that the OID matches the one we're looking for. + const otherNameOID = otherName.subs[0].toOID(); + if (otherNameOID !== oid) { + return undefined; + } + // The otherNameValue is a sequence containing the actual value. + const otherNameValue = otherName.subs[1]; + return otherNameValue.subs[0].value.toString('ascii'); + } + findGeneralName(tag) { + return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag)); + } + // The extnValue field contains a sequence of GeneralNames. + get generalNames() { + return this.extnValueObj.subs[0].subs; + } } - -module.exports.lsStream = lsStream - -function lsStream (cache) { - const indexDir = bucketDir(cache) - const stream = new Minipass({ objectMode: true }) - - // Set all this up to run on the stream and then just return the stream - Promise.resolve().then(async () => { - const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606)) - const buckets = await readdirOrEmpty(indexDir) - await pMap(buckets, async (bucket) => { - const bucketPath = path.join(indexDir, bucket) - const subbuckets = await readdirOrEmpty(bucketPath) - await pMap(subbuckets, async (subbucket) => { - const subbucketPath = path.join(bucketPath, subbucket) - - // "/cachename//./*" - const subbucketEntries = await readdirOrEmpty(subbucketPath) - await pMap(subbucketEntries, async (entry) => { - const entryPath = path.join(subbucketPath, entry) - try { - const entries = await bucketEntries(entryPath) - // using a Map here prevents duplicate keys from showing up - // twice, I guess? - const reduced = entries.reduce((acc, entry) => { - acc.set(entry.key, entry) - return acc - }, new Map()) - // reduced is a map of key => entry - for (const entry of reduced.values()) { - const formatted = formatEntry(cache, entry) - if (formatted) { - stream.write(formatted) - } - } - } catch (err) { - if (err.code === 'ENOENT') { - return undefined - } - throw err - } - }, - { concurrency: lsStreamConcurrency }) - }, - { concurrency: lsStreamConcurrency }) - }, - { concurrency: lsStreamConcurrency }) - stream.end() - return stream - }).catch(err => stream.emit('error', err)) - - return stream +exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1 +class X509AuthorityKeyIDExtension extends X509Extension { + get keyIdentifier() { + return this.findSequenceMember(0x00)?.value; + } + findSequenceMember(tag) { + return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag)); + } + // The extnValue field contains a single sequence wrapping the keyIdentifier + get sequence() { + return this.extnValueObj.subs[0]; + } } - -module.exports.ls = ls - -async function ls (cache) { - const entries = await lsStream(cache).collect() - return entries.reduce((acc, xs) => { - acc[xs.key] = xs - return acc - }, {}) +exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2 +class X509SubjectKeyIDExtension extends X509Extension { + get keyIdentifier() { + return this.extnValueObj.subs[0].value; + } +} +exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension; +// https://www.rfc-editor.org/rfc/rfc6962#section-3.3 +class X509SCTExtension extends X509Extension { + constructor(asn1) { + super(asn1); + } + get signedCertificateTimestamps() { + const buf = this.extnValueObj.subs[0].value; + const stream = new stream_1.ByteStream(buf); + // The overall list length is encoded in the first two bytes -- note this + // is the length of the list in bytes, NOT the number of SCTs in the list + const end = stream.getUint16() + 2; + const sctList = []; + while (stream.position < end) { + // Read the length of the next SCT + const sctLength = stream.getUint16(); + // Slice out the bytes for the next SCT and parse it + const sct = stream.getBlock(sctLength); + sctList.push(sct_1.SignedCertificateTimestamp.parse(sct)); + } + if (stream.position !== end) { + throw new Error('SCT list length does not match actual length'); + } + return sctList; + } } +exports.X509SCTExtension = X509SCTExtension; -module.exports.bucketEntries = bucketEntries -async function bucketEntries (bucket, filter) { - const data = await readFile(bucket, 'utf8') - return _bucketEntries(data, filter) -} +/***/ }), -function _bucketEntries (data) { - const entries = [] - data.split('\n').forEach((entry) => { - if (!entry) { - return - } +/***/ 49358: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const pieces = entry.split('\t') - if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { - // Hash is no good! Corruption or malice? Doesn't matter! - // EJECT EJECT - return - } - let obj - try { - obj = JSON.parse(pieces[1]) - } catch (_) { - // eslint-ignore-next-line no-empty-block - } - // coverage disabled here, no need to test with an entry that parses to something falsey - // istanbul ignore else - if (obj) { - entries.push(obj) - } - }) - return entries -} +"use strict"; -module.exports.bucketDir = bucketDir +/* +Copyright 2023 The Sigstore Authors. -function bucketDir (cache) { - return path.join(cache, `index-v${indexV}`) -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports.bucketPath = bucketPath + http://www.apache.org/licenses/LICENSE-2.0 -function bucketPath (cache, key) { - const hashed = hashKey(key) - return path.join.apply( - path, - [bucketDir(cache)].concat(hashToSegments(hashed)) - ) -} +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0; +var cert_1 = __nccwpck_require__(83566); +Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return cert_1.EXTENSION_OID_SCT; } })); +Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return cert_1.X509Certificate; } })); +var ext_1 = __nccwpck_require__(96389); +Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return ext_1.X509SCTExtension; } })); -module.exports.hashKey = hashKey -function hashKey (key) { - return hash(key, 'sha256') -} +/***/ }), -module.exports.hashEntry = hashEntry +/***/ 6144: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function hashEntry (str) { - return hash(str, 'sha1') -} +"use strict"; -function hash (str, digest) { - return crypto - .createHash(digest) - .update(str) - .digest('hex') -} +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SignedCertificateTimestamp = void 0; +/* +Copyright 2023 The Sigstore Authors. -function formatEntry (cache, entry, keepAll) { - // Treat null digests as deletions. They'll shadow any previous entries. - if (!entry.integrity && !keepAll) { - return null - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - return { - key: entry.key, - integrity: entry.integrity, - path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, - size: entry.size, - time: entry.time, - metadata: entry.metadata, - } -} + http://www.apache.org/licenses/LICENSE-2.0 -function readdirOrEmpty (dir) { - return readdir(dir).catch((err) => { - if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { - return [] +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const crypto = __importStar(__nccwpck_require__(69368)); +const stream_1 = __nccwpck_require__(1673); +class SignedCertificateTimestamp { + constructor(options) { + this.version = options.version; + this.logID = options.logID; + this.timestamp = options.timestamp; + this.extensions = options.extensions; + this.hashAlgorithm = options.hashAlgorithm; + this.signatureAlgorithm = options.signatureAlgorithm; + this.signature = options.signature; + } + get datetime() { + return new Date(Number(this.timestamp.readBigInt64BE())); + } + // Returns the hash algorithm used to generate the SCT's signature. + // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 + get algorithm() { + switch (this.hashAlgorithm) { + /* istanbul ignore next */ + case 0: + return 'none'; + /* istanbul ignore next */ + case 1: + return 'md5'; + /* istanbul ignore next */ + case 2: + return 'sha1'; + /* istanbul ignore next */ + case 3: + return 'sha224'; + case 4: + return 'sha256'; + /* istanbul ignore next */ + case 5: + return 'sha384'; + /* istanbul ignore next */ + case 6: + return 'sha512'; + /* istanbul ignore next */ + default: + return 'unknown'; + } + } + verify(preCert, key) { + // Assemble the digitally-signed struct (the data over which the signature + // was generated). + // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 + const stream = new stream_1.ByteStream(); + stream.appendChar(this.version); + stream.appendChar(0x00); // SignatureType = certificate_timestamp(0) + stream.appendView(this.timestamp); + stream.appendUint16(0x01); // LogEntryType = precert_entry(1) + stream.appendView(preCert); + stream.appendUint16(this.extensions.byteLength); + /* istanbul ignore next - extensions are very uncommon */ + if (this.extensions.byteLength > 0) { + stream.appendView(this.extensions); + } + return crypto.verify(stream.buffer, key, this.signature, this.algorithm); + } + // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using + // TLS encoding which means the fields and lengths of most fields are + // specified as part of the SCT and TLS specs. + // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 + // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 + static parse(buf) { + const stream = new stream_1.ByteStream(buf); + // Version - enum { v1(0), (255) } + const version = stream.getUint8(); + // Log ID - struct { opaque key_id[32]; } + const logID = stream.getBlock(32); + // Timestamp - uint64 + const timestamp = stream.getBlock(8); + // Extensions - opaque extensions<0..2^16-1>; + const extenstionLength = stream.getUint16(); + const extensions = stream.getBlock(extenstionLength); + // Hash algo - enum { sha256(4), . . . (255) } + const hashAlgorithm = stream.getUint8(); + // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } + const signatureAlgorithm = stream.getUint8(); + // Signature - opaque signature<0..2^16-1>; + const sigLength = stream.getUint16(); + const signature = stream.getBlock(sigLength); + // Check that we read the entire buffer + if (stream.position !== buf.length) { + throw new Error('SCT buffer length mismatch'); + } + return new SignedCertificateTimestamp({ + version, + logID, + timestamp, + extensions, + hashAlgorithm, + signatureAlgorithm, + signature, + }); } - - throw err - }) } +exports.SignedCertificateTimestamp = SignedCertificateTimestamp; /***/ }), -/***/ 19690: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 23688: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HEADER_OCI_SUBJECT = exports.HEADER_LOCATION = exports.HEADER_IF_MATCH = exports.HEADER_ETAG = exports.HEADER_DIGEST = exports.HEADER_CONTENT_TYPE = exports.HEADER_CONTENT_LENGTH = exports.HEADER_AUTHORIZATION = exports.HEADER_AUTHENTICATE = exports.HEADER_API_VERSION = exports.HEADER_ACCEPT = exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = exports.CONTENT_TYPE_OCTET_STREAM = exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = exports.CONTENT_TYPE_DOCKER_MANIFEST = exports.CONTENT_TYPE_OCI_MANIFEST = exports.CONTENT_TYPE_OCI_INDEX = void 0; +/* +Copyright 2023 The Sigstore Authors. -const Collect = __nccwpck_require__(11757) -const { Minipass } = __nccwpck_require__(78275) -const Pipeline = __nccwpck_require__(52899) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -const index = __nccwpck_require__(26575) -const memo = __nccwpck_require__(56068) -const read = __nccwpck_require__(39398) + http://www.apache.org/licenses/LICENSE-2.0 -async function getData (cache, key, opts = {}) { - const { integrity, memoize, size } = opts - const memoized = memo.get(cache, key, opts) - if (memoized && memoize !== false) { - return { - metadata: memoized.entry.metadata, - data: memoized.data, - integrity: memoized.entry.integrity, - size: memoized.entry.size, - } - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +exports.CONTENT_TYPE_OCI_INDEX = 'application/vnd.oci.image.index.v1+json'; +exports.CONTENT_TYPE_OCI_MANIFEST = 'application/vnd.oci.image.manifest.v1+json'; +exports.CONTENT_TYPE_DOCKER_MANIFEST = 'application/vnd.docker.distribution.manifest.v2+json'; +exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = 'application/vnd.docker.distribution.manifest.list.v2+json'; +exports.CONTENT_TYPE_OCTET_STREAM = 'application/octet-stream'; +exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = 'application/vnd.oci.empty.v1+json'; +exports.HEADER_ACCEPT = 'Accept'; +exports.HEADER_API_VERSION = 'Docker-Distribution-API-Version'; +exports.HEADER_AUTHENTICATE = 'WWW-Authenticate'; +exports.HEADER_AUTHORIZATION = 'Authorization'; +exports.HEADER_CONTENT_LENGTH = 'Content-Length'; +exports.HEADER_CONTENT_TYPE = 'Content-Type'; +exports.HEADER_DIGEST = 'Docker-Content-Digest'; +exports.HEADER_ETAG = 'Etag'; +exports.HEADER_IF_MATCH = 'If-Match'; +exports.HEADER_LOCATION = 'Location'; +exports.HEADER_OCI_SUBJECT = 'OCI-Subject'; - const entry = await index.find(cache, key, opts) - if (!entry) { - throw new index.NotFoundError(cache, key) - } - const data = await read(cache, entry.integrity, { integrity, size }) - if (memoize) { - memo.put(cache, entry, data, opts) - } - return { - data, - metadata: entry.metadata, - size: entry.size, - integrity: entry.integrity, - } -} -module.exports = getData +/***/ }), -async function getDataByDigest (cache, key, opts = {}) { - const { integrity, memoize, size } = opts - const memoized = memo.get.byDigest(cache, key, opts) - if (memoized && memoize !== false) { - return memoized - } +/***/ 62691: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const res = await read(cache, key, { integrity, size }) - if (memoize) { - memo.put.byDigest(cache, key, res, opts) - } - return res -} -module.exports.byDigest = getDataByDigest +"use strict"; -const getMemoizedStream = (memoized) => { - const stream = new Minipass() - stream.on('newListener', function (ev, cb) { - ev === 'metadata' && cb(memoized.entry.metadata) - ev === 'integrity' && cb(memoized.entry.integrity) - ev === 'size' && cb(memoized.entry.size) - }) - stream.end(memoized.data) - return stream -} +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromBasicAuth = exports.toBasicAuth = exports.getRegistryCredentials = void 0; +/* +Copyright 2023 The Sigstore Authors. -function getStream (cache, key, opts = {}) { - const { memoize, size } = opts - const memoized = memo.get(cache, key, opts) - if (memoized && memoize !== false) { - return getMemoizedStream(memoized) - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - const stream = new Pipeline() - // Set all this up to run on the stream and then just return the stream - Promise.resolve().then(async () => { - const entry = await index.find(cache, key) - if (!entry) { - throw new index.NotFoundError(cache, key) - } + http://www.apache.org/licenses/LICENSE-2.0 - stream.emit('metadata', entry.metadata) - stream.emit('integrity', entry.integrity) - stream.emit('size', entry.size) - stream.on('newListener', function (ev, cb) { - ev === 'metadata' && cb(entry.metadata) - ev === 'integrity' && cb(entry.integrity) - ev === 'size' && cb(entry.size) - }) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const node_fs_1 = __importDefault(__nccwpck_require__(73024)); +const node_os_1 = __importDefault(__nccwpck_require__(48161)); +const node_path_1 = __importDefault(__nccwpck_require__(76760)); +const name_1 = __nccwpck_require__(96666); +// Returns the credentials for a given registry by reading the Docker config +// file. +const getRegistryCredentials = (imageName) => { + const { registry } = (0, name_1.parseImageName)(imageName); + const dockerConfigFile = node_path_1.default.join(node_os_1.default.homedir(), '.docker', 'config.json'); + let content; + try { + content = node_fs_1.default.readFileSync(dockerConfigFile, 'utf8'); + } + catch (err) { + throw new Error(`No credential file found at ${dockerConfigFile}`); + } + const dockerConfig = JSON.parse(content); + const credKey = Object.keys(dockerConfig.auths || {}).find((key) => key.includes(registry)) || registry; + const creds = dockerConfig.auths?.[credKey]; + if (!creds) { + throw new Error(`No credentials found for registry ${registry}`); + } + // Extract username/password from auth string + const { username, password } = (0, exports.fromBasicAuth)(creds.auth); + // If the identitytoken is present, use it as the password (primarily for ACR) + const pass = creds.identitytoken ? creds.identitytoken : password; + return { username, password: pass }; +}; +exports.getRegistryCredentials = getRegistryCredentials; +// Encode the username and password as base64-encoded basicauth value +const toBasicAuth = (creds) => Buffer.from(`${creds.username}:${creds.password}`).toString('base64'); +exports.toBasicAuth = toBasicAuth; +// Decode the base64-encoded basicauth value +const fromBasicAuth = (auth) => { + // Need to account for the possibility of ':' in the password + const [username, ...rest] = Buffer.from(auth, 'base64').toString().split(':'); + const password = rest.join(':'); + return { username, password }; +}; +exports.fromBasicAuth = fromBasicAuth; - const src = read.readStream( - cache, - entry.integrity, - { ...opts, size: typeof size !== 'number' ? entry.size : size } - ) - if (memoize) { - const memoStream = new Collect.PassThrough() - memoStream.on('collect', data => memo.put(cache, entry, data, opts)) - stream.unshift(memoStream) - } - stream.unshift(src) - return stream - }).catch((err) => stream.emit('error', err)) +/***/ }), - return stream -} +/***/ 46803: +/***/ ((__unused_webpack_module, exports) => { -module.exports.stream = getStream +"use strict"; -function getStreamDigest (cache, integrity, opts = {}) { - const { memoize } = opts - const memoized = memo.get.byDigest(cache, integrity, opts) - if (memoized && memoize !== false) { - const stream = new Minipass() - stream.end(memoized) - return stream - } else { - const stream = read.readStream(cache, integrity, opts) - if (!memoize) { - return stream +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OCIError = exports.ensureStatus = exports.HTTPError = void 0; +class HTTPError extends Error { + constructor({ status, message }) { + super(message); + this.statusCode = status; } - - const memoStream = new Collect.PassThrough() - memoStream.on('collect', data => memo.put.byDigest( - cache, - integrity, - data, - opts - )) - return new Pipeline(stream, memoStream) - } } +exports.HTTPError = HTTPError; +// Inspects the response status and throws an HTTPError if it does not match the +// expected status code +const ensureStatus = (expectedStatus) => { + return (response) => { + if (response.status !== expectedStatus) { + throw new HTTPError({ + message: `Error fetching ${response.url} - expected ${expectedStatus}, received ${response.status}`, + status: response.status, + }); + } + return response; + }; +}; +exports.ensureStatus = ensureStatus; +class OCIError extends Error { + constructor({ message, cause, }) { + super(message); + this.cause = cause; + this.name = this.constructor.name; + } +} +exports.OCIError = OCIError; -module.exports.stream.byDigest = getStreamDigest -function info (cache, key, opts = {}) { - const { memoize } = opts - const memoized = memo.get(cache, key, opts) - if (memoized && memoize !== false) { - return Promise.resolve(memoized.entry) - } else { - return index.find(cache, key) - } -} -module.exports.info = info +/***/ }), -async function copy (cache, key, dest, opts = {}) { - const entry = await index.find(cache, key, opts) - if (!entry) { - throw new index.NotFoundError(cache, key) - } - await read.copy(cache, entry.integrity, dest, opts) - return { - metadata: entry.metadata, - size: entry.size, - integrity: entry.integrity, - } -} +/***/ 32721: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -module.exports.copy = copy +"use strict"; -async function copyByDigest (cache, key, dest, opts = {}) { - await read.copy(cache, key, dest, opts) - return key -} +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* +Copyright 2024 The Sigstore Authors. -module.exports.copy.byDigest = copyByDigest +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports.hasContent = read.hasContent + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const http2_1 = __nccwpck_require__(85675); +const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310)); +const proc_log_1 = __nccwpck_require__(26687); +const promise_retry_1 = __importDefault(__nccwpck_require__(90390)); +const { HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants; +const fetchWithRetry = async (url, options = {}) => { + return (0, promise_retry_1.default)(async (retry, attemptNum) => { + /* eslint-disable @typescript-eslint/no-explicit-any */ + const logRetry = (reason) => { + proc_log_1.log.http('fetch', `${options.method} ${url} attempt ${attemptNum} failed with ${reason}`); + }; + const response = await (0, make_fetch_happen_1.default)(url, { + ...options, + retry: false, // We're handling retries ourselves + }).catch((reason) => { + logRetry(reason); + return retry(reason); + }); + if (retryable(response.status)) { + logRetry(response.status); + return retry(response); + } + return response; + }, retryOpts(options.retry)).catch((err) => { + // If we got an actual error, throw it + if (err instanceof Error) { + throw err; + } + // Otherwise, return the response (this is simply a retry-able response for + // which we exceeded the retry limit) + return err; + }); +}; +// Returns a wrapped fetch function with default options +fetchWithRetry.defaults = (defaultOptions = {}, wrappedFetch = fetchWithRetry) => { + const defaultedFetch = (url, options = {}) => { + const finalOptions = { + ...defaultOptions, + ...options, + headers: { ...defaultOptions.headers, ...options.headers }, + }; + return wrappedFetch(url, finalOptions); + }; + defaultedFetch.defaults = (newDefaults = {}) => fetchWithRetry.defaults(newDefaults, defaultedFetch); + return defaultedFetch; +}; +// Determine if a status code is retryable. This includes 5xx errors, 408, and +// 429. +const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR; +// Normalize the retry options to the format expected by promise-retry +const retryOpts = (retry) => { + if (typeof retry === 'boolean') { + return { retries: retry ? 1 : 0 }; + } + else if (typeof retry === 'number') { + return { retries: retry }; + } + else { + return { retries: 0, ...retry }; + } +}; +exports["default"] = fetchWithRetry; /***/ }), -/***/ 85742: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 19812: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _OCIImage_instances, _OCIImage_client, _OCIImage_credentials, _OCIImage_createReferrersIndexByTag; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OCIImage = void 0; +/* +Copyright 2023 The Sigstore Authors. -const get = __nccwpck_require__(19690) -const put = __nccwpck_require__(94283) -const rm = __nccwpck_require__(30793) -const verify = __nccwpck_require__(37621) -const { clearMemoized } = __nccwpck_require__(56068) -const tmp = __nccwpck_require__(63990) -const index = __nccwpck_require__(26575) - -module.exports.index = {} -module.exports.index.compact = index.compact -module.exports.index.insert = index.insert +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports.ls = index.ls -module.exports.ls.stream = index.lsStream + http://www.apache.org/licenses/LICENSE-2.0 -module.exports.get = get -module.exports.get.byDigest = get.byDigest -module.exports.get.stream = get.stream -module.exports.get.stream.byDigest = get.stream.byDigest -module.exports.get.copy = get.copy -module.exports.get.copy.byDigest = get.copy.byDigest -module.exports.get.info = get.info -module.exports.get.hasContent = get.hasContent +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const constants_1 = __nccwpck_require__(23688); +const error_1 = __nccwpck_require__(46803); +const registry_1 = __nccwpck_require__(22138); +const DOCKER_DEFAULT_REGISTRY = 'registry-1.docker.io'; +const EMPTY_BLOB = Buffer.from('{}'); +class OCIImage { + constructor(image, creds, opts) { + _OCIImage_instances.add(this); + _OCIImage_client.set(this, void 0); + _OCIImage_credentials.set(this, void 0); + __classPrivateFieldSet(this, _OCIImage_client, new registry_1.RegistryClient(canonicalizeRegistryName(image.registry), image.path, opts), "f"); + __classPrivateFieldSet(this, _OCIImage_credentials, creds, "f"); + } + async addArtifact(opts) { + let artifactDescriptor; + const annotations = { + 'org.opencontainers.image.created': new Date().toISOString(), + ...opts.annotations, + }; + try { + if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) { + await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f")); + } + // Check that the image exists + const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(opts.imageDigest); + // Upload the artifact blob + const artifactBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(opts.artifact); + // Upload the empty blob (needed for the manifest config) + const emptyBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(EMPTY_BLOB); + // Construct artifact manifest + const manifest = buildManifest({ + artifactDescriptor: { ...artifactBlob, mediaType: opts.mediaType }, + subjectDescriptor: imageDescriptor, + configDescriptor: { + ...emptyBlob, + mediaType: constants_1.CONTENT_TYPE_EMPTY_DESCRIPTOR, + }, + annotations, + }); + // Upload artifact manifest + artifactDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(manifest)); + // Check to see if registry supports the referrers API. For most + // registries the presence of a subjectDigest response header when + // uploading the artifact manifest indicates that the referrers API IS + // supported -- however, this is not a guarantee (AWS ECR does NOT support + // the referrers API but still reports a subjectDigest). + const referrersSupported = await __classPrivateFieldGet(this, _OCIImage_client, "f").pingReferrers(); + // Manually update the referrers list if the referrers API is not supported. + if (!artifactDescriptor.subjectDigest || !referrersSupported) { + // Strip subjectDigest from the artifact descriptor (in case it was returned) + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + const { subjectDigest, ...descriptor } = artifactDescriptor; + await __classPrivateFieldGet(this, _OCIImage_instances, "m", _OCIImage_createReferrersIndexByTag).call(this, { + artifact: { + ...descriptor, + artifactType: opts.mediaType, + annotations, + }, + imageDigest: opts.imageDigest, + }); + } + } + catch (err) { + throw new error_1.OCIError({ + message: `Error uploading artifact to container registry`, + cause: err, + }); + } + return artifactDescriptor; + } + async getDigest(tag) { + try { + if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) { + await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f")); + } + const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(tag); + return imageDescriptor.digest; + } + catch (err) { + throw new error_1.OCIError({ + message: `Error retrieving image digest from container registry`, + cause: err, + }); + } + } +} +exports.OCIImage = OCIImage; +_OCIImage_client = new WeakMap(), _OCIImage_credentials = new WeakMap(), _OCIImage_instances = new WeakSet(), _OCIImage_createReferrersIndexByTag = +// Create a referrers index by tag. This is a fallback for registries that do +// not support the referrers API. +// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests-with-subject +async function _OCIImage_createReferrersIndexByTag(opts) { + const referrerTag = digestToTag(opts.imageDigest); + let referrerManifest; + let etag; + try { + // Retrieve any existing referrer index + const referrerIndex = await __classPrivateFieldGet(this, _OCIImage_client, "f").getManifest(referrerTag); + if (referrerIndex.mediaType !== constants_1.CONTENT_TYPE_OCI_INDEX) { + throw new Error(`Expected referrer manifest type ${constants_1.CONTENT_TYPE_OCI_INDEX}, got ${referrerIndex.mediaType}`); + } + referrerManifest = referrerIndex.body; + etag = referrerIndex.etag; + } + catch (err) { + // If the referrer index does not exist, create a new one + if (err instanceof error_1.HTTPError && err.statusCode === 404) { + referrerManifest = newIndex(); + } + else { + throw err; + } + } + // If the artifact is not already in the index, add it to the list and + // re-upload the index + if (!referrerManifest.manifests.some((manifest) => manifest.digest === opts.artifact.digest)) { + // Add the artifact to the index + referrerManifest.manifests.push(opts.artifact); + await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(referrerManifest), { + mediaType: constants_1.CONTENT_TYPE_OCI_INDEX, + reference: referrerTag, + etag, + }); + } +}; +// Build an OCI manifest document with references to the given artifact, +// subject, and config +const buildManifest = (opts) => ({ + schemaVersion: 2, + mediaType: constants_1.CONTENT_TYPE_OCI_MANIFEST, + artifactType: opts.artifactDescriptor.mediaType, + config: opts.configDescriptor, + layers: [opts.artifactDescriptor], + subject: opts.subjectDescriptor, + annotations: opts.annotations, +}); +// Return an empty OCI index document +const newIndex = () => ({ + mediaType: constants_1.CONTENT_TYPE_OCI_INDEX, + schemaVersion: 2, + manifests: [], +}); +// Convert an image digest to a tag per the Referrers Tag Schema +// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#referrers-tag-schema +const digestToTag = (digest) => { + return digest.replace(':', '-'); +}; +// Canonicalize the registry name to match the format used by the registry +// client. This is used primarily to handle the special case of the Docker Hub +// registry. +// https://github.com/moby/moby/blob/v24.0.2/registry/config.go#L25-L48 +const canonicalizeRegistryName = (registry) => { + return registry.endsWith('docker.io') ? DOCKER_DEFAULT_REGISTRY : registry; +}; -module.exports.put = put -module.exports.put.stream = put.stream -module.exports.rm = rm.entry -module.exports.rm.all = rm.all -module.exports.rm.entry = module.exports.rm -module.exports.rm.content = rm.content +/***/ }), -module.exports.clearMemoized = clearMemoized +/***/ 81057: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports.tmp = {} -module.exports.tmp.mkdir = tmp.mkdir -module.exports.tmp.withTmp = tmp.withTmp +"use strict"; -module.exports.verify = verify -module.exports.verify.lastRun = verify.lastRun +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getImageDigest = exports.attachArtifactToImage = exports.OCIError = exports.getRegistryCredentials = void 0; +const image_1 = __nccwpck_require__(19812); +const name_1 = __nccwpck_require__(96666); +var credentials_1 = __nccwpck_require__(62691); +Object.defineProperty(exports, "getRegistryCredentials", ({ enumerable: true, get: function () { return credentials_1.getRegistryCredentials; } })); +var error_1 = __nccwpck_require__(46803); +Object.defineProperty(exports, "OCIError", ({ enumerable: true, get: function () { return error_1.OCIError; } })); +// Associates the given artifact with an OCI image. The artifact is identified +// by its media type and a buffer containing the artifact. The image is +// identified by its FQDN and digest. +const attachArtifactToImage = async (opts) => { + const image = (0, name_1.parseImageName)(opts.imageName); + return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).addArtifact(opts); +}; +exports.attachArtifactToImage = attachArtifactToImage; +// Returns the digest of the given image tag in the remote registry. +const getImageDigest = async (opts) => { + const image = (0, name_1.parseImageName)(opts.imageName); + return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).getDigest(opts.imageTag); +}; +exports.getImageDigest = getImageDigest; /***/ }), -/***/ 56068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 96666: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseImageName = void 0; +const expression = (...res) => res.join(''); +const group = (...res) => `(?:${expression(...res)})`; +const repeated = (...res) => `${group(expression(...res))}+`; +const optional = (...res) => `${group(expression(...res))}?`; +const capture = (...res) => `(${expression(...res)})`; +const anchored = (...res) => `^${expression(...res)}$`; +// Lower case letters, numbers +const ALPHA_NUMERIC_RE = '[a-z0-9]+'; +// Separators allowed to be embedded in name components. This allows one period, +// one or two underscore or multiple dashes. +const SEPARATOR_RE = group('\\.|_|__|-+'); +// Registry path component names to start with at least one letter or number, +// with following parts able to be separated by one period, one or two +// underscores or multiple dashes. +const NAME_COMPONENT_RE = expression(ALPHA_NUMERIC_RE, optional(repeated(SEPARATOR_RE, ALPHA_NUMERIC_RE))); +const NAME_RE = expression(NAME_COMPONENT_RE, repeated(optional('\\/', NAME_COMPONENT_RE))); +// Component of the registry domain must be at least one letter or number, with +// following parts able to be separated by a dash. +const DOMAIN_COMPONENT_RE = group('[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]'); +// Restricts the registry domain to be one or more period separated components +// followed by an optional port. +const DOMAIN_RE = expression(DOMAIN_COMPONENT_RE, optional(repeated('\\.', DOMAIN_COMPONENT_RE)), optional(':[0-9]+')); +// Capture the registry domain and path components of a repository name. +const ANCHORED_NAME_RE = anchored(capture(DOMAIN_RE), '\\/', capture(NAME_RE)); +// Parses a fully qualified image name into its registry and path components. +const parseImageName = (image) => { + const matches = image.match(ANCHORED_NAME_RE); + if (!matches) { + throw new Error(`Invalid image name: ${image}`); + } + return { + registry: matches[1], + path: matches[2], + }; +}; +exports.parseImageName = parseImageName; -const { LRUCache } = __nccwpck_require__(83193) -const MEMOIZED = new LRUCache({ - max: 500, - maxSize: 50 * 1024 * 1024, // 50MB - ttl: 3 * 60 * 1000, // 3 minutes - sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, -}) +/***/ }), -module.exports.clearMemoized = clearMemoized +/***/ 22138: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function clearMemoized () { - const old = {} - MEMOIZED.forEach((v, k) => { - old[k] = v - }) - MEMOIZED.clear() - return old -} +"use strict"; -module.exports.put = put +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _RegistryClient_instances, _RegistryClient_baseURL, _RegistryClient_repository, _RegistryClient_fetch, _RegistryClient_fetchDistributionToken, _RegistryClient_fetchOAuth2Token; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RegistryClient = exports.ZERO_DIGEST = void 0; +/* +Copyright 2023 The Sigstore Authors. -function put (cache, entry, data, opts) { - pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) - putDigest(cache, entry.integrity, data, opts) -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports.put.byDigest = putDigest + http://www.apache.org/licenses/LICENSE-2.0 -function putDigest (cache, integrity, data, opts) { - pickMem(opts).set(`digest:${cache}:${integrity}`, data) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const node_crypto_1 = __importDefault(__nccwpck_require__(77598)); +const constants_1 = __nccwpck_require__(23688); +const credentials_1 = __nccwpck_require__(62691); +const error_1 = __nccwpck_require__(46803); +const fetch_1 = __importDefault(__nccwpck_require__(32721)); +const ALL_MANIFEST_MEDIA_TYPES = [ + constants_1.CONTENT_TYPE_OCI_INDEX, + constants_1.CONTENT_TYPE_OCI_MANIFEST, + constants_1.CONTENT_TYPE_DOCKER_MANIFEST, + constants_1.CONTENT_TYPE_DOCKER_MANIFEST_LIST, +].join(','); +exports.ZERO_DIGEST = 'sha256:0000000000000000000000000000000000000000000000000000000000000000'; +class RegistryClient { + constructor(registry, repository, opts) { + _RegistryClient_instances.add(this); + _RegistryClient_baseURL.set(this, void 0); + _RegistryClient_repository.set(this, void 0); + _RegistryClient_fetch.set(this, void 0); + __classPrivateFieldSet(this, _RegistryClient_repository, repository, "f"); + __classPrivateFieldSet(this, _RegistryClient_fetch, fetch_1.default.defaults(opts), "f"); + // Use http for localhost registries, https otherwise + const hostname = new URL(`http://${registry}`).hostname; + /* istanbul ignore next */ + const protocol = hostname === 'localhost' || hostname === '127.0.0.1' ? 'http' : 'https'; + __classPrivateFieldSet(this, _RegistryClient_baseURL, `${protocol}://${registry}`, "f"); + } + // Authenticate with the registry. Sends an unauthenticated request to the + // registry in order to get an auth challenge. If the challenge scheme is + // "basic" we don't need a token and can authenticate requests using basic + // auth. Otherwise, we fetch a token from the auth server and use that to + // authenticate requests. + // https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md#the-registry + async signIn(creds) { + // Initiate a blob upload to get the auth challenge + const probeResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' }); + // If we get a 200 response, we're already authenticated + if (probeResponse.status === 200) { + return; + } + const authHeader = probeResponse.headers.get(constants_1.HEADER_AUTHENTICATE) || + /* istanbul ignore next */ ''; + const challenge = parseChallenge(authHeader); + // If the challenge scheme is "basic" we don't need a token and can + // authenticate requests using basic auth + if (challenge.scheme === 'basic') { + const basicAuth = (0, credentials_1.toBasicAuth)(creds); + __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({ + headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` }, + }), "f"); + return; + } + let token; + if (creds.username === '') { + // If the OAUth2 token request fails, try to fetch a distribution token + token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchOAuth2Token).call(this, creds, challenge).catch(() => undefined); + } + if (!token) { + token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchDistributionToken).call(this, creds, challenge); + } + // Ensure the token is sent with all future requests + __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({ + headers: { [constants_1.HEADER_AUTHORIZATION]: `Bearer ${token}` }, + }), "f"); + } + // Check the registry API version + async checkVersion() { + const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/`); + return response.headers.get(constants_1.HEADER_API_VERSION) || ''; + } + // Upload a blob to the registry using the post/put method. Calculates the + // digest of the blob and checks to make sure the blob doesn't already exist + // in the registry before uploading. + async uploadBlob(blob) { + const digest = RegistryClient.digest(blob); + const size = blob.length; + // Check if blob already exists + const headResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/${digest}`, { method: 'HEAD', redirect: 'follow' }); + if (headResponse.status === 200) { + return { + mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM, + digest, + size, + }; + } + // Retrieve upload location (session ID) + const postResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' }).then((0, error_1.ensureStatus)(202)); + const location = postResponse.headers.get(constants_1.HEADER_LOCATION); + if (!location) { + throw new Error('Missing location for blob upload'); + } + // Translate location to a full URL + const uploadLocation = new URL(location.startsWith('/') ? `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}${location}` : location); + // Add digest to query string + uploadLocation.searchParams.set('digest', digest); + // Upload blob + await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, uploadLocation.href, { + method: 'PUT', + body: blob, + headers: { [constants_1.HEADER_CONTENT_TYPE]: constants_1.CONTENT_TYPE_OCTET_STREAM }, + }).then((0, error_1.ensureStatus)(201)); + return { mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM, digest, size }; + } + // Checks for the existence of a manifest by reference + async checkManifest(reference) { + const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { + method: 'HEAD', + headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES }, + }).then((0, error_1.ensureStatus)(200)); + const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) || + /* istanbul ignore next */ ''; + const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ ''; + const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) || + /* istanbul ignore next */ 0; + return { mediaType, digest, size }; + } + // Retrieves a manifest by reference + async getManifest(reference) { + const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { + headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES }, + }).then((0, error_1.ensureStatus)(200)); + const body = await response.json(); + const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) || + /* istanbul ignore next */ ''; + const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ ''; + const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) || 0; + const etag = response.headers.get(constants_1.HEADER_ETAG) || undefined; + return { body, mediaType, digest, size, etag }; + } + // Uploads a manifest by digest. If specified, the reference will be used as + // the manifest tag. + async uploadManifest(manifest, options = {}) { + const digest = RegistryClient.digest(manifest); + const reference = options.reference || digest; + const contentType = options.mediaType || constants_1.CONTENT_TYPE_OCI_MANIFEST; + const headers = { [constants_1.HEADER_CONTENT_TYPE]: contentType }; + if (options.etag) { + headers[constants_1.HEADER_IF_MATCH] = options.etag; + } + const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { method: 'PUT', body: manifest, headers }).then((0, error_1.ensureStatus)(201)); + const subjectDigest = response.headers.get(constants_1.HEADER_OCI_SUBJECT) || undefined; + return { + mediaType: contentType, + digest, + size: manifest.length, + subjectDigest, + }; + } + // Returns true if the registry supports the referrers API + async pingReferrers() { + const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/referrers/${exports.ZERO_DIGEST}`); + return response.status === 200; + } + static digest(blob) { + const hash = node_crypto_1.default.createHash('sha256'); + hash.update(blob); + return `sha256:${hash.digest('hex')}`; + } } - -module.exports.get = get - -function get (cache, key, opts) { - return pickMem(opts).get(`key:${cache}:${key}`) +exports.RegistryClient = RegistryClient; +_RegistryClient_baseURL = new WeakMap(), _RegistryClient_repository = new WeakMap(), _RegistryClient_fetch = new WeakMap(), _RegistryClient_instances = new WeakSet(), _RegistryClient_fetchDistributionToken = async function _RegistryClient_fetchDistributionToken(creds, challenge) { + const basicAuth = (0, credentials_1.toBasicAuth)(creds); + const authURL = new URL(challenge.realm); + authURL.searchParams.set('service', challenge.service); + authURL.searchParams.set('scope', challenge.scope); + // Make token request with basic auth + const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, authURL.toString(), { + headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` }, + }).then((0, error_1.ensureStatus)(200)); + return tokenResponse.json().then((json) => json.access_token || json.token); +}, _RegistryClient_fetchOAuth2Token = async function _RegistryClient_fetchOAuth2Token(creds, challenge) { + const body = new URLSearchParams({ + service: challenge.service, + scope: challenge.scope, + username: creds.username, + password: creds.password, + grant_type: 'password', + }); + // Make OAuth token request + const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, challenge.realm, { + method: 'POST', + body, + }).then((0, error_1.ensureStatus)(200)); + return tokenResponse.json().then((json) => json.access_token); +}; +// Parses an auth challenge header into its components +// https://datatracker.ietf.org/doc/html/rfc7235#section-4.1 +function parseChallenge(challenge) { + // Account for the possibility of spaces in the auth params + const [scheme, ...rest] = challenge.split(' '); + const authParams = rest.join(' '); + if (!['Basic', 'Bearer'].includes(scheme)) { + throw new Error(`Invalid challenge: ${challenge}`); + } + return { + scheme: scheme.toLocaleLowerCase(), + realm: singleMatch(authParams, /realm="(.+?)"/), + service: singleMatch(authParams, /service="(.+?)"/), + scope: singleMatch(authParams, /scope="(.+?)"/), + }; } +// Returns the first capture group of a regex match, or an empty string +const singleMatch = (str, regex) => str.match(regex)?.[1] || ''; -module.exports.get.byDigest = getDigest -function getDigest (cache, integrity, opts) { - return pickMem(opts).get(`digest:${cache}:${integrity}`) -} +/***/ }), -class ObjProxy { - constructor (obj) { - this.obj = obj - } +/***/ 43049: +/***/ ((__unused_webpack_module, exports) => { - get (key) { - return this.obj[key] - } +"use strict"; - set (key, val) { - this.obj[key] = val - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseBundleBuilder = void 0; +// BaseBundleBuilder is a base class for BundleBuilder implementations. It +// provides a the basic wokflow for signing and witnessing an artifact. +// Subclasses must implement the `package` method to assemble a valid bundle +// with the generated signature and verification material. +class BaseBundleBuilder { + constructor(options) { + this.signer = options.signer; + this.witnesses = options.witnesses; + } + // Executes the signing/witnessing process for the given artifact. + async create(artifact) { + const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob)); + const bundle = await this.package(artifact, signature); + // Invoke all of the witnesses in parallel + const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key)))); + // Collect the verification material from all of the witnesses + const tlogEntryList = []; + const timestampList = []; + verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => { + tlogEntryList.push(...(tlogEntries ?? [])); + timestampList.push(...(rfc3161Timestamps ?? [])); + }); + // Merge the collected verification material into the bundle + bundle.verificationMaterial.tlogEntries = tlogEntryList; + bundle.verificationMaterial.timestampVerificationData = { + rfc3161Timestamps: timestampList, + }; + return bundle; + } + // Override this function to apply any pre-signing transformations to the + // artifact. The returned buffer will be signed by the signer. The default + // implementation simply returns the artifact data. + async prepare(artifact) { + return artifact.data; + } } - -function pickMem (opts) { - if (!opts || !opts.memoize) { - return MEMOIZED - } else if (opts.memoize.get && opts.memoize.set) { - return opts.memoize - } else if (typeof opts.memoize === 'object') { - return new ObjProxy(opts.memoize) - } else { - return MEMOIZED - } +exports.BaseBundleBuilder = BaseBundleBuilder; +// Extracts the public key from a KeyMaterial. Returns either the public key +// or the certificate, depending on the type of key material. +function publicKey(key) { + switch (key.$case) { + case 'publicKey': + return key.publicKey; + case 'x509Certificate': + return key.certificate; + } } /***/ }), -/***/ 94283: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 85192: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toMessageSignatureBundle = toMessageSignatureBundle; +exports.toDSSEBundle = toDSSEBundle; +/* +Copyright 2023 The Sigstore Authors. -const index = __nccwpck_require__(26575) -const memo = __nccwpck_require__(56068) -const write = __nccwpck_require__(93699) -const Flush = __nccwpck_require__(37633) -const { PassThrough } = __nccwpck_require__(11757) -const Pipeline = __nccwpck_require__(52899) - -const putOpts = (opts) => ({ - algorithms: ['sha512'], - ...opts, -}) - -module.exports = putData +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -async function putData (cache, key, data, opts = {}) { - const { memoize } = opts - opts = putOpts(opts) - const res = await write(cache, data, opts) - const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) - if (memoize) { - memo.put(cache, entry, data, opts) - } + http://www.apache.org/licenses/LICENSE-2.0 - return res.integrity +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const sigstore = __importStar(__nccwpck_require__(61040)); +const util_1 = __nccwpck_require__(19100); +// Helper functions for assembling the parts of a Sigstore bundle +// Message signature bundle - $case: 'messageSignature' +function toMessageSignatureBundle(artifact, signature) { + const digest = util_1.crypto.digest('sha256', artifact.data); + return sigstore.toMessageSignatureBundle({ + digest, + signature: signature.signature, + certificate: signature.key.$case === 'x509Certificate' + ? util_1.pem.toDER(signature.key.certificate) + : undefined, + keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, + certificateChain: true, + }); } - -module.exports.stream = putStream - -function putStream (cache, key, opts = {}) { - const { memoize } = opts - opts = putOpts(opts) - let integrity - let size - let error - - let memoData - const pipeline = new Pipeline() - // first item in the pipeline is the memoizer, because we need - // that to end first and get the collected data. - if (memoize) { - const memoizer = new PassThrough().on('collect', data => { - memoData = data - }) - pipeline.push(memoizer) - } - - // contentStream is a write-only, not a passthrough - // no data comes out of it. - const contentStream = write.stream(cache, opts) - .on('integrity', (int) => { - integrity = int - }) - .on('size', (s) => { - size = s - }) - .on('error', (err) => { - error = err - }) - - pipeline.push(contentStream) - - // last but not least, we write the index and emit hash and size, - // and memoize if we're doing that - pipeline.push(new Flush({ - async flush () { - if (!error) { - const entry = await index.insert(cache, key, integrity, { ...opts, size }) - if (memoize && memoData) { - memo.put(cache, entry, memoData, opts) - } - pipeline.emit('integrity', integrity) - pipeline.emit('size', size) - } - }, - })) - - return pipeline +// DSSE envelope bundle - $case: 'dsseEnvelope' +function toDSSEBundle(artifact, signature, certificateChain) { + return sigstore.toDSSEBundle({ + artifact: artifact.data, + artifactType: artifact.type, + signature: signature.signature, + certificate: signature.key.$case === 'x509Certificate' + ? util_1.pem.toDER(signature.key.certificate) + : undefined, + keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined, + certificateChain, + }); } /***/ }), -/***/ 30793: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 83997: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DSSEBundleBuilder = void 0; +/* +Copyright 2023 The Sigstore Authors. -const { rm } = __nccwpck_require__(91943) -const glob = __nccwpck_require__(6337) -const index = __nccwpck_require__(26575) -const memo = __nccwpck_require__(56068) -const path = __nccwpck_require__(16928) -const rmContent = __nccwpck_require__(92447) - -module.exports = entry -module.exports.entry = entry - -function entry (cache, key, opts) { - memo.clearMemoized() - return index.delete(cache, key, opts) -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports.content = content + http://www.apache.org/licenses/LICENSE-2.0 -function content (cache, integrity) { - memo.clearMemoized() - return rmContent(cache, integrity) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const util_1 = __nccwpck_require__(19100); +const base_1 = __nccwpck_require__(43049); +const bundle_1 = __nccwpck_require__(85192); +// BundleBuilder implementation for DSSE wrapped attestations +class DSSEBundleBuilder extends base_1.BaseBundleBuilder { + constructor(options) { + super(options); + this.certificateChain = options.certificateChain ?? false; + } + // DSSE requires the artifact to be pre-encoded with the payload type + // before the signature is generated. + async prepare(artifact) { + const a = artifactDefaults(artifact); + return util_1.dsse.preAuthEncoding(a.type, a.data); + } + // Packages the artifact and signature into a DSSE bundle + async package(artifact, signature) { + return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.certificateChain); + } } - -module.exports.all = all - -async function all (cache) { - memo.clearMemoized() - const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) - return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) +exports.DSSEBundleBuilder = DSSEBundleBuilder; +// Defaults the artifact type to an empty string if not provided +function artifactDefaults(artifact) { + return { + ...artifact, + type: artifact.type ?? '', + }; } /***/ }), -/***/ 6337: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 35530: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const { glob } = __nccwpck_require__(67471) -const path = __nccwpck_require__(16928) - -const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep) -module.exports = (path, options) => glob(globify(path), options) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; +var dsse_1 = __nccwpck_require__(83997); +Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } })); +var message_1 = __nccwpck_require__(8269); +Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } })); /***/ }), -/***/ 99704: -/***/ ((module) => { +/***/ 8269: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MessageSignatureBundleBuilder = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports = hashToSegments + http://www.apache.org/licenses/LICENSE-2.0 -function hashToSegments (hash) { - return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const base_1 = __nccwpck_require__(43049); +const bundle_1 = __nccwpck_require__(85192); +// BundleBuilder implementation for raw message signatures +class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder { + constructor(options) { + super(options); + } + async package(artifact, signature) { + return (0, bundle_1.toMessageSignatureBundle)(artifact, signature); + } } +exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder; /***/ }), -/***/ 63990: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97841: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +/* +Copyright 2023 The Sigstore Authors. -const { withTempDir } = __nccwpck_require__(88437) -const fs = __nccwpck_require__(91943) -const path = __nccwpck_require__(16928) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports.mkdir = mktmpdir + http://www.apache.org/licenses/LICENSE-2.0 -async function mktmpdir (cache, opts = {}) { - const { tmpPrefix } = opts - const tmpDir = path.join(cache, 'tmp') - await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) - // do not use path.join(), it drops the trailing / if tmpPrefix is unset - const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` - return fs.mkdtemp(target, { owner: 'inherit' }) +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InternalError = void 0; +exports.internalError = internalError; +const error_1 = __nccwpck_require__(40369); +class InternalError extends Error { + constructor({ code, message, cause, }) { + super(message); + this.name = this.constructor.name; + this.cause = cause; + this.code = code; + } } - -module.exports.withTmp = withTmp - -function withTmp (cache, opts, cb) { - if (!cb) { - cb = opts - opts = {} - } - return withTempDir(path.join(cache, 'tmp'), cb, opts) +exports.InternalError = InternalError; +function internalError(err, code, message) { + if (err instanceof error_1.HTTPError) { + message += ` - ${err.message}`; + } + throw new InternalError({ + code: code, + message: message, + cause: err, + }); } /***/ }), -/***/ 37621: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 40369: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +/* +Copyright 2023 The Sigstore Authors. -const { - mkdir, - readFile, - rm, - stat, - truncate, - writeFile, -} = __nccwpck_require__(91943) -const contentPath = __nccwpck_require__(40233) -const fsm = __nccwpck_require__(25032) -const glob = __nccwpck_require__(6337) -const index = __nccwpck_require__(26575) -const path = __nccwpck_require__(16928) -const ssri = __nccwpck_require__(68951) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -const hasOwnProperty = (obj, key) => - Object.prototype.hasOwnProperty.call(obj, key) + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HTTPError = void 0; +class HTTPError extends Error { + constructor({ status, message, location, }) { + super(`(${status}) ${message}`); + this.statusCode = status; + this.location = location; + } +} +exports.HTTPError = HTTPError; -const verifyOpts = (opts) => ({ - concurrency: 20, - log: { silly () {} }, - ...opts, -}) -module.exports = verify +/***/ }), -async function verify (cache, opts) { - opts = verifyOpts(opts) - opts.log.silly('verify', 'verifying cache at', cache) +/***/ 9823: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - const steps = [ - markStartTime, - fixPerms, - garbageCollect, - rebuildIndex, - cleanTmp, - writeVerifile, - markEndTime, - ] +"use strict"; - const stats = {} - for (const step of steps) { - const label = step.name - const start = new Date() - const s = await step(cache, opts) - if (s) { - Object.keys(s).forEach((k) => { - stats[k] = s[k] - }) - } - const end = new Date() - if (!stats.runTime) { - stats.runTime = {} - } - stats.runTime[label] = end - start - } - stats.runTime.total = stats.endTime - stats.startTime - opts.log.silly( - 'verify', - 'verification finished for', - cache, - 'in', - `${stats.runTime.total}ms` - ) - return stats -} +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fetchWithRetry = fetchWithRetry; +/* +Copyright 2023 The Sigstore Authors. -async function markStartTime () { - return { startTime: new Date() } -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -async function markEndTime () { - return { endTime: new Date() } -} + http://www.apache.org/licenses/LICENSE-2.0 -async function fixPerms (cache, opts) { - opts.log.silly('verify', 'fixing cache permissions') - await mkdir(cache, { recursive: true }) - return null +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const http2_1 = __nccwpck_require__(85675); +const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310)); +const proc_log_1 = __nccwpck_require__(26687); +const promise_retry_1 = __importDefault(__nccwpck_require__(90390)); +const util_1 = __nccwpck_require__(19100); +const error_1 = __nccwpck_require__(40369); +const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants; +async function fetchWithRetry(url, options) { + return (0, promise_retry_1.default)(async (retry, attemptNum) => { + const method = options.method || 'POST'; + const headers = { + [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(), + ...options.headers, + }; + const response = await (0, make_fetch_happen_1.default)(url, { + method, + headers, + body: options.body, + timeout: options.timeout, + retry: false, // We're handling retries ourselves + }).catch((reason) => { + proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`); + return retry(reason); + }); + if (response.ok) { + return response; + } + else { + const error = await errorFromResponse(response); + proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`); + if (retryable(response.status)) { + return retry(error); + } + else { + throw error; + } + } + }, retryOpts(options.retry)); } - -// Implements a naive mark-and-sweep tracing garbage collector. -// -// The algorithm is basically as follows: -// 1. Read (and filter) all index entries ("pointers") -// 2. Mark each integrity value as "live" -// 3. Read entire filesystem tree in `content-vX/` dir -// 4. If content is live, verify its checksum and delete it if it fails -// 5. If content is not marked as live, rm it. -// -async function garbageCollect (cache, opts) { - opts.log.silly('verify', 'garbage collecting content') - const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606)) - const indexStream = index.lsStream(cache) - const liveContent = new Set() - indexStream.on('data', (entry) => { - if (opts.filter && !opts.filter(entry)) { - return +// Translate a Response into an HTTPError instance. This will attempt to parse +// the response body for a message, but will default to the statusText if none +// is found. +const errorFromResponse = async (response) => { + let message = response.statusText; + const location = response.headers.get(HTTP2_HEADER_LOCATION) || undefined; + const contentType = response.headers.get(HTTP2_HEADER_CONTENT_TYPE); + // If response type is JSON, try to parse the body for a message + if (contentType?.includes('application/json')) { + try { + const body = await response.json(); + message = body.message || message; + } + catch (e) { + // ignore + } } - - // integrity is stringified, re-parse it so we can get each hash - const integrity = ssri.parse(entry.integrity) - for (const algo in integrity) { - liveContent.add(integrity[algo].toString()) + return new error_1.HTTPError({ + status: response.status, + message: message, + location: location, + }); +}; +// Determine if a status code is retryable. This includes 5xx errors, 408, and +// 429. +const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR; +// Normalize the retry options to the format expected by promise-retry +const retryOpts = (retry) => { + if (typeof retry === 'boolean') { + return { retries: retry ? 1 : 0 }; } - }) - await new Promise((resolve, reject) => { - indexStream.on('end', resolve).on('error', reject) - }) - const contentDir = contentPath.contentDir(cache) - const files = await glob(path.join(contentDir, '**'), { - follow: false, - nodir: true, - nosort: true, - }) - const stats = { - verifiedContent: 0, - reclaimedCount: 0, - reclaimedSize: 0, - badContentCount: 0, - keptSize: 0, - } - await pMap( - files, - async (f) => { - const split = f.split(/[/\\]/) - const digest = split.slice(split.length - 3).join('') - const algo = split[split.length - 4] - const integrity = ssri.fromHex(digest, algo) - if (liveContent.has(integrity.toString())) { - const info = await verifyContent(f, integrity) - if (!info.valid) { - stats.reclaimedCount++ - stats.badContentCount++ - stats.reclaimedSize += info.size - } else { - stats.verifiedContent++ - stats.keptSize += info.size - } - } else { - // No entries refer to this content. We can delete. - stats.reclaimedCount++ - const s = await stat(f) - await rm(f, { recursive: true, force: true }) - stats.reclaimedSize += s.size - } - return stats - }, - { concurrency: opts.concurrency } - ) - return stats -} - -async function verifyContent (filepath, sri) { - const contentInfo = {} - try { - const { size } = await stat(filepath) - contentInfo.size = size - contentInfo.valid = true - await ssri.checkStream(new fsm.ReadStream(filepath), sri) - } catch (err) { - if (err.code === 'ENOENT') { - return { size: 0, valid: false } + else if (typeof retry === 'number') { + return { retries: retry }; } - if (err.code !== 'EINTEGRITY') { - throw err + else { + return { retries: 0, ...retry }; } +}; - await rm(filepath, { recursive: true, force: true }) - contentInfo.valid = false - } - return contentInfo -} -async function rebuildIndex (cache, opts) { - opts.log.silly('verify', 'rebuilding index') - const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606)) - const entries = await index.ls(cache) - const stats = { - missingContent: 0, - rejectedEntries: 0, - totalEntries: 0, - } - const buckets = {} - for (const k in entries) { - /* istanbul ignore else */ - if (hasOwnProperty(entries, k)) { - const hashed = index.hashKey(k) - const entry = entries[k] - const excluded = opts.filter && !opts.filter(entry) - excluded && stats.rejectedEntries++ - if (buckets[hashed] && !excluded) { - buckets[hashed].push(entry) - } else if (buckets[hashed] && excluded) { - // skip - } else if (excluded) { - buckets[hashed] = [] - buckets[hashed]._path = index.bucketPath(cache, k) - } else { - buckets[hashed] = [entry] - buckets[hashed]._path = index.bucketPath(cache, k) - } - } - } - await pMap( - Object.keys(buckets), - (key) => { - return rebuildBucket(cache, buckets[key], stats, opts) - }, - { concurrency: opts.concurrency } - ) - return stats -} +/***/ }), -async function rebuildBucket (cache, bucket, stats) { - await truncate(bucket._path) - // This needs to be serialized because cacache explicitly - // lets very racy bucket conflicts clobber each other. - for (const entry of bucket) { - const content = contentPath(cache, entry.integrity) - try { - await stat(content) - await index.insert(cache, entry.key, entry.integrity, { - metadata: entry.metadata, - size: entry.size, - time: entry.time, - }) - stats.totalEntries++ - } catch (err) { - if (err.code === 'ENOENT') { - stats.rejectedEntries++ - stats.missingContent++ - } else { - throw err - } - } - } -} +/***/ 26819: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function cleanTmp (cache, opts) { - opts.log.silly('verify', 'cleaning tmp directory') - return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) -} +"use strict"; -async function writeVerifile (cache, opts) { - const verifile = path.join(cache, '_lastverified') - opts.log.silly('verify', 'writing verifile to ' + verifile) - return writeFile(verifile, `${Date.now()}`) -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Fulcio = void 0; +/* +Copyright 2023 The Sigstore Authors. -module.exports.lastRun = lastRun +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -async function lastRun (cache) { - const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) - return new Date(+data) + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fetch_1 = __nccwpck_require__(9823); +/** + * Fulcio API client. + */ +class Fulcio { + constructor(options) { + this.options = options; + } + async createSigningCertificate(request) { + const { baseURL, retry, timeout } = this.options; + const url = `${baseURL}/api/v2/signingCert`; + const response = await (0, fetch_1.fetchWithRetry)(url, { + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(request), + timeout, + retry, + }); + return response.json(); + } } +exports.Fulcio = Fulcio; /***/ }), -/***/ 45177: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 32688: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var balanced = __nccwpck_require__(59380); +"use strict"; -module.exports = expandTop; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Rekor = void 0; +/* +Copyright 2023 The Sigstore Authors. -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + http://www.apache.org/licenses/LICENSE-2.0 -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fetch_1 = __nccwpck_require__(9823); +/** + * Rekor API client. + */ +class Rekor { + constructor(options) { + this.options = options; + } + /** + * Create a new entry in the Rekor log. + * @param propsedEntry {ProposedEntry} Data to create a new entry + * @returns {Promise} The created entry + */ + async createEntry(propsedEntry) { + const { baseURL, timeout, retry } = this.options; + const url = `${baseURL}/api/v1/log/entries`; + const response = await (0, fetch_1.fetchWithRetry)(url, { + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify(propsedEntry), + timeout, + retry, + }); + const data = await response.json(); + return entryFromResponse(data); + } + /** + * Get an entry from the Rekor log. + * @param uuid {string} The UUID of the entry to retrieve + * @returns {Promise} The retrieved entry + */ + async getEntry(uuid) { + const { baseURL, timeout, retry } = this.options; + const url = `${baseURL}/api/v1/log/entries/${uuid}`; + const response = await (0, fetch_1.fetchWithRetry)(url, { + method: 'GET', + headers: { + Accept: 'application/json', + }, + timeout, + retry, + }); + const data = await response.json(); + return entryFromResponse(data); + } } - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +exports.Rekor = Rekor; +// Unpack the response from the Rekor API into a more convenient format. +function entryFromResponse(data) { + const entries = Object.entries(data); + if (entries.length != 1) { + throw new Error('Received multiple entries in Rekor response'); + } + // Grab UUID and entry data from the response + const [uuid, entry] = entries[0]; + return { + ...entry, + uuid, + }; } -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +/***/ }), - var parts = []; - var m = balanced('{', '}', str); +/***/ 78963: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!m) - return str.split(','); +"use strict"; - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TimestampAuthority = void 0; +/* +Copyright 2023 The Sigstore Authors. - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - parts.push.apply(parts, p); + http://www.apache.org/licenses/LICENSE-2.0 - return parts; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fetch_1 = __nccwpck_require__(9823); +class TimestampAuthority { + constructor(options) { + this.options = options; + } + async createTimestamp(request) { + const { baseURL, timeout, retry } = this.options; + const url = `${baseURL}/api/v1/timestamp`; + const response = await (0, fetch_1.fetchWithRetry)(url, { + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(request), + timeout, + retry, + }); + return response.buffer(); + } } +exports.TimestampAuthority = TimestampAuthority; -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - return expand(escapeBraces(str), true).map(unescapeBraces); -} +/***/ }), -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +/***/ 92092: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} +"use strict"; -function expand(str, isTop) { - var expansions = []; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CIContextProvider = void 0; +/* +Copyright 2023 The Sigstore Authors. - var m = balanced('{', '}', str); - if (!m) return [str]; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + http://www.apache.org/licenses/LICENSE-2.0 - if (/\$$/.test(m.pre)) { - for (var k = 0; k < post.length; k++) { - var expansion = pre+ '{' + m.body + '}' + post[k]; - expansions.push(expansion); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310)); +// Collection of all the CI-specific providers we have implemented +const providers = [getGHAToken, getEnv]; +/** + * CIContextProvider is a composite identity provider which will iterate + * over all of the CI-specific providers and return the token from the first + * one that resolves. + */ +class CIContextProvider { + /* istanbul ignore next */ + constructor(audience = 'sigstore') { + this.audience = audience; } - } else { - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; + // Invoke all registered ProviderFuncs and return the value of whichever one + // resolves first. + async getToken() { + return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available')); } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } +} +exports.CIContextProvider = CIContextProvider; +/** + * getGHAToken can retrieve an OIDC token when running in a GitHub Actions + * workflow + */ +async function getGHAToken(audience) { + // Check to see if we're running in GitHub Actions + if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || + !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { + return Promise.reject('no token available'); + } + // Construct URL to request token w/ appropriate audience + const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL); + url.searchParams.append('audience', audience); + const response = await (0, make_fetch_happen_1.default)(url.href, { + retry: 2, + headers: { + Accept: 'application/json', + Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, + }, + }); + return response.json().then((data) => data.value); +} +/** + * getEnv can retrieve an OIDC token from an environment variable. + * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar + */ +async function getEnv() { + if (!process.env.SIGSTORE_ID_TOKEN) { + return Promise.reject('no token available'); } + return process.env.SIGSTORE_ID_TOKEN; +} - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - var N; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); +/***/ }), - N = []; +/***/ 55022: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = []; +"use strict"; - for (var j = 0; j < n.length; j++) { - N.push.apply(N, expand(n[j], false)); - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CIContextProvider = void 0; +/* +Copyright 2023 The Sigstore Authors. - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - return expansions; -} + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var ci_1 = __nccwpck_require__(92092); +Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return ci_1.CIContextProvider; } })); /***/ }), -/***/ 97087: -/***/ ((module) => { +/***/ 15179: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; +"use strict"; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0; +var bundler_1 = __nccwpck_require__(35530); +Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } })); +Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } })); +var error_1 = __nccwpck_require__(97841); +Object.defineProperty(exports, "InternalError", ({ enumerable: true, get: function () { return error_1.InternalError; } })); +var identity_1 = __nccwpck_require__(55022); +Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return identity_1.CIContextProvider; } })); +var signer_1 = __nccwpck_require__(34342); +Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } })); +Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return signer_1.FulcioSigner; } })); +var witness_1 = __nccwpck_require__(55383); +Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } })); +Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return witness_1.RekorWitness; } })); +Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return witness_1.TSAWitness; } })); /***/ }), -/***/ 6110: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; +/***/ 5875: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); +"use strict"; -/** - * Colors. - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CAClient = void 0; +/* +Copyright 2023 The Sigstore Authors. -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ + http://www.apache.org/licenses/LICENSE-2.0 -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = __nccwpck_require__(97841); +const fulcio_1 = __nccwpck_require__(26819); +class CAClient { + constructor(options) { + this.fulcio = new fulcio_1.Fulcio({ + baseURL: options.fulcioBaseURL, + retry: options.retry, + timeout: options.timeout, + }); + } + async createSigningCertificate(identityToken, publicKey, challenge) { + const request = toCertificateRequest(identityToken, publicKey, challenge); + try { + const resp = await this.fulcio.createSigningCertificate(request); + // Account for the fact that the response may contain either a + // signedCertificateEmbeddedSct or a signedCertificateDetachedSct. + const cert = resp.signedCertificateEmbeddedSct + ? resp.signedCertificateEmbeddedSct + : resp.signedCertificateDetachedSct; + return cert.chain.certificates; + } + catch (err) { + (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate'); + } + } +} +exports.CAClient = CAClient; +function toCertificateRequest(identityToken, publicKey, challenge) { + return { + credentials: { + oidcIdentityToken: identityToken, + }, + publicKeyRequest: { + publicKey: { + algorithm: 'ECDSA', + content: publicKey, + }, + proofOfPossession: challenge.toString('base64'), + }, + }; +} - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +/***/ }), -/** - * Colorize log arguments if enabled. - * - * @api public - */ +/***/ 97064: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); +"use strict"; - if (!this.useColors) { - return; - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.EphemeralSigner = void 0; +/* +Copyright 2023 The Sigstore Authors. - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); + http://www.apache.org/licenses/LICENSE-2.0 - args.splice(lastC, 0, c); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const crypto_1 = __importDefault(__nccwpck_require__(76982)); +const EC_KEYPAIR_TYPE = 'ec'; +const P256_CURVE = 'P-256'; +// Signer implementation which uses an ephemeral keypair to sign artifacts. +// The private key lives only in memory and is tied to the lifetime of the +// EphemeralSigner instance. +class EphemeralSigner { + constructor() { + this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, { + namedCurve: P256_CURVE, + }); + } + async sign(data) { + const signature = crypto_1.default.sign(null, data, this.keypair.privateKey); + const publicKey = this.keypair.publicKey + .export({ format: 'pem', type: 'spki' }) + .toString('ascii'); + return { + signature: signature, + key: { $case: 'publicKey', publicKey }, + }; + } } +exports.EphemeralSigner = EphemeralSigner; -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +/***/ }), - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } +/***/ 26303: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return r; -} +"use strict"; -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; +/* +Copyright 2023 The Sigstore Authors. -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -module.exports = __nccwpck_require__(40897)(exports); + http://www.apache.org/licenses/LICENSE-2.0 -const {formatters} = module.exports; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = __nccwpck_require__(97841); +const util_1 = __nccwpck_require__(19100); +const ca_1 = __nccwpck_require__(5875); +const ephemeral_1 = __nccwpck_require__(97064); +exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev'; +// Signer implementation which can be used to decorate another signer +// with a Fulcio-issued signing certificate for the signer's public key. +// Must be instantiated with an identity provider which can provide a JWT +// which represents the identity to be bound to the signing certificate. +class FulcioSigner { + constructor(options) { + this.ca = new ca_1.CAClient({ + ...options, + fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL, + }); + this.identityProvider = options.identityProvider; + this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner(); + } + async sign(data) { + // Retrieve identity token from the supplied identity provider + const identityToken = await this.getIdentityToken(); + // Extract challenge claim from OIDC token + let subject; + try { + subject = util_1.oidc.extractJWTSubject(identityToken); + } + catch (err) { + throw new error_1.InternalError({ + code: 'IDENTITY_TOKEN_PARSE_ERROR', + message: `invalid identity token: ${identityToken}`, + cause: err, + }); + } + // Construct challenge value by signing the subject claim + const challenge = await this.keyHolder.sign(Buffer.from(subject)); + if (challenge.key.$case !== 'publicKey') { + throw new error_1.InternalError({ + code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', + message: 'unexpected format for signing key', + }); + } + // Create signing certificate + const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature); + // Generate artifact signature + const signature = await this.keyHolder.sign(data); + // Specifically returning only the first certificate in the chain + // as the key. + return { + signature: signature.signature, + key: { + $case: 'x509Certificate', + certificate: certificates[0], + }, + }; + } + async getIdentityToken() { + try { + return await this.identityProvider.getToken(); + } + catch (err) { + throw new error_1.InternalError({ + code: 'IDENTITY_TOKEN_READ_ERROR', + message: 'error retrieving identity token', + cause: err, + }); + } + } +} +exports.FulcioSigner = FulcioSigner; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; +/***/ }), +/***/ 34342: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), +"use strict"; -/***/ 40897: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/* istanbul ignore file */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0; +/* +Copyright 2023 The Sigstore Authors. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ + http://www.apache.org/licenses/LICENSE-2.0 -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(70744); - createDebug.destroy = destroy; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var fulcio_1 = __nccwpck_require__(26303); +Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } })); +Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return fulcio_1.FulcioSigner; } })); - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - /** - * The currently active debug mode names, and names to skip. - */ +/***/ }), - createDebug.names = []; - createDebug.skips = []; +/***/ 19100: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; +"use strict"; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0; +/* +Copyright 2023 The Sigstore Authors. - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + http://www.apache.org/licenses/LICENSE-2.0 - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var core_1 = __nccwpck_require__(83917); +Object.defineProperty(exports, "crypto", ({ enumerable: true, get: function () { return core_1.crypto; } })); +Object.defineProperty(exports, "dsse", ({ enumerable: true, get: function () { return core_1.dsse; } })); +Object.defineProperty(exports, "encoding", ({ enumerable: true, get: function () { return core_1.encoding; } })); +Object.defineProperty(exports, "json", ({ enumerable: true, get: function () { return core_1.json; } })); +Object.defineProperty(exports, "pem", ({ enumerable: true, get: function () { return core_1.pem; } })); +exports.oidc = __importStar(__nccwpck_require__(81963)); +exports.ua = __importStar(__nccwpck_require__(81268)); - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - const self = debug; +/***/ }), - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +/***/ 81963: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - args[0] = createDebug.coerce(args[0]); +"use strict"; - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.extractJWTSubject = extractJWTSubject; +/* +Copyright 2023 The Sigstore Authors. - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + http://www.apache.org/licenses/LICENSE-2.0 - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const core_1 = __nccwpck_require__(83917); +function extractJWTSubject(jwt) { + const parts = jwt.split('.', 3); + const payload = JSON.parse(core_1.encoding.base64Decode(parts[1])); + switch (payload.iss) { + case 'https://accounts.google.com': + case 'https://oauth2.sigstore.dev/auth': + return payload.email; + default: + return payload.sub; + } +} - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. +/***/ }), - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } +/***/ 81268: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); +"use strict"; - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getUserAgent = void 0; +/* +Copyright 2023 The Sigstore Authors. - return debug; - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } + http://www.apache.org/licenses/LICENSE-2.0 - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const os_1 = __importDefault(__nccwpck_require__(70857)); +// Format User-Agent: / () +// source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent +const getUserAgent = () => { + const packageVersion = (__nccwpck_require__(85896)/* .version */ .rE); + const nodeVersion = process.version; + const platformName = os_1.default.platform(); + const archName = os_1.default.arch(); + return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`; +}; +exports.getUserAgent = getUserAgent; - createDebug.names = []; - createDebug.skips = []; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +/***/ }), - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +/***/ 55383: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - namespaces = split[i].replace(/\*/g, '.*?'); +"use strict"; - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } +/* istanbul ignore file */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; +/* +Copyright 2023 The Sigstore Authors. - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + http://www.apache.org/licenses/LICENSE-2.0 - let i; - let len; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var tlog_1 = __nccwpck_require__(2566); +Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } })); +Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return tlog_1.RekorWitness; } })); +var tsa_1 = __nccwpck_require__(66936); +Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return tsa_1.TSAWitness; } })); - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +/***/ }), - return false; - } +/***/ 42815: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } +"use strict"; - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TLogClient = void 0; +/* +Copyright 2023 The Sigstore Authors. - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at - createDebug.enable(createDebug.load()); + http://www.apache.org/licenses/LICENSE-2.0 - return createDebug; +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = __nccwpck_require__(97841); +const error_2 = __nccwpck_require__(40369); +const rekor_1 = __nccwpck_require__(32688); +class TLogClient { + constructor(options) { + this.fetchOnConflict = options.fetchOnConflict ?? false; + this.rekor = new rekor_1.Rekor({ + baseURL: options.rekorBaseURL, + retry: options.retry, + timeout: options.timeout, + }); + } + async createEntry(proposedEntry) { + let entry; + try { + entry = await this.rekor.createEntry(proposedEntry); + } + catch (err) { + // If the entry already exists, fetch it (if enabled) + if (entryExistsError(err) && this.fetchOnConflict) { + // Grab the UUID of the existing entry from the location header + /* istanbul ignore next */ + const uuid = err.location.split('/').pop() || ''; + try { + entry = await this.rekor.getEntry(uuid); + } + catch (err) { + (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry'); + } + } + else { + (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry'); + } + } + return entry; + } +} +exports.TLogClient = TLogClient; +function entryExistsError(value) { + return (value instanceof error_2.HTTPError && + value.statusCode === 409 && + value.location !== undefined); } - -module.exports = setup; /***/ }), -/***/ 2830: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 97890: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ +"use strict"; -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(6110); -} else { - module.exports = __nccwpck_require__(95108); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toProposedEntry = toProposedEntry; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const bundle_1 = __nccwpck_require__(61040); +const util_1 = __nccwpck_require__(19100); +const SHA256_ALGORITHM = 'sha256'; +function toProposedEntry(content, publicKey, +// TODO: Remove this parameter once have completely switched to 'dsse' entries +entryType = 'dsse') { + switch (content.$case) { + case 'dsseEnvelope': + // TODO: Remove this conditional once have completely ditched "intoto" entries + if (entryType === 'intoto') { + return toProposedIntotoEntry(content.dsseEnvelope, publicKey); + } + return toProposedDSSEEntry(content.dsseEnvelope, publicKey); + case 'messageSignature': + return toProposedHashedRekordEntry(content.messageSignature, publicKey); + } +} +// Returns a properly formatted Rekor "hashedrekord" entry for the given digest +// and signature +function toProposedHashedRekordEntry(messageSignature, publicKey) { + const hexDigest = messageSignature.messageDigest.digest.toString('hex'); + const b64Signature = messageSignature.signature.toString('base64'); + const b64Key = util_1.encoding.base64Encode(publicKey); + return { + apiVersion: '0.0.1', + kind: 'hashedrekord', + spec: { + data: { + hash: { + algorithm: SHA256_ALGORITHM, + value: hexDigest, + }, + }, + signature: { + content: b64Signature, + publicKey: { + content: b64Key, + }, + }, + }, + }; +} +// Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope +// and signature +function toProposedDSSEEntry(envelope, publicKey) { + const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope)); + const encodedKey = util_1.encoding.base64Encode(publicKey); + return { + apiVersion: '0.0.1', + kind: 'dsse', + spec: { + proposedContent: { + envelope: envelopeJSON, + verifiers: [encodedKey], + }, + }, + }; +} +// Returns a properly formatted Rekor "intoto" entry for the given DSSE +// envelope and signature +function toProposedIntotoEntry(envelope, publicKey) { + // Calculate the value for the payloadHash field in the Rekor entry + const payloadHash = util_1.crypto + .digest(SHA256_ALGORITHM, envelope.payload) + .toString('hex'); + // Calculate the value for the hash field in the Rekor entry + const envelopeHash = calculateDSSEHash(envelope, publicKey); + // Collect values for re-creating the DSSE envelope. + // Double-encode payload and signature cause that's what Rekor expects + const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64')); + const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64')); + const keyid = envelope.signatures[0].keyid; + const encodedKey = util_1.encoding.base64Encode(publicKey); + // Create the envelope portion of the entry. Note the inclusion of the + // publicKey in the signature struct is not a standard part of a DSSE + // envelope, but is required by Rekor. + const dsse = { + payloadType: envelope.payloadType, + payload: payload, + signatures: [{ sig, publicKey: encodedKey }], + }; + // If the keyid is an empty string, Rekor seems to remove it altogether. We + // need to do the same here so that we can properly recreate the entry for + // verification. + if (keyid.length > 0) { + dsse.signatures[0].keyid = keyid; + } + return { + apiVersion: '0.0.2', + kind: 'intoto', + spec: { + content: { + envelope: dsse, + hash: { algorithm: SHA256_ALGORITHM, value: envelopeHash }, + payloadHash: { algorithm: SHA256_ALGORITHM, value: payloadHash }, + }, + }, + }; +} +// Calculates the hash of a DSSE envelope for inclusion in a Rekor entry. +// There is no standard way to do this, so the scheme we're using as as +// follows: +// * payload is base64 encoded +// * signature is base64 encoded (only the first signature is used) +// * keyid is included ONLY if it is NOT an empty string +// * The resulting JSON is canonicalized and hashed to a hex string +function calculateDSSEHash(envelope, publicKey) { + const dsse = { + payloadType: envelope.payloadType, + payload: envelope.payload.toString('base64'), + signatures: [ + { sig: envelope.signatures[0].sig.toString('base64'), publicKey }, + ], + }; + // If the keyid is an empty string, Rekor seems to remove it altogether. + if (envelope.signatures[0].keyid.length > 0) { + dsse.signatures[0].keyid = envelope.signatures[0].keyid; + } + return util_1.crypto + .digest(SHA256_ALGORITHM, util_1.json.canonicalize(dsse)) + .toString('hex'); } /***/ }), -/***/ 95108: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 2566: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Module dependencies. - */ +"use strict"; -const tty = __nccwpck_require__(52018); -const util = __nccwpck_require__(39023); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0; +/* +Copyright 2023 The Sigstore Authors. -/** - * This is the Node.js implementation of `debug()`. - */ +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); + http://www.apache.org/licenses/LICENSE-2.0 -/** - * Colors. - */ +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const util_1 = __nccwpck_require__(19100); +const client_1 = __nccwpck_require__(42815); +const entry_1 = __nccwpck_require__(97890); +exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev'; +class RekorWitness { + constructor(options) { + this.entryType = options.entryType; + this.tlog = new client_1.TLogClient({ + ...options, + rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL, + }); + } + async testify(content, publicKey) { + const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType); + const entry = await this.tlog.createEntry(proposedEntry); + return toTransparencyLogEntry(entry); + } +} +exports.RekorWitness = RekorWitness; +function toTransparencyLogEntry(entry) { + const logID = Buffer.from(entry.logID, 'hex'); + // Parse entry body so we can extract the kind and version. + const bodyJSON = util_1.encoding.base64Decode(entry.body); + const entryBody = JSON.parse(bodyJSON); + const promise = entry?.verification?.signedEntryTimestamp + ? inclusionPromise(entry.verification.signedEntryTimestamp) + : undefined; + const proof = entry?.verification?.inclusionProof + ? inclusionProof(entry.verification.inclusionProof) + : undefined; + const tlogEntry = { + logIndex: entry.logIndex.toString(), + logId: { + keyId: logID, + }, + integratedTime: entry.integratedTime.toString(), + kindVersion: { + kind: entryBody.kind, + version: entryBody.apiVersion, + }, + inclusionPromise: promise, + inclusionProof: proof, + canonicalizedBody: Buffer.from(entry.body, 'base64'), + }; + return { + tlogEntries: [tlogEntry], + }; +} +function inclusionPromise(promise) { + return { + signedEntryTimestamp: Buffer.from(promise, 'base64'), + }; +} +function inclusionProof(proof) { + return { + logIndex: proof.logIndex.toString(), + treeSize: proof.treeSize.toString(), + rootHash: Buffer.from(proof.rootHash, 'hex'), + hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')), + checkpoint: { + envelope: proof.checkpoint, + }, + }; +} -exports.colors = [6, 2, 3, 4, 5, 1]; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(21450); +/***/ }), - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. +/***/ 97409: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TSAClient = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = __nccwpck_require__(97841); +const tsa_1 = __nccwpck_require__(78963); +const util_1 = __nccwpck_require__(19100); +const SHA256_ALGORITHM = 'sha256'; +class TSAClient { + constructor(options) { + this.tsa = new tsa_1.TimestampAuthority({ + baseURL: options.tsaBaseURL, + retry: options.retry, + timeout: options.timeout, + }); + } + async createTimestamp(signature) { + const request = { + artifactHash: util_1.crypto + .digest(SHA256_ALGORITHM, signature) + .toString('base64'), + hashAlgorithm: SHA256_ALGORITHM, + }; + try { + return await this.tsa.createTimestamp(request); + } + catch (err) { + (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp'); + } + } } +exports.TSAClient = TSAClient; -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +/***/ }), + +/***/ 66936: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TSAWitness = void 0; +/* +Copyright 2023 The Sigstore Authors. - obj[prop] = val; - return obj; -}, {}); +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + http://www.apache.org/licenses/LICENSE-2.0 -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const client_1 = __nccwpck_require__(97409); +class TSAWitness { + constructor(options) { + this.tsa = new client_1.TSAClient({ + tsaBaseURL: options.tsaBaseURL, + retry: options.retry, + timeout: options.timeout, + }); + } + async testify(content) { + const signature = extractSignature(content); + const timestamp = await this.tsa.createTimestamp(signature); + return { + rfc3161Timestamps: [{ signedTimestamp: timestamp }], + }; + } +} +exports.TSAWitness = TSAWitness; +function extractSignature(content) { + switch (content.$case) { + case 'dsseEnvelope': + return content.dsseEnvelope.signatures[0].sig; + case 'messageSignature': + return content.messageSignature.signature; + } } -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ -function formatArgs(args) { - const {namespace: name, useColors} = this; +/***/ }), - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; +/***/ 15183: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} +"use strict"; -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.req = exports.json = exports.toBuffer = void 0; +const http = __importStar(__nccwpck_require__(58611)); +const https = __importStar(__nccwpck_require__(65692)); +async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +} +exports.toBuffer = toBuffer; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function json(stream) { + const buf = await toBuffer(stream); + const str = buf.toString('utf8'); + try { + return JSON.parse(str); + } + catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } +} +exports.json = json; +function req(url, opts = {}) { + const href = typeof url === 'string' ? url : url.href; + const req = (href.startsWith('https:') ? https : http).request(url, opts); + const promise = new Promise((resolve, reject) => { + req + .once('response', resolve) + .once('error', reject) + .end(); + }); + req.then = promise.then.bind(promise); + return req; } +exports.req = req; +//# sourceMappingURL=helpers.js.map -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ +/***/ }), -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} +/***/ 98894: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Agent = void 0; +const net = __importStar(__nccwpck_require__(69278)); +const http = __importStar(__nccwpck_require__(58611)); +const https_1 = __nccwpck_require__(65692); +__exportStar(__nccwpck_require__(15183), exports); +const INTERNAL = Symbol('AgentBaseInternalState'); +class Agent extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + /** + * Determine whether this is an `http` or `https` request. + */ + isSecureEndpoint(options) { + if (options) { + // First check the `secureEndpoint` property explicitly, since this + // means that a parent `Agent` is "passing through" to this instance. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof options.secureEndpoint === 'boolean') { + return options.secureEndpoint; + } + // If no explicit `secure` endpoint, check if `protocol` property is + // set. This will usually be the case since using a full string URL + // or `URL` instance should be the most common usage. + if (typeof options.protocol === 'string') { + return options.protocol === 'https:'; + } + } + // Finally, if no `protocol` property was set, then fall back to + // checking the stack trace of the current call stack, and try to + // detect the "https" module. + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack + .split('\n') + .some((l) => l.indexOf('(https.js:') !== -1 || + l.indexOf('node:https:') !== -1); + } + // In order to support async signatures in `connect()` and Node's native + // connection pooling in `http.Agent`, the array of sockets for each origin + // has to be updated synchronously. This is so the length of the array is + // accurate when `addRequest()` is next called. We achieve this by creating a + // fake socket and adding it to `sockets[origin]` and incrementing + // `totalSocketCount`. + incrementSockets(name) { + // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no + // need to create a fake socket because Node.js native connection pooling + // will never be invoked. + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + // All instances of `sockets` are expected TypeScript errors. The + // alternative is to add it as a private property of this class but that + // will break TypeScript subclassing. + if (!this.sockets[name]) { + // @ts-expect-error `sockets` is readonly in `@types/node` + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index = sockets.indexOf(socket); + if (index !== -1) { + sockets.splice(index, 1); + // @ts-expect-error `totalSocketCount` isn't defined in `@types/node` + this.totalSocketCount--; + if (sockets.length === 0) { + // @ts-expect-error `sockets` is readonly in `@types/node` + delete this.sockets[name]; + } + } + } + // In order to properly update the socket pool, we need to call `getName()` on + // the core `https.Agent` if it is a secureEndpoint. + getName(options) { + const secureEndpoint = typeof options.secureEndpoint === 'boolean' + ? options.secureEndpoint + : this.isSecureEndpoint(options); + if (secureEndpoint) { + // @ts-expect-error `getName()` isn't defined in `@types/node` + return https_1.Agent.prototype.getName.call(this, options); + } + // @ts-expect-error `getName()` isn't defined in `@types/node` + return super.getName(options); + } + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options), + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve() + .then(() => this.connect(req, connectOpts)) + .then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + return socket.addRequest(req, connectOpts); + } + this[INTERNAL].currentSocket = socket; + // @ts-expect-error `createSocket()` isn't defined in `@types/node` + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error('No socket was returned in the `connect()` function'); + } + return socket; + } + get defaultPort() { + return (this[INTERNAL].defaultPort ?? + (this.protocol === 'https:' ? 443 : 80)); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; + } + } + get protocol() { + return (this[INTERNAL].protocol ?? + (this.isSecureEndpoint() ? 'https:' : 'http:')); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } + } } +exports.Agent = Agent; +//# sourceMappingURL=index.js.map -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +/***/ }), -function load() { - return process.env.DEBUG; -} +/***/ 59380: +/***/ ((module) => { -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +"use strict"; -function init(debug) { - debug.inspectOpts = {}; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; } -module.exports = __nccwpck_require__(40897)(exports); +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} -const {formatters} = module.exports; +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ + bi = str.indexOf(b, i + 1); + } -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} /***/ }), -/***/ 14150: -/***/ ((__unused_webpack_module, exports) => { +/***/ 52732: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var register = __nccwpck_require__(11063); +var addHook = __nccwpck_require__(22027); +var removeHook = __nccwpck_require__(59934); +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); -Object.defineProperty(exports, "__esModule", ({ value: true })); +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} - /* istanbul ignore next */ +function HookCollection() { + var state = { + registry: {}, + }; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + var hook = register.bind(null, state); + bindApi(hook, state); - this.name = 'Deprecation'; + return hook; +} + +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; } - + return HookCollection(); } -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 24056: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); -var iconvLite = __nccwpck_require__(31748); +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; -// Expose to the world -module.exports.C = convert; -/** - * Convert encoding of an UTF-8 string or a buffer - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convert(str, to, from) { - from = checkEncoding(from || 'UTF-8'); - to = checkEncoding(to || 'UTF-8'); - str = str || ''; +/***/ }), - var result; +/***/ 22027: +/***/ ((module) => { - if (from !== 'UTF-8' && typeof str === 'string') { - str = Buffer.from(str, 'binary'); - } +module.exports = addHook; - if (from === to) { - if (typeof str === 'string') { - result = Buffer.from(str); - } else { - result = str; - } - } else { - try { - result = convertIconvLite(str, to, from); - } catch (E) { - console.error(E); - result = str; - } - } +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - if (typeof result === 'string') { - result = Buffer.from(result, 'utf-8'); - } + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } - return result; -} + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } -/** - * Convert encoding of astring with iconv-lite - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convertIconvLite(str, to, from) { - if (to === 'UTF-8') { - return iconvLite.decode(str, from); - } else if (from === 'UTF-8') { - return iconvLite.encode(str, to); - } else { - return iconvLite.encode(iconvLite.decode(str, from), to); - } -} + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } -/** - * Converts charset name if needed - * - * @param {String} name Character set - * @return {String} Character set name - */ -function checkEncoding(name) { - return (name || '') - .toString() - .trim() - .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') - .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') - .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') - .replace(/^ks_c_5601\-1987$/i, 'CP949') - .replace(/^us[\-_]?ascii$/i, 'ASCII') - .toUpperCase(); + state.registry[name].push({ + hook: hook, + orig: orig, + }); } /***/ }), -/***/ 14339: +/***/ 11063: /***/ ((module) => { -"use strict"; +module.exports = register; +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } -function assign(obj, props) { - for (const key in props) { - Object.defineProperty(obj, key, { - value: props[key], - enumerable: true, - configurable: true, - }); + if (!options) { + options = {}; + } + + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - return obj; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); } -function createError(err, code, props) { - if (!err || typeof err === 'string') { - throw new TypeError('Please pass an Error to err-code'); - } - if (!props) { - props = {}; - } +/***/ }), - if (typeof code === 'object') { - props = code; - code = undefined; - } +/***/ 59934: +/***/ ((module) => { - if (code != null) { - props.code = code; - } +module.exports = removeHook; - try { - return assign(err, props); - } catch (_) { - props.message = err.message; - props.stack = err.stack; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } - const ErrClass = function () {}; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - ErrClass.prototype = Object.create(Object.getPrototypeOf(err)); + if (index === -1) { + return; + } - return assign(new ErrClass(), props); - } + state.registry[name].splice(index, 1); } -module.exports = createError; - /***/ }), -/***/ 25032: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 63251: +/***/ (function(module) { -"use strict"; +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; -const { Minipass } = __nccwpck_require__(78275) -const EE = (__nccwpck_require__(24434).EventEmitter) -const fs = __nccwpck_require__(79896) + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; -const writev = fs.writev + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } -const _autoClose = Symbol('_autoClose') -const _close = Symbol('_close') -const _ended = Symbol('_ended') -const _fd = Symbol('_fd') -const _finished = Symbol('_finished') -const _flags = Symbol('_flags') -const _flush = Symbol('_flush') -const _handleChunk = Symbol('_handleChunk') -const _makeBuf = Symbol('_makeBuf') -const _mode = Symbol('_mode') -const _needDrain = Symbol('_needDrain') -const _onerror = Symbol('_onerror') -const _onopen = Symbol('_onopen') -const _onread = Symbol('_onread') -const _onwrite = Symbol('_onwrite') -const _open = Symbol('_open') -const _path = Symbol('_path') -const _pos = Symbol('_pos') -const _queue = Symbol('_queue') -const _read = Symbol('_read') -const _readSize = Symbol('_readSize') -const _reading = Symbol('_reading') -const _remain = Symbol('_remain') -const _size = Symbol('_size') -const _write = Symbol('_write') -const _writing = Symbol('_writing') -const _defaultFlag = Symbol('_defaultFlag') -const _errored = Symbol('_errored') + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; -class ReadStream extends Minipass { - constructor (path, opt) { - opt = opt || {} - super(opt) + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; - this.readable = true - this.writable = false + var parser = { + load: load, + overwrite: overwrite + }; - if (typeof path !== 'string') { - throw new TypeError('path must be a string') - } + var DLList; - this[_errored] = false - this[_fd] = typeof opt.fd === 'number' ? opt.fd : null - this[_path] = path - this[_readSize] = opt.readSize || 16 * 1024 * 1024 - this[_reading] = false - this[_size] = typeof opt.size === 'number' ? opt.size : Infinity - this[_remain] = this[_size] - this[_autoClose] = typeof opt.autoClose === 'boolean' ? - opt.autoClose : true + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } - if (typeof this[_fd] === 'number') { - this[_read]() - } else { - this[_open]() - } - } + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } - get fd () { - return this[_fd] - } + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } - get path () { - return this[_path] - } + first() { + if (this._first != null) { + return this._first.value; + } + } - write () { - throw new TypeError('this is a readable stream') - } + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - end () { - throw new TypeError('this is a readable stream') - } + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } - [_open] () { - fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) - } + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } - [_onopen] (er, fd) { - if (er) { - this[_onerror](er) - } else { - this[_fd] = fd - this.emit('open', fd) - this[_read]() - } - } + }; - [_makeBuf] () { - return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) - } + var DLList_1 = DLList; - [_read] () { - if (!this[_reading]) { - this[_reading] = true - const buf = this[_makeBuf]() - /* istanbul ignore if */ - if (buf.length === 0) { - return process.nextTick(() => this[_onread](null, 0, buf)) - } - fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => - this[_onread](er, br, b)) - } - } + var Events; - [_onread] (er, br, buf) { - this[_reading] = false - if (er) { - this[_onerror](er) - } else if (this[_handleChunk](br, buf)) { - this[_read]() - } - } + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) - } - } + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } - [_onerror] (er) { - this[_reading] = true - this[_close]() - this.emit('error', er) - } + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } + + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } - [_handleChunk] (br, buf) { - let ret = false - // no effect if infinite - this[_remain] -= br - if (br > 0) { - ret = super.write(br < buf.length ? buf.slice(0, br) : buf) - } + }; - if (br === 0 || this[_remain] <= 0) { - ret = false - this[_close]() - super.end() - } + var Events_1 = Events; - return ret - } + var DLList$1, Events$1, Queues; - emit (ev, data) { - switch (ev) { - case 'prefinish': - case 'finish': - break + DLList$1 = DLList_1; - case 'drain': - if (typeof this[_fd] === 'number') { - this[_read]() - } - break + Events$1 = Events_1; - case 'error': - if (this[_errored]) { - return - } - this[_errored] = true - return super.emit(ev, data) + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } - default: - return super.emit(ev, data) - } - } -} + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } -class ReadStreamSync extends ReadStream { - [_open] () { - let threw = true - try { - this[_onopen](null, fs.openSync(this[_path], 'r')) - threw = false - } finally { - if (threw) { - this[_close]() - } - } - } + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - [_read] () { - let threw = true - try { - if (!this[_reading]) { - this[_reading] = true - do { - const buf = this[_makeBuf]() - /* istanbul ignore next */ - const br = buf.length === 0 ? 0 - : fs.readSync(this[_fd], buf, 0, buf.length, null) - if (!this[_handleChunk](br, buf)) { - break - } - } while (true) - this[_reading] = false - } - threw = false - } finally { - if (threw) { - this[_close]() - } - } - } + push(job) { + return this._lists[job.options.priority].push(job); + } - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } - } -} + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } -class WriteStream extends EE { - constructor (path, opt) { - opt = opt || {} - super(opt) - this.readable = false - this.writable = true - this[_errored] = false - this[_writing] = false - this[_ended] = false - this[_needDrain] = false - this[_queue] = [] - this[_path] = path - this[_fd] = typeof opt.fd === 'number' ? opt.fd : null - this[_mode] = opt.mode === undefined ? 0o666 : opt.mode - this[_pos] = typeof opt.start === 'number' ? opt.start : null - this[_autoClose] = typeof opt.autoClose === 'boolean' ? - opt.autoClose : true + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } - // truncating makes no sense when writing into the middle - const defaultFlag = this[_pos] !== null ? 'r+' : 'w' - this[_defaultFlag] = opt.flags === undefined - this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } - if (this[_fd] === null) { - this[_open]() - } - } + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } - emit (ev, data) { - if (ev === 'error') { - if (this[_errored]) { - return - } - this[_errored] = true - } - return super.emit(ev, data) - } + }; - get fd () { - return this[_fd] - } + var Queues_1 = Queues; - get path () { - return this[_path] - } + var BottleneckError; - [_onerror] (er) { - this[_close]() - this[_writing] = true - this.emit('error', er) - } + BottleneckError = class BottleneckError extends Error {}; - [_open] () { - fs.open(this[_path], this[_flags], this[_mode], - (er, fd) => this[_onopen](er, fd)) - } + var BottleneckError_1 = BottleneckError; - [_onopen] (er, fd) { - if (this[_defaultFlag] && - this[_flags] === 'r+' && - er && er.code === 'ENOENT') { - this[_flags] = 'w' - this[_open]() - } else if (er) { - this[_onerror](er) - } else { - this[_fd] = fd - this.emit('open', fd) - if (!this[_writing]) { - this[_flush]() - } - } - } + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - end (buf, enc) { - if (buf) { - this.write(buf, enc) - } + NUM_PRIORITIES = 10; - this[_ended] = true + DEFAULT_PRIORITY = 5; - // synthetic after-write logic, where drain/finish live - if (!this[_writing] && !this[_queue].length && - typeof this[_fd] === 'number') { - this[_onwrite](null, 0) - } - return this - } + parser$1 = parser; - write (buf, enc) { - if (typeof buf === 'string') { - buf = Buffer.from(buf, enc) - } + BottleneckError$1 = BottleneckError_1; - if (this[_ended]) { - this.emit('error', new Error('write() after end()')) - return false - } + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } - if (this[_fd] === null || this[_writing] || this[_queue].length) { - this[_queue].push(buf) - this[_needDrain] = true - return false - } + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } - this[_writing] = true - this[_write](buf) - return true - } + _randomIndex() { + return Math.random().toString(36).slice(2); + } - [_write] (buf) { - fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => - this[_onwrite](er, bw)) - } + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } - [_onwrite] (er, bw) { - if (er) { - this[_onerror](er) - } else { - if (this[_pos] !== null) { - this[_pos] += bw - } - if (this[_queue].length) { - this[_flush]() - } else { - this[_writing] = false + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } - if (this[_ended] && !this[_finished]) { - this[_finished] = true - this[_close]() - this.emit('finish') - } else if (this[_needDrain]) { - this[_needDrain] = false - this.emit('drain') - } - } - } - } + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } - [_flush] () { - if (this[_queue].length === 0) { - if (this[_ended]) { - this[_onwrite](null, 0) - } - } else if (this[_queue].length === 1) { - this[_write](this[_queue].pop()) - } else { - const iovec = this[_queue] - this[_queue] = [] - writev(this[_fd], iovec, this[_pos], - (er, bw) => this[_onwrite](er, bw)) - } - } + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) - } - } -} + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } -class WriteStreamSync extends WriteStream { - [_open] () { - let fd - // only wrap in a try{} block if we know we'll retry, to avoid - // the rethrow obscuring the error's source frame in most cases. - if (this[_defaultFlag] && this[_flags] === 'r+') { - try { - fd = fs.openSync(this[_path], this[_flags], this[_mode]) - } catch (er) { - if (er.code === 'ENOENT') { - this[_flags] = 'w' - return this[_open]() - } else { - throw er - } - } - } else { - fd = fs.openSync(this[_path], this[_flags], this[_mode]) - } + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } - this[_onopen](null, fd) - } + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } - [_close] () { - if (this[_autoClose] && typeof this[_fd] === 'number') { - const fd = this[_fd] - this[_fd] = null - fs.closeSync(fd) - this.emit('close') - } - } + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } - [_write] (buf) { - // throw the original, but try to close if it fails - let threw = true - try { - this[_onwrite](null, - fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) - threw = false - } finally { - if (threw) { - try { - this[_close]() - } catch { - // ok error - } - } - } - } -} + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } -exports.ReadStream = ReadStream -exports.ReadStreamSync = ReadStreamSync + }; -exports.WriteStream = WriteStream -exports.WriteStreamSync = WriteStreamSync + var Job_1 = Job; + var BottleneckError$2, LocalDatastore, parser$2; -/***/ }), + parser$2 = parser; -/***/ 83813: -/***/ ((module) => { + BottleneckError$2 = BottleneckError_1; -"use strict"; + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } -/***/ }), + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } -/***/ 12203: -/***/ ((module) => { + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } -"use strict"; + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } -// rfc7231 6.1 -const statusCodeCacheableByDefault = new Set([ - 200, - 203, - 204, - 206, - 300, - 301, - 308, - 404, - 405, - 410, - 414, - 501, -]); + async __running__() { + await this.yieldLoop(); + return this._running; + } -// This implementation does not understand partial responses (206) -const understoodStatuses = new Set([ - 200, - 203, - 204, - 300, - 301, - 302, - 303, - 307, - 308, - 404, - 405, - 410, - 414, - 501, -]); + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -const errorStatusCodes = new Set([ - 500, - 502, - 503, - 504, -]); + async __done__() { + await this.yieldLoop(); + return this._done; + } -const hopByHopHeaders = { - date: true, // included, because we add Age update Date - connection: true, - 'keep-alive': true, - 'proxy-authenticate': true, - 'proxy-authorization': true, - te: true, - trailer: true, - 'transfer-encoding': true, - upgrade: true, -}; + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } -const excludedFromRevalidationUpdate = { - // Since the old body is reused, it doesn't make sense to change properties of the body - 'content-length': true, - 'content-encoding': true, - 'transfer-encoding': true, - 'content-range': true, -}; + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } -function toNumberOrZero(s) { - const n = parseInt(s, 10); - return isFinite(n) ? n : 0; -} + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -// RFC 5861 -function isErrorResponse(response) { - // consider undefined response as faulty - if(!response) { - return true - } - return errorStatusCodes.has(response.status); -} + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } -function parseCacheControl(header) { - const cc = {}; - if (!header) return cc; + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } - // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), - // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale - const parts = header.trim().split(/,/); - for (const part of parts) { - const [k, v] = part.split(/=/, 2); - cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); - } + isBlocked(now) { + return this._unblockTime >= now; + } - return cc; -} + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } -function formatCacheControl(cc) { - let parts = []; - for (const k in cc) { - const v = cc[k]; - parts.push(v === true ? k : k + '=' + v); - } - if (!parts.length) { - return undefined; - } - return parts.join(', '); -} + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } -module.exports = class CachePolicy { - constructor( - req, - res, - { - shared, - cacheHeuristic, - immutableMinTimeToLive, - ignoreCargoCult, - _fromObject, - } = {} - ) { - if (_fromObject) { - this._fromObject(_fromObject); - return; - } + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } - if (!res || !res.headers) { - throw Error('Response headers missing'); - } - this._assertRequestHasHeaders(req); + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } - this._responseTime = this.now(); - this._isShared = shared !== false; - this._cacheHeuristic = - undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE - this._immutableMinTtl = - undefined !== immutableMinTimeToLive - ? immutableMinTimeToLive - : 24 * 3600 * 1000; + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } - this._status = 'status' in res ? res.status : 200; - this._resHeaders = res.headers; - this._rescc = parseCacheControl(res.headers['cache-control']); - this._method = 'method' in req ? req.method : 'GET'; - this._url = req.url; - this._host = req.headers.host; - this._noAuthorization = !req.headers.authorization; - this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used - this._reqcc = parseCacheControl(req.headers['cache-control']); + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } - // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, - // so there's no point stricly adhering to the blindly copy&pasted directives. - if ( - ignoreCargoCult && - 'pre-check' in this._rescc && - 'post-check' in this._rescc - ) { - delete this._rescc['pre-check']; - delete this._rescc['post-check']; - delete this._rescc['no-cache']; - delete this._rescc['no-store']; - delete this._rescc['must-revalidate']; - this._resHeaders = Object.assign({}, this._resHeaders, { - 'cache-control': formatCacheControl(this._rescc), - }); - delete this._resHeaders.expires; - delete this._resHeaders.pragma; - } + }; - // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive - // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). - if ( - res.headers['cache-control'] == null && - /no-cache/.test(res.headers.pragma) - ) { - this._rescc['no-cache'] = true; - } - } + var LocalDatastore_1 = LocalDatastore; - now() { - return Date.now(); - } + var BottleneckError$3, States; - storable() { - // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. - return !!( - !this._reqcc['no-store'] && - // A cache MUST NOT store a response to any request, unless: - // The request method is understood by the cache and defined as being cacheable, and - ('GET' === this._method || - 'HEAD' === this._method || - ('POST' === this._method && this._hasExplicitExpiration())) && - // the response status code is understood by the cache, and - understoodStatuses.has(this._status) && - // the "no-store" cache directive does not appear in request or response header fields, and - !this._rescc['no-store'] && - // the "private" response directive does not appear in the response, if the cache is shared, and - (!this._isShared || !this._rescc.private) && - // the Authorization header field does not appear in the request, if the cache is shared, - (!this._isShared || - this._noAuthorization || - this._allowsStoringAuthenticated()) && - // the response either: - // contains an Expires header field, or - (this._resHeaders.expires || - // contains a max-age response directive, or - // contains a s-maxage response directive and the cache is shared, or - // contains a public response directive. - this._rescc['max-age'] || - (this._isShared && this._rescc['s-maxage']) || - this._rescc.public || - // has a status code that is defined as cacheable by default - statusCodeCacheableByDefault.has(this._status)) - ); - } + BottleneckError$3 = BottleneckError_1; - _hasExplicitExpiration() { - // 4.2.1 Calculating Freshness Lifetime - return ( - (this._isShared && this._rescc['s-maxage']) || - this._rescc['max-age'] || - this._resHeaders.expires - ); - } + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } - _assertRequestHasHeaders(req) { - if (!req || !req.headers) { - throw Error('Request headers missing'); - } - } + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } - satisfiesWithoutRevalidation(req) { - this._assertRequestHasHeaders(req); + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } - // When presented with a request, a cache MUST NOT reuse a stored response, unless: - // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, - // unless the stored response is successfully validated (Section 4.3), and - const requestCC = parseCacheControl(req.headers['cache-control']); - if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { - return false; - } + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } - if (requestCC['max-age'] && this.age() > requestCC['max-age']) { - return false; - } + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } - if ( - requestCC['min-fresh'] && - this.timeToLive() < 1000 * requestCC['min-fresh'] - ) { - return false; - } + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } - // the stored response is either: - // fresh, or allowed to be served stale - if (this.stale()) { - const allowsStale = - requestCC['max-stale'] && - !this._rescc['must-revalidate'] && - (true === requestCC['max-stale'] || - requestCC['max-stale'] > this.age() - this.maxAge()); - if (!allowsStale) { - return false; - } - } + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } - return this._requestMatches(req, false); - } + }; - _requestMatches(req, allowHeadMethod) { - // The presented effective request URI and that of the stored response match, and - return ( - (!this._url || this._url === req.url) && - this._host === req.headers.host && - // the request method associated with the stored response allows it to be used for the presented request, and - (!req.method || - this._method === req.method || - (allowHeadMethod && 'HEAD' === req.method)) && - // selecting header fields nominated by the stored response (if any) match those presented, and - this._varyMatches(req) - ); - } + var States_1 = States; - _allowsStoringAuthenticated() { - // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. - return ( - this._rescc['must-revalidate'] || - this._rescc.public || - this._rescc['s-maxage'] - ); - } + var DLList$2, Sync; - _varyMatches(req) { - if (!this._resHeaders.vary) { - return true; - } + DLList$2 = DLList_1; - // A Vary header field-value of "*" always fails to match - if (this._resHeaders.vary === '*') { - return false; - } + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } - const fields = this._resHeaders.vary - .trim() - .toLowerCase() - .split(/\s*,\s*/); - for (const name of fields) { - if (req.headers[name] !== this._reqHeaders[name]) return false; - } - return true; - } + isEmpty() { + return this._queue.length === 0; + } - _copyWithoutHopByHopHeaders(inHeaders) { - const headers = {}; - for (const name in inHeaders) { - if (hopByHopHeaders[name]) continue; - headers[name] = inHeaders[name]; - } - // 9.1. Connection - if (inHeaders.connection) { - const tokens = inHeaders.connection.trim().split(/\s*,\s*/); - for (const name of tokens) { - delete headers[name]; - } - } - if (headers.warning) { - const warnings = headers.warning.split(/,/).filter(warning => { - return !/^\s*1[0-9][0-9]/.test(warning); - }); - if (!warnings.length) { - delete headers.warning; - } else { - headers.warning = warnings.join(',').trim(); - } - } - return headers; - } + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } - responseHeaders() { - const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); - const age = this.age(); + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } - // A cache SHOULD generate 113 warning if it heuristically chose a freshness - // lifetime greater than 24 hours and the response's age is greater than 24 hours. - if ( - age > 3600 * 24 && - !this._hasExplicitExpiration() && - this.maxAge() > 3600 * 24 - ) { - headers.warning = - (headers.warning ? `${headers.warning}, ` : '') + - '113 - "rfc7234 5.5.4"'; - } - headers.age = `${Math.round(age)}`; - headers.date = new Date(this.now()).toUTCString(); - return headers; - } + }; - /** - * Value of the Date response header or current time if Date was invalid - * @return timestamp - */ - date() { - const serverDate = Date.parse(this._resHeaders.date); - if (isFinite(serverDate)) { - return serverDate; - } - return this._responseTime; - } + var Sync_1 = Sync; - /** - * Value of the Age header, in seconds, updated for the current time. - * May be fractional. - * - * @return Number - */ - age() { - let age = this._ageValue(); + var version = "2.19.5"; + var version$1 = { + version: version + }; - const residentTime = (this.now() - this._responseTime) / 1000; - return age + residentTime; - } + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); - _ageValue() { - return toNumberOrZero(this._resHeaders.age); - } + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - /** - * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. - * - * For an up-to-date value, see `timeToLive()`. - * - * @return Number - */ - maxAge() { - if (!this.storable() || this._rescc['no-cache']) { - return 0; - } + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default - // so this implementation requires explicit opt-in via public header - if ( - this._isShared && - (this._resHeaders['set-cookie'] && - !this._rescc.public && - !this._rescc.immutable) - ) { - return 0; - } + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - if (this._resHeaders.vary === '*') { - return 0; - } + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; - if (this._isShared) { - if (this._rescc['proxy-revalidate']) { - return 0; - } - // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. - if (this._rescc['s-maxage']) { - return toNumberOrZero(this._rescc['s-maxage']); - } - } + parser$3 = parser; - // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. - if (this._rescc['max-age']) { - return toNumberOrZero(this._rescc['max-age']); - } + Events$2 = Events_1; - const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + RedisConnection$1 = require$$2; - const serverDate = this.date(); - if (this._resHeaders.expires) { - const expires = Date.parse(this._resHeaders.expires); - // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). - if (Number.isNaN(expires) || expires < serverDate) { - return 0; - } - return Math.max(defaultMinTtl, (expires - serverDate) / 1000); - } + IORedisConnection$1 = require$$3; - if (this._resHeaders['last-modified']) { - const lastModified = Date.parse(this._resHeaders['last-modified']); - if (isFinite(lastModified) && serverDate > lastModified) { - return Math.max( - defaultMinTtl, - ((serverDate - lastModified) / 1000) * this._cacheHeuristic - ); - } - } + Scripts$1 = require$$4; - return defaultMinTtl; - } + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } - timeToLive() { - const age = this.maxAge() - this.age(); - const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); - const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); - return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; - } + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } - stale() { - return this.maxAge() <= this.age(); - } + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } - _useStaleIfError() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); - } + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } - useStaleWhileRevalidate() { - return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); - } + keys() { + return Object.keys(this.instances); + } - static fromObject(obj) { - return new this(undefined, undefined, { _fromObject: obj }); - } + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } - _fromObject(obj) { - if (this._responseTime) throw Error('Reinitialized'); - if (!obj || obj.v !== 1) throw Error('Invalid serialization'); + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } - this._responseTime = obj.t; - this._isShared = obj.sh; - this._cacheHeuristic = obj.ch; - this._immutableMinTtl = - obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; - this._status = obj.st; - this._resHeaders = obj.resh; - this._rescc = obj.rescc; - this._method = obj.m; - this._url = obj.u; - this._host = obj.h; - this._noAuthorization = obj.a; - this._reqHeaders = obj.reqh; - this._reqcc = obj.reqcc; - } + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - toObject() { - return { - v: 1, - t: this._responseTime, - sh: this._isShared, - ch: this._cacheHeuristic, - imm: this._immutableMinTtl, - st: this._status, - resh: this._resHeaders, - rescc: this._rescc, - m: this._method, - u: this._url, - h: this._host, - a: this._noAuthorization, - reqh: this._reqHeaders, - reqcc: this._reqcc, - }; - } + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } - /** - * Headers for sending to the origin server to revalidate stale response. - * Allows server to return 304 to allow reuse of the previous response. - * - * Hop by hop headers are always stripped. - * Revalidation headers may be added or removed, depending on request. - */ - revalidationHeaders(incomingReq) { - this._assertRequestHasHeaders(incomingReq); - const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; - // This implementation does not understand range requests - delete headers['if-range']; + return Group; - if (!this._requestMatches(incomingReq, true) || !this.storable()) { - // revalidation allowed via HEAD - // not for the same resource, or wasn't allowed to be cached anyway - delete headers['if-none-match']; - delete headers['if-modified-since']; - return headers; - } + }).call(commonjsGlobal); - /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ - if (this._resHeaders.etag) { - headers['if-none-match'] = headers['if-none-match'] - ? `${headers['if-none-match']}, ${this._resHeaders.etag}` - : this._resHeaders.etag; - } + var Group_1 = Group; - // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. - const forbidsWeakValidators = - headers['accept-ranges'] || - headers['if-match'] || - headers['if-unmodified-since'] || - (this._method && this._method != 'GET'); + var Batcher, Events$3, parser$4; - /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. - Note: This implementation does not understand partial responses (206) */ - if (forbidsWeakValidators) { - delete headers['if-modified-since']; + parser$4 = parser; - if (headers['if-none-match']) { - const etags = headers['if-none-match'] - .split(/,/) - .filter(etag => { - return !/^\s*W\//.test(etag); - }); - if (!etags.length) { - delete headers['if-none-match']; - } else { - headers['if-none-match'] = etags.join(',').trim(); - } - } - } else if ( - this._resHeaders['last-modified'] && - !headers['if-modified-since'] - ) { - headers['if-modified-since'] = this._resHeaders['last-modified']; - } + Events$3 = Events_1; - return headers; - } + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } - /** - * Creates new CachePolicy with information combined from the previews response, - * and the new revalidation response. - * - * Returns {policy, modified} where modified is a boolean indicating - * whether the response body has been modified, and old cached body can't be used. - * - * @return {Object} {policy: CachePolicy, modified: Boolean} - */ - revalidatedPolicy(request, response) { - this._assertRequestHasHeaders(request); - if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful - return { - modified: false, - matches: false, - policy: this, - }; - } - if (!response || !response.headers) { - throw Error('Response headers missing'); - } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - // These aren't going to be supported exactly, since one CachePolicy object - // doesn't know about all the other cached objects. - let matches = false; - if (response.status !== undefined && response.status != 304) { - matches = false; - } else if ( - response.headers.etag && - !/^\s*W\//.test(response.headers.etag) - ) { - // "All of the stored responses with the same strong validator are selected. - // If none of the stored responses contain the same strong validator, - // then the cache MUST NOT use the new response to update any stored responses." - matches = - this._resHeaders.etag && - this._resHeaders.etag.replace(/^\s*W\//, '') === - response.headers.etag; - } else if (this._resHeaders.etag && response.headers.etag) { - // "If the new response contains a weak validator and that validator corresponds - // to one of the cache's stored responses, - // then the most recent of those matching stored responses is selected for update." - matches = - this._resHeaders.etag.replace(/^\s*W\//, '') === - response.headers.etag.replace(/^\s*W\//, ''); - } else if (this._resHeaders['last-modified']) { - matches = - this._resHeaders['last-modified'] === - response.headers['last-modified']; - } else { - // If the new response does not include any form of validator (such as in the case where - // a client generates an If-Modified-Since request from a source other than the Last-Modified - // response header field), and there is only one stored response, and that stored response also - // lacks a validator, then that stored response is selected for update. - if ( - !this._resHeaders.etag && - !this._resHeaders['last-modified'] && - !response.headers.etag && - !response.headers['last-modified'] - ) { - matches = true; - } - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - if (!matches) { - return { - policy: new this.constructor(request, response), - // Client receiving 304 without body, even if it's invalid/mismatched has no option - // but to reuse a cached body. We don't have a good way to tell clients to do - // error recovery in such case. - modified: response.status != 304, - matches: false, - }; - } + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } - // use other header fields provided in the 304 (Not Modified) response to replace all instances - // of the corresponding header fields in the stored response. - const headers = {}; - for (const k in this._resHeaders) { - headers[k] = - k in response.headers && !excludedFromRevalidationUpdate[k] - ? response.headers[k] - : this._resHeaders[k]; - } + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; - const newResponse = Object.assign({}, response, { - status: this._status, - method: this._method, - headers, - }); - return { - policy: new this.constructor(request, newResponse, { - shared: this._isShared, - cacheHeuristic: this._cacheHeuristic, - immutableMinTimeToLive: this._immutableMinTtl, - }), - modified: false, - matches: true, - }; - } -}; + return Batcher; + }).call(commonjsGlobal); -/***/ }), + var Batcher_1 = Batcher; -/***/ 81970: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -"use strict"; + var require$$8 = getCjsExportFromNamespace(version$2); -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpProxyAgent = void 0; -const net = __importStar(__nccwpck_require__(69278)); -const tls = __importStar(__nccwpck_require__(64756)); -const debug_1 = __importDefault(__nccwpck_require__(2830)); -const events_1 = __nccwpck_require__(24434); -const agent_base_1 = __nccwpck_require__(98894); -const url_1 = __nccwpck_require__(87016); -const debug = (0, debug_1.default)('http-proxy-agent'); -/** - * The `HttpProxyAgent` implements an HTTP Agent subclass that connects - * to the specified "HTTP proxy server" in order to proxy HTTP requests. - */ -class HttpProxyAgent extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); - // Trim off the brackets from IPv6 addresses - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); - const port = this.proxy.port - ? parseInt(this.proxy.port, 10) - : this.proxy.protocol === 'https:' - ? 443 - : 80; - this.connectOpts = { - ...(opts ? omit(opts, 'headers') : null), - host, - port, - }; - } - addRequest(req, opts) { - req._header = null; - this.setRequestProps(req, opts); - // @ts-expect-error `addRequest()` isn't defined in `@types/node` - super.addRequest(req, opts); - } - setRequestProps(req, opts) { - const { proxy } = this; - const protocol = opts.secureEndpoint ? 'https:' : 'http:'; - const hostname = req.getHeader('host') || 'localhost'; - const base = `${protocol}//${hostname}`; - const url = new url_1.URL(req.path, base); - if (opts.port !== 80) { - url.port = String(opts.port); - } - // Change the `http.ClientRequest` instance's "path" field - // to the absolute path of the URL that will be requested. - req.path = String(url); - // Inject the `Proxy-Authorization` header if necessary. - const headers = typeof this.proxyHeaders === 'function' - ? this.proxyHeaders() - : { ...this.proxyHeaders }; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; - } - if (!headers['Proxy-Connection']) { - headers['Proxy-Connection'] = this.keepAlive - ? 'Keep-Alive' - : 'close'; - } - for (const name of Object.keys(headers)) { - const value = headers[name]; - if (value) { - req.setHeader(name, value); - } - } - } - async connect(req, opts) { - req._header = null; - if (!req.path.includes('://')) { - this.setRequestProps(req, opts); - } - // At this point, the http ClientRequest's internal `_header` field - // might have already been set. If this is the case then we'll need - // to re-generate the string since we just changed the `req.path`. - let first; - let endOfHeaders; - debug('Regenerating stored HTTP header string for request'); - req._implicitHeader(); - if (req.outputData && req.outputData.length > 0) { - debug('Patching connection write() output buffer with updated header'); - first = req.outputData[0].data; - endOfHeaders = first.indexOf('\r\n\r\n') + 4; - req.outputData[0].data = - req._header + first.substring(endOfHeaders); - debug('Output buffer: %o', req.outputData[0].data); - } - // Create a socket connection to the proxy server. - let socket; - if (this.proxy.protocol === 'https:') { - debug('Creating `tls.Socket`: %o', this.connectOpts); - socket = tls.connect(this.connectOpts); - } - else { - debug('Creating `net.Socket`: %o', this.connectOpts); - socket = net.connect(this.connectOpts); - } - // Wait for the socket's `connect` event, so that this `callback()` - // function throws instead of the `http` request machinery. This is - // important for i.e. `PacProxyAgent` which determines a failed proxy - // connection via the `callback()` function throwing. - await (0, events_1.once)(socket, 'connect'); - return socket; - } -} -HttpProxyAgent.protocols = ['http', 'https']; -exports.HttpProxyAgent = HttpProxyAgent; -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=index.js.map + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; -/***/ }), + NUM_PRIORITIES$1 = 10; -/***/ 3669: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + DEFAULT_PRIORITY$1 = 5; -"use strict"; + parser$5 = parser; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpsProxyAgent = void 0; -const net = __importStar(__nccwpck_require__(69278)); -const tls = __importStar(__nccwpck_require__(64756)); -const assert_1 = __importDefault(__nccwpck_require__(42613)); -const debug_1 = __importDefault(__nccwpck_require__(2830)); -const agent_base_1 = __nccwpck_require__(98894); -const url_1 = __nccwpck_require__(87016); -const parse_proxy_response_1 = __nccwpck_require__(37943); -const debug = (0, debug_1.default)('https-proxy-agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: undefined }; - this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); - // Trim off the brackets from IPv6 addresses - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); - const port = this.proxy.port - ? parseInt(this.proxy.port, 10) - : this.proxy.protocol === 'https:' - ? 443 - : 80; - this.connectOpts = { - // Attempt to negotiate http/1.1 for proxy servers that support http/2 - ALPNProtocols: ['http/1.1'], - ...(opts ? omit(opts, 'headers') : null), - host, - port, - }; - } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - */ - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); - } - // Create a socket connection to the proxy server. - let socket; - if (proxy.protocol === 'https:') { - debug('Creating `tls.Socket`: %o', this.connectOpts); - const servername = this.connectOpts.servername || this.connectOpts.host; - socket = tls.connect({ - ...this.connectOpts, - servername, - }); - } - else { - debug('Creating `net.Socket`: %o', this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === 'function' - ? this.proxyHeaders() - : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers['Proxy-Connection']) { - headers['Proxy-Connection'] = this.keepAlive - ? 'Keep-Alive' - : 'close'; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r\n`); - const { connect, buffered } = await proxyResponsePromise; - req.emit('proxyConnect', connect); - this.emit('proxyConnect', connect, req); - if (connect.statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - const servername = opts.servername || opts.host; - return tls.connect({ - ...omit(opts, 'host', 'path', 'port'), - socket, - servername, - }); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('Replaying proxy buffer for failed request'); - (0, assert_1.default)(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - } -} -HttpsProxyAgent.protocols = ['http', 'https']; -exports.HttpsProxyAgent = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; - } - } - return ret; -} -//# sourceMappingURL=index.js.map + Queues$1 = Queues_1; -/***/ }), + Job$1 = Job_1; -/***/ 37943: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + LocalDatastore$1 = LocalDatastore_1; -"use strict"; + RedisDatastore$1 = require$$4$1; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseProxyResponse = void 0; -const debug_1 = __importDefault(__nccwpck_require__(2830)); -const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('readable', read); - } - function onend() { - cleanup(); - debug('onend'); - reject(new Error('Proxy connection ended before receiving CONNECT response')); - } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const headerParts = buffered - .slice(0, endOfHeaders) - .toString('ascii') - .split('\r\n'); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error('No header received from proxy CONNECT response')); - } - const firstLineParts = firstLine.split(' '); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(' '); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(':'); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === 'string') { - headers[key] = [current, value]; - } - else if (Array.isArray(current)) { - current.push(value); - } - else { - headers[key] = value; - } - } - debug('got proxy server response: %o %o', firstLine, headers); - cleanup(); - resolve({ - connect: { - statusCode, - statusText, - headers, - }, - buffered, - }); - } - socket.on('error', onerror); - socket.on('end', onend); - read(); - }); -} -exports.parseProxyResponse = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map + Events$4 = Events_1; + + States$1 = States_1; -/***/ }), + Sync$1 = Sync_1; -/***/ 7978: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } -"use strict"; + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } -var Buffer = (__nccwpck_require__(12803).Buffer); + ready() { + return this._store.ready; + } -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. + clients() { + return this._store.clients; + } -exports._dbcs = DBCSCodec; + channel() { + return `b_${this.id}`; + } -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; + publish(message) { + return this._store.__publish__(message); + } + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); + chain(_limiter) { + this._limiter = _limiter; + return this; + } - // Load tables. - var mappingTable = codecOptions.table(); + queued(priority) { + return this._queues.queued(priority); + } + clusterQueued() { + return this._store.__queued__(); + } - // Decode tables: MBCS -> Unicode. + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + running() { + return this._store.__running__(); + } - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; + done() { + return this._store.__done__(); + } - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); + jobStatus(id) { + return this._states.jobStatus(id); + } - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + jobs(status) { + return this._states.statusJobs(status); + } - // Add GB18030 common decode nodes. - var commonThirdByteNodeIdx = this.decodeTables.length; - this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + counts() { + return this._states.statusCounts(); + } - var commonFourthByteNodeIdx = this.decodeTables.length; - this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + _randomIndex() { + return Math.random().toString(36).slice(2); + } - // Fill out the tree - var firstByteNode = this.decodeTables[0]; - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]; - for (var j = 0x30; j <= 0x39; j++) { - if (secondByteNode[j] === UNASSIGNED) { - secondByteNode[j] = NODE_START - commonThirdByteNodeIdx; - } else if (secondByteNode[j] > NODE_START) { - throw new Error("gb18030 decode tables conflict at byte 2"); - } + check(weight = 1) { + return this._store.__check__(weight); + } - var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]; - for (var k = 0x81; k <= 0xFE; k++) { - if (thirdByteNode[k] === UNASSIGNED) { - thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx; - } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { - continue; - } else if (thirdByteNode[k] > NODE_START) { - throw new Error("gb18030 decode tables conflict at byte 3"); - } + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]; - for (var l = 0x30; l <= 0x39; l++) { - if (fourthByteNode[l] === UNASSIGNED) - fourthByteNode[l] = GB18030_CODE; - } - } - } - } - } + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } - this.defaultCharUnicode = iconv.defaultCharUnicode; + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - - // Encode tables: Unicode -> DBCS. + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); -} + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } + + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } + + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } + + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } + + currentReservoir() { + return this._store.__currentReservoir__(); + } + + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } + + } + Bottleneck.default = Bottleneck; + + Bottleneck.Events = Events$4; + + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; + + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; + + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; + + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; + + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; + + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - return node; -} + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; + return Bottleneck; - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + }).call(commonjsGlobal); - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); - } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} + var Bottleneck_1 = Bottleneck; -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} + var lib = Bottleneck_1; -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; -} + return lib; -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; +}))); - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal - } - } +/***/ }), - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} +/***/ 94691: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - var hasValues = false; - var subNodeEmpty = {}; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; +var concatMap = __nccwpck_require__(97087); +var balanced = __nccwpck_require__(59380); - if (uCode >= 0) { - this._setEncodeChar(uCode, mbCode); - hasValues = true; - } else if (uCode <= NODE_START) { - var subNodeIdx = NODE_START - uCode; - if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). - var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive. - if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) - hasValues = true; - else - subNodeEmpty[subNodeIdx] = true; - } - } else if (uCode <= SEQ_START) { - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - hasValues = true; - } - } - return hasValues; -} +module.exports = expandTop; +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} -// == Encoder ================================================================== +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } + var parts = []; + var m = balanced('{', '}', str); - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; + if (!m) + return str.split(','); - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - } else if (resCode == undefined) { // Current character is not part of the sequence. + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. + parts.push.apply(parts, p); - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } + return parts; +} - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } +function expandTop(str) { + if (!str) + return []; - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else if (dbcsCode < 0x1000000) { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } else { - newBuf[j++] = dbcsCode >>> 24; - newBuf[j++] = (dbcsCode >>> 16) & 0xFF; - newBuf[j++] = (dbcsCode >>> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } - } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); + return expand(escapeBraces(str), true).map(unescapeBraces); } -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. - - var newBuf = Buffer.alloc(10), j = 0; - - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; - } +function identity(e) { + return e; +} - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; - } - - return newBuf.slice(0, j); +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); } -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand(str, isTop) { + var expansions = []; -// == Decoder ================================================================== + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBytes = []; + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBytes = this.prevBytes, prevOffset = this.prevBytes.length, - seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence. - uCode; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; + var N; - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - uCode = this.defaultCharUnicode.charCodeAt(0); - i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again. - } - else if (uCode === GB18030_CODE) { - if (i >= 3) { - var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30); - } else { - var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + - (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + - (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + - (curByte-0x30); - } - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode >= 0x10000) { - uCode -= 0x10000; - var uCodeLead = 0xD800 | (uCode >> 10); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; + N = []; - uCode = 0xDC00 | (uCode & 0x3FF); + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - - // Reset trie node. - nodeIdx = 0; seqStart = i+1; + } + N.push(c); } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } - this.nodeIdx = nodeIdx; - this.prevBytes = (seqStart >= 0) - ? Array.prototype.slice.call(buf, seqStart) - : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } - return newBuf.slice(0, j).toString('ucs2'); + return expansions; } -DBCSDecoder.prototype.end = function() { - var ret = ''; - // Try to parse all remaining chars. - while (this.prevBytes.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var bytesArr = this.prevBytes.slice(1); - // Parse remaining as usual. - this.prevBytes = []; - this.nodeIdx = 0; - if (bytesArr.length > 0) - ret += this.write(bytesArr); - } +/***/ }), - this.prevBytes = []; - this.nodeIdx = 0; - return ret; -} +/***/ 40233: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; +"use strict"; - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + ((r-l+1) >> 1); - if (table[mid] <= val) - l = mid; - else - r = mid; - } - return l; + +const contentVer = (__nccwpck_require__(4038)/* ["cache-version"].content */ .MH.Q) +const hashToSegments = __nccwpck_require__(99704) +const path = __nccwpck_require__(16928) +const ssri = __nccwpck_require__(68951) + +// Current format of content file path: +// +// sha512-BaSE64Hex= -> +// ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee +// +module.exports = contentPath + +function contentPath (cache, integrity) { + const sri = ssri.parse(integrity, { single: true }) + // contentPath is the *strongest* algo given + return path.join( + contentDir(cache), + sri.algorithm, + ...hashToSegments(sri.hexDigest()) + ) } +module.exports.contentDir = contentDir + +function contentDir (cache) { + return path.join(cache, `content-v${contentVer}`) +} /***/ }), -/***/ 11802: +/***/ 39398: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. +const fs = __nccwpck_require__(91943) +const fsm = __nccwpck_require__(25032) +const ssri = __nccwpck_require__(68951) +const contentPath = __nccwpck_require__(40233) +const Pipeline = __nccwpck_require__(52899) -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) +module.exports = read - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html +const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024 +async function read (cache, integrity, opts = {}) { + const { size } = opts + const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { + // get size + const stat = size ? { size } : await fs.stat(cpath) + return { stat, cpath, sri } + }) - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(40679) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', + if (stat.size > MAX_SINGLE_READ_SIZE) { + return readPipeline(cpath, stat.size, sri, new Pipeline()).concat() + } - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(56406) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, + const data = await fs.readFile(cpath, { encoding: null }) - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + if (stat.size !== data.length) { + throw sizeError(stat.size, data.length) + } + if (!ssri.checkData(data, sri)) { + throw integrityError(sri, cpath) + } - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + return data +} - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', +const readPipeline = (cpath, size, sri, stream) => { + stream.push( + new fsm.ReadStream(cpath, { + size, + readSize: MAX_SINGLE_READ_SIZE, + }), + ssri.integrityStream({ + integrity: sri, + size, + }) + ) + return stream +} - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(74488) }, - }, +module.exports.stream = readStream +module.exports.readStream = readStream - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', +function readStream (cache, integrity, opts = {}) { + const { size } = opts + const stream = new Pipeline() + // Set all this up to run on the stream and then just return the stream + Promise.resolve().then(async () => { + const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => { + // get size + const stat = size ? { size } : await fs.stat(cpath) + return { stat, cpath, sri } + }) - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) }, - gb18030: function() { return __nccwpck_require__(99129) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, + return readPipeline(cpath, stat.size, sri, stream) + }).catch(err => stream.emit('error', err)) - 'chinese': 'gb18030', + return stream +} +module.exports.copy = copy - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(21166) }, - }, +function copy (cache, integrity, dest) { + return withContentSri(cache, integrity, (cpath) => { + return fs.copyFile(cpath, dest) + }) +} - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', +module.exports.hasContent = hasContent +async function hasContent (cache, integrity) { + if (!integrity) { + return false + } - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + try { + return await withContentSri(cache, integrity, async (cpath, sri) => { + const stat = await fs.stat(cpath) + return { size: stat.size, sri, stat } + }) + } catch (err) { + if (err.code === 'ENOENT') { + return false + } - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(72324) }, - }, + if (err.code === 'EPERM') { + /* istanbul ignore else */ + if (process.platform !== 'win32') { + throw err + } else { + return false + } + } + } +} - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return (__nccwpck_require__(72324).concat)(__nccwpck_require__(43267)) }, - encodeSkipVals: [ - // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of - // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. - // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. - 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, - 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, - 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, - 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, - 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, +async function withContentSri (cache, integrity, fn) { + const sri = ssri.parse(integrity) + // If `integrity` has multiple entries, pick the first digest + // with available local data. + const algo = sri.pickAlgorithm() + const digests = sri[algo] - // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 - 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, - ], - }, + if (digests.length <= 1) { + const cpath = contentPath(cache, digests[0]) + return fn(cpath, digests[0]) + } else { + // Can't use race here because a generic error can happen before + // a ENOENT error, and can happen before a valid result + const results = await Promise.all(digests.map(async (meta) => { + try { + return await withContentSri(cache, meta, fn) + } catch (err) { + if (err.code === 'ENOENT') { + return Object.assign( + new Error('No matching content found for ' + sri.toString()), + { code: 'ENOENT' } + ) + } + return err + } + })) + // Return the first non error if it is found + const result = results.find((r) => !(r instanceof Error)) + if (result) { + return result + } - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; + // Throw the No matching content found error + const enoentError = results.find((r) => r.code === 'ENOENT') + if (enoentError) { + throw enoentError + } + + // Throw generic error + throw results.find((r) => r instanceof Error) + } +} + +function sizeError (expected, found) { + /* eslint-disable-next-line max-len */ + const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) + err.expected = expected + err.found = found + err.code = 'EBADSIZE' + return err +} + +function integrityError (sri, path) { + const err = new Error(`Integrity verification failed for ${sri} (${path})`) + err.code = 'EINTEGRITY' + err.sri = sri + err.path = path + return err +} /***/ }), -/***/ 27585: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 92447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(72356), - __nccwpck_require__(62021), - __nccwpck_require__(8771), - __nccwpck_require__(28231), - __nccwpck_require__(82473), - __nccwpck_require__(97083), - __nccwpck_require__(69487), - __nccwpck_require__(7978), - __nccwpck_require__(11802), -]; +const fs = __nccwpck_require__(91943) +const contentPath = __nccwpck_require__(40233) +const { hasContent } = __nccwpck_require__(39398) -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; +module.exports = rm + +async function rm (cache, integrity) { + const content = await hasContent(cache, integrity) + // ~pretty~ sure we can't end up with a content lacking sri, but be safe + if (content && content.sri) { + await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true }) + return true + } else { + return false + } } /***/ }), -/***/ 72356: +/***/ 93699: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Buffer = (__nccwpck_require__(12803).Buffer); - -// Export Node.js internal encodings. -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", +const events = __nccwpck_require__(24434) - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", +const contentPath = __nccwpck_require__(40233) +const fs = __nccwpck_require__(91943) +const { moveFile } = __nccwpck_require__(88437) +const { Minipass } = __nccwpck_require__(78275) +const Pipeline = __nccwpck_require__(52899) +const Flush = __nccwpck_require__(37633) +const path = __nccwpck_require__(16928) +const ssri = __nccwpck_require__(68951) +const uniqueFilename = __nccwpck_require__(46019) +const fsm = __nccwpck_require__(25032) - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, +module.exports = write - // Codec. - _internal: InternalCodec, -}; +// Cache of move operations in process so we don't duplicate +const moveOperations = new Map() -//------------------------------------------------------------------------------ +async function write (cache, data, opts = {}) { + const { algorithms, size, integrity } = opts -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; + if (typeof size === 'number' && data.length !== size) { + throw sizeError(size, data.length) + } - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; + const sri = ssri.fromData(data, algorithms ? { algorithms } : {}) + if (integrity && !ssri.checkData(data, integrity, opts)) { + throw checksumError(integrity, sri) + } - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } + for (const algo in sri) { + const tmp = await makeTmp(cache, opts) + const hash = sri[algo].toString() + try { + await fs.writeFile(tmp.target, data, { flag: 'wx' }) + await moveToDestination(tmp, cache, hash, opts) + } finally { + if (!tmp.moved) { + await fs.rm(tmp.target, { recursive: true, force: true }) + } } + } + return { integrity: sri, size: data.length } } -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; - -//------------------------------------------------------------------------------ +module.exports.stream = writeStream -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = (__nccwpck_require__(13193).StringDecoder); +// writes proxied to the 'inputStream' that is passed to the Promise +// 'end' is deferred until content is handled. +class CacacheWriteStream extends Flush { + constructor (cache, opts) { + super() + this.opts = opts + this.cache = cache + this.inputStream = new Minipass() + this.inputStream.on('error', er => this.emit('error', er)) + this.inputStream.on('drain', () => this.emit('drain')) + this.handleContentP = null + } -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; + write (chunk, encoding, cb) { + if (!this.handleContentP) { + this.handleContentP = handleContent( + this.inputStream, + this.cache, + this.opts + ) + this.handleContentP.catch(error => this.emit('error', error)) + } + return this.inputStream.write(chunk, encoding, cb) + } + flush (cb) { + this.inputStream.end(() => { + if (!this.handleContentP) { + const e = new Error('Cache input stream was empty') + e.code = 'ENODATA' + // empty streams are probably emitting end right away. + // defer this one tick by rejecting a promise on it. + return Promise.reject(e).catch(cb) + } + // eslint-disable-next-line promise/catch-or-return + this.handleContentP.then( + (res) => { + res.integrity && this.emit('integrity', res.integrity) + // eslint-disable-next-line promise/always-return + res.size !== null && this.emit('size', res.size) + cb() + }, + (er) => cb(er) + ) + }) + } +} -function InternalDecoder(options, codec) { - this.decoder = new StringDecoder(codec.enc); +function writeStream (cache, opts = {}) { + return new CacacheWriteStream(cache, opts) } -InternalDecoder.prototype.write = function(buf) { - if (!Buffer.isBuffer(buf)) { - buf = Buffer.from(buf); +async function handleContent (inputStream, cache, opts) { + const tmp = await makeTmp(cache, opts) + try { + const res = await pipeToTmp(inputStream, cache, tmp.target, opts) + await moveToDestination( + tmp, + cache, + res.integrity, + opts + ) + return res + } finally { + if (!tmp.moved) { + await fs.rm(tmp.target, { recursive: true, force: true }) } - - return this.decoder.write(buf); + } } -InternalDecoder.prototype.end = function() { - return this.decoder.end(); +async function pipeToTmp (inputStream, cache, tmpTarget, opts) { + const outStream = new fsm.WriteStream(tmpTarget, { + flags: 'wx', + }) + + if (opts.integrityEmitter) { + // we need to create these all simultaneously since they can fire in any order + const [integrity, size] = await Promise.all([ + events.once(opts.integrityEmitter, 'integrity').then(res => res[0]), + events.once(opts.integrityEmitter, 'size').then(res => res[0]), + new Pipeline(inputStream, outStream).promise(), + ]) + return { integrity, size } + } + + let integrity + let size + const hashStream = ssri.integrityStream({ + integrity: opts.integrity, + algorithms: opts.algorithms, + size: opts.size, + }) + hashStream.on('integrity', i => { + integrity = i + }) + hashStream.on('size', s => { + size = s + }) + + const pipeline = new Pipeline(inputStream, hashStream, outStream) + await pipeline.promise() + return { integrity, size } } +async function makeTmp (cache, opts) { + const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) + await fs.mkdir(path.dirname(tmpTarget), { recursive: true }) + return { + target: tmpTarget, + moved: false, + } +} -//------------------------------------------------------------------------------ -// Encoder is mostly trivial +async function moveToDestination (tmp, cache, sri) { + const destination = contentPath(cache, sri) + const destDir = path.dirname(destination) + if (moveOperations.has(destination)) { + return moveOperations.get(destination) + } + moveOperations.set( + destination, + fs.mkdir(destDir, { recursive: true }) + .then(async () => { + await moveFile(tmp.target, destination, { overwrite: false }) + tmp.moved = true + return tmp.moved + }) + .catch(err => { + if (!err.message.startsWith('The destination file exists')) { + throw Object.assign(err, { code: 'EEXIST' }) + } + }).finally(() => { + moveOperations.delete(destination) + }) -function InternalEncoder(options, codec) { - this.enc = codec.enc; + ) + return moveOperations.get(destination) } -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); +function sizeError (expected, found) { + /* eslint-disable-next-line max-len */ + const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`) + err.expected = expected + err.found = found + err.code = 'EBADSIZE' + return err } -InternalEncoder.prototype.end = function() { +function checksumError (expected, found) { + const err = new Error(`Integrity check failed: + Wanted: ${expected} + Found: ${found}`) + err.code = 'EINTEGRITY' + err.expected = expected + err.found = found + return err } -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. +/***/ }), -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} +/***/ 26575: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); +"use strict"; - return Buffer.from(str, "base64"); -} -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} +const crypto = __nccwpck_require__(76982) +const { + appendFile, + mkdir, + readFile, + readdir, + rm, + writeFile, +} = __nccwpck_require__(91943) +const { Minipass } = __nccwpck_require__(78275) +const path = __nccwpck_require__(16928) +const ssri = __nccwpck_require__(68951) +const uniqueFilename = __nccwpck_require__(46019) +const contentPath = __nccwpck_require__(40233) +const hashToSegments = __nccwpck_require__(99704) +const indexV = (__nccwpck_require__(4038)/* ["cache-version"].index */ .MH.P) +const { moveFile } = __nccwpck_require__(88437) -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. +const lsStreamConcurrency = 5 -function InternalEncoderCesu8(options, codec) { +module.exports.NotFoundError = class NotFoundError extends Error { + constructor (cache, key) { + super(`No cache entry for ${key} found in ${cache}`) + this.code = 'ENOENT' + this.cache = cache + this.key = key + } } -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - } - return buf.slice(0, bufIdx); -} +module.exports.compact = compact -InternalEncoderCesu8.prototype.end = function() { -} +async function compact (cache, key, matchFn, opts = {}) { + const bucket = bucketPath(cache, key) + const entries = await bucketEntries(bucket) + const newEntries = [] + // we loop backwards because the bottom-most result is the newest + // since we add new entries with appendFile + for (let i = entries.length - 1; i >= 0; --i) { + const entry = entries[i] + // a null integrity could mean either a delete was appended + // or the user has simply stored an index that does not map + // to any content. we determine if the user wants to keep the + // null integrity based on the validateEntry function passed in options. + // if the integrity is null and no validateEntry is provided, we break + // as we consider the null integrity to be a deletion of everything + // that came before it. + if (entry.integrity === null && !opts.validateEntry) { + break + } -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ + // if this entry is valid, and it is either the first entry or + // the newEntries array doesn't already include an entry that + // matches this one based on the provided matchFn, then we add + // it to the beginning of our list + if ((!opts.validateEntry || opts.validateEntry(entry) === true) && + (newEntries.length === 0 || + !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) { + newEntries.unshift(entry) + } + } -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} + const newIndex = '\n' + newEntries.map((entry) => { + const stringified = JSON.stringify(entry) + const hash = hashEntry(stringified) + return `${hash}\t${stringified}` + }).join('\n') -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } + const setup = async () => { + const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix) + await mkdir(path.dirname(target), { recursive: true }) + return { + target, + moved: false, + } + } - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } + const teardown = async (tmp) => { + if (!tmp.moved) { + return rm(tmp.target, { recursive: true, force: true }) } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} + } -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; -} + const write = async (tmp) => { + await writeFile(tmp.target, newIndex, { flag: 'wx' }) + await mkdir(path.dirname(bucket), { recursive: true }) + // we use @npmcli/move-file directly here because we + // want to overwrite the existing file + await moveFile(tmp.target, bucket) + tmp.moved = true + } + // write the file atomically + const tmp = await setup() + try { + await write(tmp) + } finally { + await teardown(tmp) + } -/***/ }), + // we reverse the list we generated such that the newest + // entries come first in order to make looping through them easier + // the true passed to formatEntry tells it to keep null + // integrity values, if they made it this far it's because + // validateEntry returned true, and as such we should return it + return newEntries.reverse().map((entry) => formatEntry(cache, entry, true)) +} -/***/ 82473: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +module.exports.insert = insert -"use strict"; +async function insert (cache, key, integrity, opts = {}) { + const { metadata, size, time } = opts + const bucket = bucketPath(cache, key) + const entry = { + key, + integrity: integrity && ssri.stringify(integrity), + time: time || Date.now(), + size, + metadata, + } + try { + await mkdir(path.dirname(bucket), { recursive: true }) + const stringified = JSON.stringify(entry) + // NOTE - Cleverness ahoy! + // + // This works because it's tremendously unlikely for an entry to corrupt + // another while still preserving the string length of the JSON in + // question. So, we just slap the length in there and verify it on read. + // + // Thanks to @isaacs for the whiteboarding session that ended up with + // this. + await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`) + } catch (err) { + if (err.code === 'ENOENT') { + return undefined + } -var Buffer = (__nccwpck_require__(12803).Buffer); + throw err + } + return formatEntry(cache, entry) +} -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). +module.exports.find = find -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; +async function find (cache, key) { + const bucket = bucketPath(cache, key) + try { + const entries = await bucketEntries(bucket) + return entries.reduce((latest, next) => { + if (next && next.key === key) { + return formatEntry(cache, next) + } else { + return latest + } + }, null) + } catch (err) { + if (err.code === 'ENOENT') { + return null + } else { + throw err } + } +} - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); +module.exports["delete"] = del - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; +function del (cache, key, opts = {}) { + if (!opts.removeFully) { + return insert(cache, key, null, opts) + } - this.encodeBuf = encodeBuf; + const bucket = bucketPath(cache, key) + return rm(bucket, { recursive: true, force: true }) } -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; +module.exports.lsStream = lsStream +function lsStream (cache) { + const indexDir = bucketDir(cache) + const stream = new Minipass({ objectMode: true }) -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} + // Set all this up to run on the stream and then just return the stream + Promise.resolve().then(async () => { + const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606)) + const buckets = await readdirOrEmpty(indexDir) + await pMap(buckets, async (bucket) => { + const bucketPath = path.join(indexDir, bucket) + const subbuckets = await readdirOrEmpty(bucketPath) + await pMap(subbuckets, async (subbucket) => { + const subbucketPath = path.join(bucketPath, subbucket) -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} + // "/cachename//./*" + const subbucketEntries = await readdirOrEmpty(subbucketPath) + await pMap(subbucketEntries, async (entry) => { + const entryPath = path.join(subbucketPath, entry) + try { + const entries = await bucketEntries(entryPath) + // using a Map here prevents duplicate keys from showing up + // twice, I guess? + const reduced = entries.reduce((acc, entry) => { + acc.set(entry.key, entry) + return acc + }, new Map()) + // reduced is a map of key => entry + for (const entry of reduced.values()) { + const formatted = formatEntry(cache, entry) + if (formatted) { + stream.write(formatted) + } + } + } catch (err) { + if (err.code === 'ENOENT') { + return undefined + } + throw err + } + }, + { concurrency: lsStreamConcurrency }) + }, + { concurrency: lsStreamConcurrency }) + }, + { concurrency: lsStreamConcurrency }) + stream.end() + return stream + }).catch(err => stream.emit('error', err)) -SBCSEncoder.prototype.end = function() { + return stream } +module.exports.ls = ls -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; +async function ls (cache) { + const entries = await lsStream(cache).collect() + return entries.reduce((acc, xs) => { + acc[xs.key] = xs + return acc + }, {}) } -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); -} +module.exports.bucketEntries = bucketEntries -SBCSDecoder.prototype.end = function() { +async function bucketEntries (bucket, filter) { + const data = await readFile(bucket, 'utf8') + return _bucketEntries(data, filter) } +function _bucketEntries (data) { + const entries = [] + data.split('\n').forEach((entry) => { + if (!entry) { + return + } -/***/ }), - -/***/ 69487: -/***/ ((module) => { - -"use strict"; - - -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + const pieces = entry.split('\t') + if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) { + // Hash is no good! Corruption or malice? Doesn't matter! + // EJECT EJECT + return + } + let obj + try { + obj = JSON.parse(pieces[1]) + } catch (_) { + // eslint-ignore-next-line no-empty-block + } + // coverage disabled here, no need to test with an entry that parses to something falsey + // istanbul ignore else + if (obj) { + entries.push(obj) + } + }) + return entries +} + +module.exports.bucketDir = bucketDir + +function bucketDir (cache) { + return path.join(cache, `index-v${indexV}`) +} + +module.exports.bucketPath = bucketPath + +function bucketPath (cache, key) { + const hashed = hashKey(key) + return path.join.apply( + path, + [bucketDir(cache)].concat(hashToSegments(hashed)) + ) +} + +module.exports.hashKey = hashKey + +function hashKey (key) { + return hash(key, 'sha256') +} + +module.exports.hashEntry = hashEntry + +function hashEntry (str) { + return hash(str, 'sha1') +} + +function hash (str, digest) { + return crypto + .createHash(digest) + .update(str) + .digest('hex') +} + +function formatEntry (cache, entry, keepAll) { + // Treat null digests as deletions. They'll shadow any previous entries. + if (!entry.integrity && !keepAll) { + return null + } + + return { + key: entry.key, + integrity: entry.integrity, + path: entry.integrity ? contentPath(cache, entry.integrity) : undefined, + size: entry.size, + time: entry.time, + metadata: entry.metadata, } } +function readdirOrEmpty (dir) { + return readdir(dir).catch((err) => { + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { + return [] + } + + throw err + }) +} + + /***/ }), -/***/ 97083: -/***/ ((module) => { +/***/ 19690: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Manually added data to be used by sbcs codec in addition to generated one. +const Collect = __nccwpck_require__(11757) +const { Minipass } = __nccwpck_require__(78275) +const Pipeline = __nccwpck_require__(52899) -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, +const index = __nccwpck_require__(26575) +const memo = __nccwpck_require__(56068) +const read = __nccwpck_require__(39398) - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, +async function getData (cache, key, opts = {}) { + const { integrity, memoize, size } = opts + const memoized = memo.get(cache, key, opts) + if (memoized && memoize !== false) { + return { + metadata: memoized.entry.metadata, + data: memoized.data, + integrity: memoized.entry.integrity, + size: memoized.entry.size, + } + } - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, + const entry = await index.find(cache, key, opts) + if (!entry) { + throw new index.NotFoundError(cache, key) + } + const data = await read(cache, entry.integrity, { integrity, size }) + if (memoize) { + memo.put(cache, entry, data, opts) + } - "cp720": { - "type": "_sbcs", - "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" - }, + return { + data, + metadata: entry.metadata, + size: entry.size, + integrity: entry.integrity, + } +} +module.exports = getData - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", +async function getDataByDigest (cache, key, opts = {}) { + const { integrity, memoize, size } = opts + const memoized = memo.get.byDigest(cache, key, opts) + if (memoized && memoize !== false) { + return memoized + } - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", + const res = await read(cache, key, { integrity, size }) + if (memoize) { + memo.put.byDigest(cache, key, res, opts) + } + return res +} +module.exports.byDigest = getDataByDigest - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", +const getMemoizedStream = (memoized) => { + const stream = new Minipass() + stream.on('newListener', function (ev, cb) { + ev === 'metadata' && cb(memoized.entry.metadata) + ev === 'integrity' && cb(memoized.entry.integrity) + ev === 'size' && cb(memoized.entry.size) + }) + stream.end(memoized.data) + return stream +} - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", +function getStream (cache, key, opts = {}) { + const { memoize, size } = opts + const memoized = memo.get(cache, key, opts) + if (memoized && memoize !== false) { + return getMemoizedStream(memoized) + } - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", + const stream = new Pipeline() + // Set all this up to run on the stream and then just return the stream + Promise.resolve().then(async () => { + const entry = await index.find(cache, key) + if (!entry) { + throw new index.NotFoundError(cache, key) + } - "cp819": "iso88591", - "ibm819": "iso88591", + stream.emit('metadata', entry.metadata) + stream.emit('integrity', entry.integrity) + stream.emit('size', entry.size) + stream.on('newListener', function (ev, cb) { + ev === 'metadata' && cb(entry.metadata) + ev === 'integrity' && cb(entry.integrity) + ev === 'size' && cb(entry.size) + }) - "cyrillic": "iso88595", + const src = read.readStream( + cache, + entry.integrity, + { ...opts, size: typeof size !== 'number' ? entry.size : size } + ) - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", + if (memoize) { + const memoStream = new Collect.PassThrough() + memoStream.on('collect', data => memo.put(cache, entry, data, opts)) + stream.unshift(memoStream) + } + stream.unshift(src) + return stream + }).catch((err) => stream.emit('error', err)) - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", + return stream +} - "hebrew": "iso88598", - "hebrew8": "iso88598", +module.exports.stream = getStream - "turkish": "iso88599", - "turkish8": "iso88599", +function getStreamDigest (cache, integrity, opts = {}) { + const { memoize } = opts + const memoized = memo.get.byDigest(cache, integrity, opts) + if (memoized && memoize !== false) { + const stream = new Minipass() + stream.end(memoized) + return stream + } else { + const stream = read.readStream(cache, integrity, opts) + if (!memoize) { + return stream + } - "thai": "iso885911", - "thai8": "iso885911", + const memoStream = new Collect.PassThrough() + memoStream.on('collect', data => memo.put.byDigest( + cache, + integrity, + data, + opts + )) + return new Pipeline(stream, memoStream) + } +} - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", +module.exports.stream.byDigest = getStreamDigest - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", +function info (cache, key, opts = {}) { + const { memoize } = opts + const memoized = memo.get(cache, key, opts) + if (memoized && memoize !== false) { + return Promise.resolve(memoized.entry) + } else { + return index.find(cache, key) + } +} +module.exports.info = info - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", +async function copy (cache, key, dest, opts = {}) { + const entry = await index.find(cache, key, opts) + if (!entry) { + throw new index.NotFoundError(cache, key) + } + await read.copy(cache, entry.integrity, dest, opts) + return { + metadata: entry.metadata, + size: entry.size, + integrity: entry.integrity, + } +} - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", +module.exports.copy = copy - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", +async function copyByDigest (cache, key, dest, opts = {}) { + await read.copy(cache, key, dest, opts) + return key +} - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", +module.exports.copy.byDigest = copyByDigest - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", +module.exports.hasContent = read.hasContent - "strk10482002": "rk1048", - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", +/***/ }), + +/***/ 85742: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const get = __nccwpck_require__(19690) +const put = __nccwpck_require__(94283) +const rm = __nccwpck_require__(30793) +const verify = __nccwpck_require__(37621) +const { clearMemoized } = __nccwpck_require__(56068) +const tmp = __nccwpck_require__(63990) +const index = __nccwpck_require__(26575) + +module.exports.index = {} +module.exports.index.compact = index.compact +module.exports.index.insert = index.insert + +module.exports.ls = index.ls +module.exports.ls.stream = index.lsStream + +module.exports.get = get +module.exports.get.byDigest = get.byDigest +module.exports.get.stream = get.stream +module.exports.get.stream.byDigest = get.stream.byDigest +module.exports.get.copy = get.copy +module.exports.get.copy.byDigest = get.copy.byDigest +module.exports.get.info = get.info +module.exports.get.hasContent = get.hasContent + +module.exports.put = put +module.exports.put.stream = put.stream + +module.exports.rm = rm.entry +module.exports.rm.all = rm.all +module.exports.rm.entry = module.exports.rm +module.exports.rm.content = rm.content + +module.exports.clearMemoized = clearMemoized + +module.exports.tmp = {} +module.exports.tmp.mkdir = tmp.mkdir +module.exports.tmp.withTmp = tmp.withTmp + +module.exports.verify = verify +module.exports.verify.lastRun = verify.lastRun + + +/***/ }), + +/***/ 56068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { LRUCache } = __nccwpck_require__(83193) + +const MEMOIZED = new LRUCache({ + max: 500, + maxSize: 50 * 1024 * 1024, // 50MB + ttl: 3 * 60 * 1000, // 3 minutes + sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length, +}) + +module.exports.clearMemoized = clearMemoized + +function clearMemoized () { + const old = {} + MEMOIZED.forEach((v, k) => { + old[k] = v + }) + MEMOIZED.clear() + return old +} + +module.exports.put = put + +function put (cache, entry, data, opts) { + pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data }) + putDigest(cache, entry.integrity, data, opts) +} + +module.exports.put.byDigest = putDigest + +function putDigest (cache, integrity, data, opts) { + pickMem(opts).set(`digest:${cache}:${integrity}`, data) +} + +module.exports.get = get + +function get (cache, key, opts) { + return pickMem(opts).get(`key:${cache}:${key}`) +} + +module.exports.get.byDigest = getDigest + +function getDigest (cache, integrity, opts) { + return pickMem(opts).get(`digest:${cache}:${integrity}`) +} + +class ObjProxy { + constructor (obj) { + this.obj = obj + } + + get (key) { + return this.obj[key] + } + + set (key, val) { + this.obj[key] = val + } +} + +function pickMem (opts) { + if (!opts || !opts.memoize) { + return MEMOIZED + } else if (opts.memoize.get && opts.memoize.set) { + return opts.memoize + } else if (typeof opts.memoize === 'object') { + return new ObjProxy(opts.memoize) + } else { + return MEMOIZED + } +} + + +/***/ }), + +/***/ 94283: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const index = __nccwpck_require__(26575) +const memo = __nccwpck_require__(56068) +const write = __nccwpck_require__(93699) +const Flush = __nccwpck_require__(37633) +const { PassThrough } = __nccwpck_require__(11757) +const Pipeline = __nccwpck_require__(52899) + +const putOpts = (opts) => ({ + algorithms: ['sha512'], + ...opts, +}) + +module.exports = putData + +async function putData (cache, key, data, opts = {}) { + const { memoize } = opts + opts = putOpts(opts) + const res = await write(cache, data, opts) + const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size }) + if (memoize) { + memo.put(cache, entry, data, opts) + } + + return res.integrity +} + +module.exports.stream = putStream - "gb198880": "iso646cn", - "cn": "iso646cn", +function putStream (cache, key, opts = {}) { + const { memoize } = opts + opts = putOpts(opts) + let integrity + let size + let error - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", + let memoData + const pipeline = new Pipeline() + // first item in the pipeline is the memoizer, because we need + // that to end first and get the collected data. + if (memoize) { + const memoizer = new PassThrough().on('collect', data => { + memoData = data + }) + pipeline.push(memoizer) + } - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", + // contentStream is a write-only, not a passthrough + // no data comes out of it. + const contentStream = write.stream(cache, opts) + .on('integrity', (int) => { + integrity = int + }) + .on('size', (s) => { + size = s + }) + .on('error', (err) => { + error = err + }) - "mac": "macintosh", - "csmacintosh": "macintosh", -}; + pipeline.push(contentStream) + + // last but not least, we write the index and emit hash and size, + // and memoize if we're doing that + pipeline.push(new Flush({ + async flush () { + if (!error) { + const entry = await index.insert(cache, key, integrity, { ...opts, size }) + if (memoize && memoData) { + memo.put(cache, entry, memoData, opts) + } + pipeline.emit('integrity', integrity) + pipeline.emit('size', size) + } + }, + })) + return pipeline +} /***/ }), -/***/ 8771: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 30793: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Buffer = (__nccwpck_require__(12803).Buffer); -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js +const { rm } = __nccwpck_require__(91943) +const glob = __nccwpck_require__(6337) +const index = __nccwpck_require__(26575) +const memo = __nccwpck_require__(56068) +const path = __nccwpck_require__(16928) +const rmContent = __nccwpck_require__(92447) -// == UTF16-BE codec. ========================================================== +module.exports = entry +module.exports.entry = entry -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { +function entry (cache, key, opts) { + memo.clearMemoized() + return index.delete(cache, key, opts) } -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; +module.exports.content = content +function content (cache, integrity) { + memo.clearMemoized() + return rmContent(cache, integrity) +} -// -- Encoding +module.exports.all = all -function Utf16BEEncoder() { +async function all (cache) { + memo.clearMemoized() + const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true }) + return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true }))) } -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; -} -Utf16BEEncoder.prototype.end = function() { -} +/***/ }), +/***/ 6337: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// -- Decoding +"use strict"; -function Utf16BEDecoder() { - this.overflowByte = -1; -} -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; +const { glob } = __nccwpck_require__(67471) +const path = __nccwpck_require__(16928) - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; +const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep) +module.exports = (path, options) => glob(globify(path), options) - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } +/***/ }), - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; +/***/ 99704: +/***/ ((module) => { - return buf2.slice(0, j).toString('ucs2'); -} +"use strict"; -Utf16BEDecoder.prototype.end = function() { - this.overflowByte = -1; + +module.exports = hashToSegments + +function hashToSegments (hash) { + return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)] } -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); +/***/ }), -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). +/***/ 63990: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} +"use strict"; -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; +const { withTempDir } = __nccwpck_require__(88437) +const fs = __nccwpck_require__(91943) +const path = __nccwpck_require__(16928) -// -- Encoding (pass-through) +module.exports.mkdir = mktmpdir -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); +async function mktmpdir (cache, opts = {}) { + const { tmpPrefix } = opts + const tmpDir = path.join(cache, 'tmp') + await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' }) + // do not use path.join(), it drops the trailing / if tmpPrefix is unset + const target = `${tmpDir}${path.sep}${tmpPrefix || ''}` + return fs.mkdtemp(target, { owner: 'inherit' }) } -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} +module.exports.withTmp = withTmp -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); +function withTmp (cache, opts, cb) { + if (!cb) { + cb = opts + opts = {} + } + return withTempDir(path.join(cache, 'tmp'), cb, opts) } -// -- Decoding - -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; +/***/ }), - this.options = options || {}; - this.iconv = codec.iconv; -} +/***/ 37621: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - - if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) - return ''; +"use strict"; - // We have enough bytes -> detect endianness. - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); +const { + mkdir, + readFile, + rm, + stat, + truncate, + writeFile, +} = __nccwpck_require__(91943) +const contentPath = __nccwpck_require__(40233) +const fsm = __nccwpck_require__(25032) +const glob = __nccwpck_require__(6337) +const index = __nccwpck_require__(26575) +const path = __nccwpck_require__(16928) +const ssri = __nccwpck_require__(68951) - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } +const hasOwnProperty = (obj, key) => + Object.prototype.hasOwnProperty.call(obj, key) - return this.decoder.write(buf); -} +const verifyOpts = (opts) => ({ + concurrency: 20, + log: { silly () {} }, + ...opts, +}) -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); +module.exports = verify - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); +async function verify (cache, opts) { + opts = verifyOpts(opts) + opts.log.silly('verify', 'verifying cache at', cache) - var trail = this.decoder.end(); - if (trail) - resStr += trail; + const steps = [ + markStartTime, + fixPerms, + garbageCollect, + rebuildIndex, + cleanTmp, + writeVerifile, + markEndTime, + ] - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; + const stats = {} + for (const step of steps) { + const label = step.name + const start = new Date() + const s = await step(cache, opts) + if (s) { + Object.keys(s).forEach((k) => { + stats[k] = s[k] + }) } - return this.decoder.end(); + const end = new Date() + if (!stats.runTime) { + stats.runTime = {} + } + stats.runTime[label] = end - start + } + stats.runTime.total = stats.endTime - stats.startTime + opts.log.silly( + 'verify', + 'verification finished for', + cache, + 'in', + `${stats.runTime.total}ms` + ) + return stats } -function detectEncoding(bufs, defaultEncoding) { - var b = []; - var charsProcessed = 0; - var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. - - outer_loop: - for (var i = 0; i < bufs.length; i++) { - var buf = bufs[i]; - for (var j = 0; j < buf.length; j++) { - b.push(buf[j]); - if (b.length === 2) { - if (charsProcessed === 0) { - // Check BOM first. - if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; - if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; - } +async function markStartTime () { + return { startTime: new Date() } +} - if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; - if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; +async function markEndTime () { + return { endTime: new Date() } +} - b.length = 0; - charsProcessed++; +async function fixPerms (cache, opts) { + opts.log.silly('verify', 'fixing cache permissions') + await mkdir(cache, { recursive: true }) + return null +} - if (charsProcessed >= 100) { - break outer_loop; - } - } - } +// Implements a naive mark-and-sweep tracing garbage collector. +// +// The algorithm is basically as follows: +// 1. Read (and filter) all index entries ("pointers") +// 2. Mark each integrity value as "live" +// 3. Read entire filesystem tree in `content-vX/` dir +// 4. If content is live, verify its checksum and delete it if it fails +// 5. If content is not marked as live, rm it. +// +async function garbageCollect (cache, opts) { + opts.log.silly('verify', 'garbage collecting content') + const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606)) + const indexStream = index.lsStream(cache) + const liveContent = new Set() + indexStream.on('data', (entry) => { + if (opts.filter && !opts.filter(entry)) { + return } - // Make decisions. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; - if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; - - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-16le'; + // integrity is stringified, re-parse it so we can get each hash + const integrity = ssri.parse(entry.integrity) + for (const algo in integrity) { + liveContent.add(integrity[algo].toString()) + } + }) + await new Promise((resolve, reject) => { + indexStream.on('end', resolve).on('error', reject) + }) + const contentDir = contentPath.contentDir(cache) + const files = await glob(path.join(contentDir, '**'), { + follow: false, + nodir: true, + nosort: true, + }) + const stats = { + verifiedContent: 0, + reclaimedCount: 0, + reclaimedSize: 0, + badContentCount: 0, + keptSize: 0, + } + await pMap( + files, + async (f) => { + const split = f.split(/[/\\]/) + const digest = split.slice(split.length - 3).join('') + const algo = split[split.length - 4] + const integrity = ssri.fromHex(digest, algo) + if (liveContent.has(integrity.toString())) { + const info = await verifyContent(f, integrity) + if (!info.valid) { + stats.reclaimedCount++ + stats.badContentCount++ + stats.reclaimedSize += info.size + } else { + stats.verifiedContent++ + stats.keptSize += info.size + } + } else { + // No entries refer to this content. We can delete. + stats.reclaimedCount++ + const s = await stat(f) + await rm(f, { recursive: true, force: true }) + stats.reclaimedSize += s.size + } + return stats + }, + { concurrency: opts.concurrency } + ) + return stats } +async function verifyContent (filepath, sri) { + const contentInfo = {} + try { + const { size } = await stat(filepath) + contentInfo.size = size + contentInfo.valid = true + await ssri.checkStream(new fsm.ReadStream(filepath), sri) + } catch (err) { + if (err.code === 'ENOENT') { + return { size: 0, valid: false } + } + if (err.code !== 'EINTEGRITY') { + throw err + } + await rm(filepath, { recursive: true, force: true }) + contentInfo.valid = false + } + return contentInfo +} +async function rebuildIndex (cache, opts) { + opts.log.silly('verify', 'rebuilding index') + const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606)) + const entries = await index.ls(cache) + const stats = { + missingContent: 0, + rejectedEntries: 0, + totalEntries: 0, + } + const buckets = {} + for (const k in entries) { + /* istanbul ignore else */ + if (hasOwnProperty(entries, k)) { + const hashed = index.hashKey(k) + const entry = entries[k] + const excluded = opts.filter && !opts.filter(entry) + excluded && stats.rejectedEntries++ + if (buckets[hashed] && !excluded) { + buckets[hashed].push(entry) + } else if (buckets[hashed] && excluded) { + // skip + } else if (excluded) { + buckets[hashed] = [] + buckets[hashed]._path = index.bucketPath(cache, k) + } else { + buckets[hashed] = [entry] + buckets[hashed]._path = index.bucketPath(cache, k) + } + } + } + await pMap( + Object.keys(buckets), + (key) => { + return rebuildBucket(cache, buckets[key], stats, opts) + }, + { concurrency: opts.concurrency } + ) + return stats +} -/***/ }), - -/***/ 62021: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +async function rebuildBucket (cache, bucket, stats) { + await truncate(bucket._path) + // This needs to be serialized because cacache explicitly + // lets very racy bucket conflicts clobber each other. + for (const entry of bucket) { + const content = contentPath(cache, entry.integrity) + try { + await stat(content) + await index.insert(cache, entry.key, entry.integrity, { + metadata: entry.metadata, + size: entry.size, + time: entry.time, + }) + stats.totalEntries++ + } catch (err) { + if (err.code === 'ENOENT') { + stats.rejectedEntries++ + stats.missingContent++ + } else { + throw err + } + } + } +} -"use strict"; +function cleanTmp (cache, opts) { + opts.log.silly('verify', 'cleaning tmp directory') + return rm(path.join(cache, 'tmp'), { recursive: true, force: true }) +} +async function writeVerifile (cache, opts) { + const verifile = path.join(cache, '_lastverified') + opts.log.silly('verify', 'writing verifile to ' + verifile) + return writeFile(verifile, `${Date.now()}`) +} -var Buffer = (__nccwpck_require__(12803).Buffer); +module.exports.lastRun = lastRun -// == UTF32-LE/BE codec. ========================================================== +async function lastRun (cache) { + const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' }) + return new Date(+data) +} -exports._utf32 = Utf32Codec; -function Utf32Codec(codecOptions, iconv) { - this.iconv = iconv; - this.bomAware = true; - this.isLE = codecOptions.isLE; -} +/***/ }), -exports.utf32le = { type: '_utf32', isLE: true }; -exports.utf32be = { type: '_utf32', isLE: false }; +/***/ 66723: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Aliases -exports.ucs4le = 'utf32le'; -exports.ucs4be = 'utf32be'; +var balanced = __nccwpck_require__(59380); -Utf32Codec.prototype.encoder = Utf32Encoder; -Utf32Codec.prototype.decoder = Utf32Decoder; +module.exports = expandTop; -// -- Encoding +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -function Utf32Encoder(options, codec) { - this.isLE = codec.isLE; - this.highSurrogate = 0; +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); } -Utf32Encoder.prototype.write = function(str) { - var src = Buffer.from(str, 'ucs2'); - var dst = Buffer.alloc(src.length * 2); - var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; - var offset = 0; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} - for (var i = 0; i < src.length; i += 2) { - var code = src.readUInt16LE(i); - var isHighSurrogate = (0xD800 <= code && code < 0xDC00); - var isLowSurrogate = (0xDC00 <= code && code < 0xE000); +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} - if (this.highSurrogate) { - if (isHighSurrogate || !isLowSurrogate) { - // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low - // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character - // (technically wrong, but expected by some applications, like Windows file names). - write32.call(dst, this.highSurrogate, offset); - offset += 4; - } - else { - // Create 32-bit value from high and low surrogates; - var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; - write32.call(dst, codepoint, offset); - offset += 4; - this.highSurrogate = 0; +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; - continue; - } - } + var parts = []; + var m = balanced('{', '}', str); - if (isHighSurrogate) - this.highSurrogate = code; - else { - // Even if the current character is a low surrogate, with no previous high surrogate, we'll - // encode it as a semi-invalid stand-alone character for the same reasons expressed above for - // unpaired high surrogates. - write32.call(dst, code, offset); - offset += 4; - this.highSurrogate = 0; - } - } + if (!m) + return str.split(','); - if (offset < dst.length) - dst = dst.slice(0, offset); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - return dst; -}; + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } -Utf32Encoder.prototype.end = function() { - // Treat any leftover high surrogate as a semi-valid independent character. - if (!this.highSurrogate) - return; + parts.push.apply(parts, p); - var buf = Buffer.alloc(4); + return parts; +} - if (this.isLE) - buf.writeUInt32LE(this.highSurrogate, 0); - else - buf.writeUInt32BE(this.highSurrogate, 0); +function expandTop(str) { + if (!str) + return []; - this.highSurrogate = 0; + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } - return buf; -}; + return expand(escapeBraces(str), true).map(unescapeBraces); +} -// -- Decoding +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} -function Utf32Decoder(options, codec) { - this.isLE = codec.isLE; - this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); - this.overflow = []; +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; } -Utf32Decoder.prototype.write = function(src) { - if (src.length === 0) - return ''; +function expand(str, isTop) { + var expansions = []; - var i = 0; - var codepoint = 0; - var dst = Buffer.alloc(src.length + 4); - var offset = 0; - var isLE = this.isLE; - var overflow = this.overflow; - var badChar = this.badChar; + var m = balanced('{', '}', str); + if (!m) return [str]; - if (overflow.length > 0) { - for (; i < src.length && overflow.length < 4; i++) - overflow.push(src[i]); - - if (overflow.length === 4) { - // NOTE: codepoint is a signed int32 and can be negative. - // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). - if (isLE) { - codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); - } else { - codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); - } - overflow.length = 0; + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - offset = _writeCodepoint(dst, offset, codepoint, badChar); - } + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); } - - // Main loop. Should be as optimized as possible. - for (; i < src.length - 3; i += 4) { - // NOTE: codepoint is a signed int32 and can be negative. - if (isLE) { - codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); - } else { - codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); - } - offset = _writeCodepoint(dst, offset, codepoint, badChar); + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; } - // Keep overflowing bytes. - for (; i < src.length; i++) { - overflow.push(src[i]); + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } } - return dst.slice(0, offset).toString('ucs2'); -}; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; -function _writeCodepoint(dst, offset, codepoint, badChar) { - // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. - if (codepoint < 0 || codepoint > 0x10FFFF) { - // Not a valid Unicode codepoint - codepoint = badChar; - } + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - // Ephemeral Planes: Write high surrogate. - if (codepoint >= 0x10000) { - codepoint -= 0x10000; + N = []; - var high = 0xD800 | (codepoint >> 10); - dst[offset++] = high & 0xff; - dst[offset++] = high >> 8; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; - // Low surrogate is written below. - var codepoint = 0xDC00 | (codepoint & 0x3FF); + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } } - // Write BMP char or low surrogate. - dst[offset++] = codepoint & 0xff; - dst[offset++] = codepoint >> 8; - - return offset; -}; + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } -Utf32Decoder.prototype.end = function() { - this.overflow.length = 0; -}; + return expansions; +} -// == UTF-32 Auto codec ============================================================= -// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. -// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 -// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); -// Encoder prepends BOM (which can be overridden with (addBOM: false}). -exports.utf32 = Utf32AutoCodec; -exports.ucs4 = 'utf32'; +/***/ }), -function Utf32AutoCodec(options, iconv) { - this.iconv = iconv; -} +/***/ 97087: +/***/ ((module) => { -Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; -Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; -// -- Encoding +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; -function Utf32AutoEncoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; +/***/ }), - this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); -} +/***/ 6110: +/***/ ((module, exports, __nccwpck_require__) => { -Utf32AutoEncoder.prototype.write = function(str) { - return this.encoder.write(str); -}; +/* eslint-env browser */ -Utf32AutoEncoder.prototype.end = function() { - return this.encoder.end(); -}; +/** + * This is the web browser implementation of `debug()`. + */ -// -- Decoding +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; -function Utf32AutoDecoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - this.options = options || {}; - this.iconv = codec.iconv; -} + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); -Utf32AutoDecoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; +/** + * Colors. + */ - if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) - return ''; +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; - // We have enough bytes -> detect endianness. - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } - return this.decoder.write(buf); -}; + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} -Utf32AutoDecoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); +/** + * Colorize log arguments if enabled. + * + * @api public + */ - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - var trail = this.decoder.end(); - if (trail) - resStr += trail; + if (!this.useColors) { + return; + } - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - return this.decoder.end(); -}; + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); -function detectEncoding(bufs, defaultEncoding) { - var b = []; - var charsProcessed = 0; - var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. - var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. + args.splice(lastC, 0, c); +} - outer_loop: - for (var i = 0; i < bufs.length; i++) { - var buf = bufs[i]; - for (var j = 0; j < buf.length; j++) { - b.push(buf[j]); - if (b.length === 4) { - if (charsProcessed === 0) { - // Check BOM first. - if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { - return 'utf-32le'; - } - if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { - return 'utf-32be'; - } - } +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); - if (b[0] !== 0 || b[1] > 0x10) invalidBE++; - if (b[3] !== 0 || b[2] > 0x10) invalidLE++; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} - if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; - if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } - b.length = 0; - charsProcessed++; + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - if (charsProcessed >= 100) { - break outer_loop; - } - } - } - } + return r; +} - // Make decisions. - if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; - if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-32le'; +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } +module.exports = __nccwpck_require__(40897)(exports); -/***/ }), +const {formatters} = module.exports; -/***/ 28231: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -"use strict"; +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; -var Buffer = (__nccwpck_require__(12803).Buffer); -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 +/***/ }), -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; +/***/ 40897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ -// -- Encoding +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(70744); + createDebug.destroy = destroy; -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + /** + * The currently active debug mode names, and names to skip. + */ -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} + createDebug.names = []; + createDebug.skips = []; -Utf7Encoder.prototype.end = function() { -} + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; -// -- Decoding + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + const self = debug; - // The decoder is more involved as we must handle chunks in stream. + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii"); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + args[0] = createDebug.coerce(args[0]); - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - return res; -} + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + return debug; + } -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; + createDebug.names = []; + createDebug.skips = []; -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } -// -- Encoding + namespaces = split[i].replace(/\*/g, '.*?'); -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } + let i; + let len; - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } - } + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; + createDebug.enable(createDebug.load()); - return buf.slice(0, bufIdx); + return createDebug; } -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } +module.exports = setup; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } - return buf.slice(0, bufIdx); -} +/***/ }), +/***/ 2830: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// -- Decoding +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(6110); +} else { + module.exports = __nccwpck_require__(95108); } -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; +/***/ }), - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). +/***/ 95108: +/***/ ((module, exports, __nccwpck_require__) => { - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } +/** + * Module dependencies. + */ - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; +const tty = __nccwpck_require__(52018); +const util = __nccwpck_require__(39023); - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } +/** + * This is the Node.js implementation of `debug()`. + */ - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); +/** + * Colors. + */ - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } +exports.colors = [6, 2, 3, 4, 5, 1]; - this.inBase64 = inBase64; - this.base64Accum = base64Accum; +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(21450); - return res; + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - this.inBase64 = false; - this.base64Accum = ''; - return res; -} +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; +}, {}); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ -/***/ }), +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} -/***/ 74250: -/***/ ((__unused_webpack_module, exports) => { +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -"use strict"; +function formatArgs(args) { + const {namespace: name, useColors} = this; + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; -var BOMChar = '\uFEFF'; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; } -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ - return this.encoder.write(str); +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; +function load() { + return process.env.DEBUG; } -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; - - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - this.pass = true; - return res; -} +function init(debug) { + debug.inspectOpts = {}; -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } } +module.exports = __nccwpck_require__(40897)(exports); +const {formatters} = module.exports; -/***/ }), +/** + * Map %o to `util.inspect()`, all on a single line. + */ -/***/ 31748: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; -"use strict"; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; -var Buffer = (__nccwpck_require__(12803).Buffer); -var bomHandling = __nccwpck_require__(74250), - iconv = module.exports; +/***/ }), -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; +/***/ 14150: +/***/ ((__unused_webpack_module, exports) => { -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; +"use strict"; -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. - var encoder = iconv.getEncoder(encoding, options); +Object.defineProperty(exports, "__esModule", ({ value: true })); - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } + /* istanbul ignore next */ - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - var decoder = iconv.getDecoder(encoding, options); - - var res = decoder.write(buf); - var trail = decoder.end(); + this.name = 'Deprecation'; + } - return trail ? (res + trail) : res; } -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } -} +exports.Deprecation = Deprecation; -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(27585); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); +/***/ }), - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; +/***/ 24056: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var codecDef = iconv.encodings[enc]; +"use strict"; - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; +var iconvLite = __nccwpck_require__(31748); - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; +// Expose to the world +module.exports.C = convert; - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; +/** + * Convert encoding of an UTF-8 string or a buffer + * + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @return {Buffer} Encoded string + */ +function convert(str, to, from) { + from = checkEncoding(from || 'UTF-8'); + to = checkEncoding(to || 'UTF-8'); + str = str || ''; - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); + var result; + + if (from !== 'UTF-8' && typeof str === 'string') { + str = Buffer.from(str, 'binary'); + } + + if (from === to) { + if (typeof str === 'string') { + result = Buffer.from(str); + } else { + result = str; + } + } else { + try { + result = convertIconvLite(str, to, from); + } catch (E) { + console.error(E); + result = str; + } + } + + if (typeof result === 'string') { + result = Buffer.from(result, 'utf-8'); + } - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; + return result; +} - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } +/** + * Convert encoding of astring with iconv-lite + * + * @param {String|Buffer} str String to be converted + * @param {String} to Encoding to be converted to + * @param {String} [from='UTF-8'] Encoding to be converted from + * @return {Buffer} Encoded string + */ +function convertIconvLite(str, to, from) { + if (to === 'UTF-8') { + return iconvLite.decode(str, from); + } else if (from === 'UTF-8') { + return iconvLite.encode(str, to); + } else { + return iconvLite.encode(iconvLite.decode(str, from), to); } } -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +/** + * Converts charset name if needed + * + * @param {String} name Character set + * @return {String} Character set name + */ +function checkEncoding(name) { + return (name || '') + .toString() + .trim() + .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') + .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') + .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') + .replace(/^ks_c_5601\-1987$/i, 'CP949') + .replace(/^us[\-_]?ascii$/i, 'ASCII') + .toUpperCase(); } -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); +/***/ }), - return encoder; -} +/***/ 14339: +/***/ ((module) => { -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); +"use strict"; - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); - return decoder; -} +function assign(obj, props) { + for (const key in props) { + Object.defineProperty(obj, key, { + value: props[key], + enumerable: true, + configurable: true, + }); + } -// Streaming API -// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add -// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. -// If you would like to enable it explicitly, please add the following code to your app: -// > iconv.enableStreamingAPI(require('stream')); -iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) { - if (iconv.supportsStreams) - return; + return obj; +} - // Dependency-inject stream module to create IconvLite stream classes. - var streams = __nccwpck_require__(42281)(stream_module); +function createError(err, code, props) { + if (!err || typeof err === 'string') { + throw new TypeError('Please pass an Error to err-code'); + } - // Not public API yet, but expose the stream classes. - iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; + if (!props) { + props = {}; + } - // Streaming API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + if (typeof code === 'object') { + props = code; + code = undefined; } - iconv.decodeStream = function decodeStream(encoding, options) { - return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + if (code != null) { + props.code = code; } - iconv.supportsStreams = true; -} + try { + return assign(err, props); + } catch (_) { + props.message = err.message; + props.stack = err.stack; -// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). -var stream_module; -try { - stream_module = __nccwpck_require__(2203); -} catch (e) {} + const ErrClass = function () {}; -if (stream_module && stream_module.Transform) { - iconv.enableStreamingAPI(stream_module); + ErrClass.prototype = Object.create(Object.getPrototypeOf(err)); -} else { - // In rare cases where 'stream' module is not available by default, throw a helpful exception. - iconv.encodeStream = iconv.decodeStream = function() { - throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); - }; + return assign(new ErrClass(), props); + } } -if (false) {} +module.exports = createError; /***/ }), -/***/ 42281: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 25032: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +const { Minipass } = __nccwpck_require__(78275) +const EE = (__nccwpck_require__(24434).EventEmitter) +const fs = __nccwpck_require__(79896) -var Buffer = (__nccwpck_require__(12803).Buffer); +const writev = fs.writev -// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), -// we opt to dependency-inject it instead of creating a hard dependency. -module.exports = function(stream_module) { - var Transform = stream_module.Transform; +const _autoClose = Symbol('_autoClose') +const _close = Symbol('_close') +const _ended = Symbol('_ended') +const _fd = Symbol('_fd') +const _finished = Symbol('_finished') +const _flags = Symbol('_flags') +const _flush = Symbol('_flush') +const _handleChunk = Symbol('_handleChunk') +const _makeBuf = Symbol('_makeBuf') +const _mode = Symbol('_mode') +const _needDrain = Symbol('_needDrain') +const _onerror = Symbol('_onerror') +const _onopen = Symbol('_onopen') +const _onread = Symbol('_onread') +const _onwrite = Symbol('_onwrite') +const _open = Symbol('_open') +const _path = Symbol('_path') +const _pos = Symbol('_pos') +const _queue = Symbol('_queue') +const _read = Symbol('_read') +const _readSize = Symbol('_readSize') +const _reading = Symbol('_reading') +const _remain = Symbol('_remain') +const _size = Symbol('_size') +const _write = Symbol('_write') +const _writing = Symbol('_writing') +const _defaultFlag = Symbol('_defaultFlag') +const _errored = Symbol('_errored') - // == Encoder stream ======================================================= +class ReadStream extends Minipass { + constructor (path, opt) { + opt = opt || {} + super(opt) - function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); + this.readable = true + this.writable = false + + if (typeof path !== 'string') { + throw new TypeError('path must be a string') } - IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } - }); + this[_errored] = false + this[_fd] = typeof opt.fd === 'number' ? opt.fd : null + this[_path] = path + this[_readSize] = opt.readSize || 16 * 1024 * 1024 + this[_reading] = false + this[_size] = typeof opt.size === 'number' ? opt.size : Infinity + this[_remain] = this[_size] + this[_autoClose] = typeof opt.autoClose === 'boolean' ? + opt.autoClose : true - IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } + if (typeof this[_fd] === 'number') { + this[_read]() + } else { + this[_open]() } + } - IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } - } + get fd () { + return this[_fd] + } - IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; - } + get path () { + return this[_path] + } + write () { + throw new TypeError('this is a readable stream') + } - // == Decoder stream ======================================================= + end () { + throw new TypeError('this is a readable stream') + } - function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); + [_open] () { + fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd)) + } + + [_onopen] (er, fd) { + if (er) { + this[_onerror](er) + } else { + this[_fd] = fd + this.emit('open', fd) + this[_read]() } + } - IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } - }); + [_makeBuf] () { + return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain])) + } - IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } + [_read] () { + if (!this[_reading]) { + this[_reading] = true + const buf = this[_makeBuf]() + /* istanbul ignore if */ + if (buf.length === 0) { + return process.nextTick(() => this[_onread](null, 0, buf)) + } + fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => + this[_onread](er, br, b)) } + } - IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } + [_onread] (er, br, buf) { + this[_reading] = false + if (er) { + this[_onerror](er) + } else if (this[_handleChunk](br, buf)) { + this[_read]() } + } - IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } + } - return { - IconvLiteEncoderStream: IconvLiteEncoderStream, - IconvLiteDecoderStream: IconvLiteDecoderStream, - }; -}; - - -/***/ }), - -/***/ 72024: -/***/ ((module) => { - -/** - * @preserve - * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) - * - * @author Jens Taylor - * @see http://github.com/homebrewing/brauhaus-diff - * @author Gary Court - * @see http://github.com/garycourt/murmurhash-js - * @author Austin Appleby - * @see http://sites.google.com/site/murmurhash/ - */ -(function(){ - var cache; + [_onerror] (er) { + this[_reading] = true + this[_close]() + this.emit('error', er) + } - // Call this function without `new` to use the cached object (good for - // single-threaded environments), or with `new` to create a new object. - // - // @param {string} key A UTF-16 or ASCII string - // @param {number} seed An optional positive integer - // @return {object} A MurmurHash3 object for incremental hashing - function MurmurHash3(key, seed) { - var m = this instanceof MurmurHash3 ? this : cache; - m.reset(seed) - if (typeof key === 'string' && key.length > 0) { - m.hash(key); - } + [_handleChunk] (br, buf) { + let ret = false + // no effect if infinite + this[_remain] -= br + if (br > 0) { + ret = super.write(br < buf.length ? buf.slice(0, br) : buf) + } - if (m !== this) { - return m; - } - }; + if (br === 0 || this[_remain] <= 0) { + ret = false + this[_close]() + super.end() + } - // Incrementally add a string to this hash - // - // @param {string} key A UTF-16 or ASCII string - // @return {object} this - MurmurHash3.prototype.hash = function(key) { - var h1, k1, i, top, len; + return ret + } - len = key.length; - this.len += len; + emit (ev, data) { + switch (ev) { + case 'prefinish': + case 'finish': + break - k1 = this.k1; - i = 0; - switch (this.rem) { - case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; - case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; - case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; - case 3: - k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; - k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + case 'drain': + if (typeof this[_fd] === 'number') { + this[_read]() } + break - this.rem = (len + this.rem) & 3; // & 3 is same as % 4 - len -= this.rem; - if (len > 0) { - h1 = this.h1; - while (1) { - k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; - k1 = (k1 << 15) | (k1 >>> 17); - k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; - - h1 ^= k1; - h1 = (h1 << 13) | (h1 >>> 19); - h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; - - if (i >= len) { - break; - } - - k1 = ((key.charCodeAt(i++) & 0xffff)) ^ - ((key.charCodeAt(i++) & 0xffff) << 8) ^ - ((key.charCodeAt(i++) & 0xffff) << 16); - top = key.charCodeAt(i++); - k1 ^= ((top & 0xff) << 24) ^ - ((top & 0xff00) >> 8); - } - - k1 = 0; - switch (this.rem) { - case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; - case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; - case 1: k1 ^= (key.charCodeAt(i) & 0xffff); - } - - this.h1 = h1; + case 'error': + if (this[_errored]) { + return } + this[_errored] = true + return super.emit(ev, data) - this.k1 = k1; - return this; - }; - - // Get the result of this hash - // - // @return {number} The 32-bit hash - MurmurHash3.prototype.result = function() { - var k1, h1; - - k1 = this.k1; - h1 = this.h1; + default: + return super.emit(ev, data) + } + } +} - if (k1 > 0) { - k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; - k1 = (k1 << 15) | (k1 >>> 17); - k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; - h1 ^= k1; - } +class ReadStreamSync extends ReadStream { + [_open] () { + let threw = true + try { + this[_onopen](null, fs.openSync(this[_path], 'r')) + threw = false + } finally { + if (threw) { + this[_close]() + } + } + } - h1 ^= this.len; + [_read] () { + let threw = true + try { + if (!this[_reading]) { + this[_reading] = true + do { + const buf = this[_makeBuf]() + /* istanbul ignore next */ + const br = buf.length === 0 ? 0 + : fs.readSync(this[_fd], buf, 0, buf.length, null) + if (!this[_handleChunk](br, buf)) { + break + } + } while (true) + this[_reading] = false + } + threw = false + } finally { + if (threw) { + this[_close]() + } + } + } - h1 ^= h1 >>> 16; - h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; - h1 ^= h1 >>> 13; - h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; - h1 ^= h1 >>> 16; + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') + } + } +} - return h1 >>> 0; - }; +class WriteStream extends EE { + constructor (path, opt) { + opt = opt || {} + super(opt) + this.readable = false + this.writable = true + this[_errored] = false + this[_writing] = false + this[_ended] = false + this[_needDrain] = false + this[_queue] = [] + this[_path] = path + this[_fd] = typeof opt.fd === 'number' ? opt.fd : null + this[_mode] = opt.mode === undefined ? 0o666 : opt.mode + this[_pos] = typeof opt.start === 'number' ? opt.start : null + this[_autoClose] = typeof opt.autoClose === 'boolean' ? + opt.autoClose : true - // Reset the hash object for reuse - // - // @param {number} seed An optional positive integer - MurmurHash3.prototype.reset = function(seed) { - this.h1 = typeof seed === 'number' ? seed : 0; - this.rem = this.k1 = this.len = 0; - return this; - }; + // truncating makes no sense when writing into the middle + const defaultFlag = this[_pos] !== null ? 'r+' : 'w' + this[_defaultFlag] = opt.flags === undefined + this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags - // A cached object to use. This can be safely used if you're in a single- - // threaded environment, otherwise you need to create new hashes to use. - cache = new MurmurHash3(); + if (this[_fd] === null) { + this[_open]() + } + } - if (true) { - module.exports = MurmurHash3; - } else {} -}()); + emit (ev, data) { + if (ev === 'error') { + if (this[_errored]) { + return + } + this[_errored] = true + } + return super.emit(ev, data) + } + get fd () { + return this[_fd] + } -/***/ }), + get path () { + return this[_path] + } -/***/ 68850: -/***/ ((__unused_webpack_module, exports) => { + [_onerror] (er) { + this[_close]() + this[_writing] = true + this.emit('error', er) + } -"use strict"; + [_open] () { + fs.open(this[_path], this[_flags], this[_mode], + (er, fd) => this[_onopen](er, fd)) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AddressError = void 0; -class AddressError extends Error { - constructor(message, parseMessage) { - super(message); - this.name = 'AddressError'; - if (parseMessage !== null) { - this.parseMessage = parseMessage; - } + [_onopen] (er, fd) { + if (this[_defaultFlag] && + this[_flags] === 'r+' && + er && er.code === 'ENOENT') { + this[_flags] = 'w' + this[_open]() + } else if (er) { + this[_onerror](er) + } else { + this[_fd] = fd + this.emit('open', fd) + if (!this[_writing]) { + this[_flush]() + } } -} -exports.AddressError = AddressError; -//# sourceMappingURL=address-error.js.map - -/***/ }), + } -/***/ 45864: -/***/ ((__unused_webpack_module, exports) => { + end (buf, enc) { + if (buf) { + this.write(buf, enc) + } -"use strict"; + this[_ended] = true -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCorrect = exports.isInSubnet = void 0; -function isInSubnet(address) { - if (this.subnetMask < address.subnetMask) { - return false; - } - if (this.mask(address.subnetMask) === address.mask()) { - return true; + // synthetic after-write logic, where drain/finish live + if (!this[_writing] && !this[_queue].length && + typeof this[_fd] === 'number') { + this[_onwrite](null, 0) } - return false; -} -exports.isInSubnet = isInSubnet; -function isCorrect(defaultBits) { - return function () { - if (this.addressMinusSuffix !== this.correctForm()) { - return false; - } - if (this.subnetMask === defaultBits && !this.parsedSubnet) { - return true; - } - return this.parsedSubnet === String(this.subnetMask); - }; -} -exports.isCorrect = isCorrect; -//# sourceMappingURL=common.js.map - -/***/ }), + return this + } -/***/ 79253: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + write (buf, enc) { + if (typeof buf === 'string') { + buf = Buffer.from(buf, enc) + } -"use strict"; + if (this[_ended]) { + this.emit('error', new Error('write() after end()')) + return false + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + if (this[_fd] === null || this[_writing] || this[_queue].length) { + this[_queue].push(buf) + this[_needDrain] = true + return false } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; -const ipv4_1 = __nccwpck_require__(17946); -Object.defineProperty(exports, "Address4", ({ enumerable: true, get: function () { return ipv4_1.Address4; } })); -const ipv6_1 = __nccwpck_require__(38096); -Object.defineProperty(exports, "Address6", ({ enumerable: true, get: function () { return ipv6_1.Address6; } })); -const address_error_1 = __nccwpck_require__(68850); -Object.defineProperty(exports, "AddressError", ({ enumerable: true, get: function () { return address_error_1.AddressError; } })); -const helpers = __importStar(__nccwpck_require__(20339)); -exports.v6 = { helpers }; -//# sourceMappingURL=ip-address.js.map -/***/ }), + this[_writing] = true + this[_write](buf) + return true + } -/***/ 17946: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + [_write] (buf) { + fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => + this[_onwrite](er, bw)) + } -"use strict"; + [_onwrite] (er, bw) { + if (er) { + this[_onerror](er) + } else { + if (this[_pos] !== null) { + this[_pos] += bw + } + if (this[_queue].length) { + this[_flush]() + } else { + this[_writing] = false -/* eslint-disable no-param-reassign */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Address4 = void 0; -const common = __importStar(__nccwpck_require__(45864)); -const constants = __importStar(__nccwpck_require__(66437)); -const address_error_1 = __nccwpck_require__(68850); -const jsbn_1 = __nccwpck_require__(95947); -const sprintf_js_1 = __nccwpck_require__(72701); -/** - * Represents an IPv4 address - * @class Address4 - * @param {string} address - An IPv4 address string - */ -class Address4 { - constructor(address) { - this.groups = constants.GROUPS; - this.parsedAddress = []; - this.parsedSubnet = ''; - this.subnet = '/32'; - this.subnetMask = 32; - this.v4 = true; - /** - * Returns true if the address is correct, false otherwise - * @memberof Address4 - * @instance - * @returns {Boolean} - */ - this.isCorrect = common.isCorrect(constants.BITS); - /** - * Returns true if the given address is in the subnet of the current address - * @memberof Address4 - * @instance - * @returns {boolean} - */ - this.isInSubnet = common.isInSubnet; - this.address = address; - const subnet = constants.RE_SUBNET_STRING.exec(address); - if (subnet) { - this.parsedSubnet = subnet[0].replace('/', ''); - this.subnetMask = parseInt(this.parsedSubnet, 10); - this.subnet = `/${this.subnetMask}`; - if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { - throw new address_error_1.AddressError('Invalid subnet mask.'); - } - address = address.replace(constants.RE_SUBNET_STRING, ''); - } - this.addressMinusSuffix = address; - this.parsedAddress = this.parse(address); - } - static isValid(address) { - try { - // eslint-disable-next-line no-new - new Address4(address); - return true; - } - catch (e) { - return false; - } - } - /* - * Parses a v4 address - */ - parse(address) { - const groups = address.split('.'); - if (!address.match(constants.RE_ADDRESS)) { - throw new address_error_1.AddressError('Invalid IPv4 address.'); - } - return groups; - } - /** - * Returns the correct form of an address - * @memberof Address4 - * @instance - * @returns {String} - */ - correctForm() { - return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); - } - /** - * Converts a hex string to an IPv4 address object - * @memberof Address4 - * @static - * @param {string} hex - a hex string to convert - * @returns {Address4} - */ - static fromHex(hex) { - const padded = hex.replace(/:/g, '').padStart(8, '0'); - const groups = []; - let i; - for (i = 0; i < 8; i += 2) { - const h = padded.slice(i, i + 2); - groups.push(parseInt(h, 16)); - } - return new Address4(groups.join('.')); - } - /** - * Converts an integer into a IPv4 address object - * @memberof Address4 - * @static - * @param {integer} integer - a number to convert - * @returns {Address4} - */ - static fromInteger(integer) { - return Address4.fromHex(integer.toString(16)); - } - /** - * Return an address from in-addr.arpa form - * @memberof Address4 - * @static - * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address - * @returns {Adress4} - * @example - * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) - * address.correctForm(); // '192.0.2.42' - */ - static fromArpa(arpaFormAddress) { - // remove ending ".in-addr.arpa." or just "." - const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ''); - const address = leader.split('.').reverse().join('.'); - return new Address4(address); - } - /** - * Converts an IPv4 address object to a hex string - * @memberof Address4 - * @instance - * @returns {String} - */ - toHex() { - return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':'); - } - /** - * Converts an IPv4 address object to an array of bytes - * @memberof Address4 - * @instance - * @returns {Array} - */ - toArray() { - return this.parsedAddress.map((part) => parseInt(part, 10)); - } - /** - * Converts an IPv4 address object to an IPv6 address group - * @memberof Address4 - * @instance - * @returns {String} - */ - toGroup6() { - const output = []; - let i; - for (i = 0; i < constants.GROUPS; i += 2) { - const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10)); - output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16))); + if (this[_ended] && !this[_finished]) { + this[_finished] = true + this[_close]() + this.emit('finish') + } else if (this[_needDrain]) { + this[_needDrain] = false + this.emit('drain') } - return output.join(':'); - } - /** - * Returns the address as a BigInteger - * @memberof Address4 - * @instance - * @returns {BigInteger} - */ - bigInteger() { - return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16); - } - /** - * Helper function getting start address. - * @memberof Address4 - * @instance - * @returns {BigInteger} - */ - _startAddress() { - return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2); - } - /** - * The first address in the range given by this address' subnet. - * Often referred to as the Network Address. - * @memberof Address4 - * @instance - * @returns {Address4} - */ - startAddress() { - return Address4.fromBigInteger(this._startAddress()); - } - /** - * The first host address in the range given by this address's subnet ie - * the first address after the Network Address - * @memberof Address4 - * @instance - * @returns {Address4} - */ - startAddressExclusive() { - const adjust = new jsbn_1.BigInteger('1'); - return Address4.fromBigInteger(this._startAddress().add(adjust)); - } - /** - * Helper function getting end address. - * @memberof Address4 - * @instance - * @returns {BigInteger} - */ - _endAddress() { - return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2); - } - /** - * The last address in the range given by this address' subnet - * Often referred to as the Broadcast - * @memberof Address4 - * @instance - * @returns {Address4} - */ - endAddress() { - return Address4.fromBigInteger(this._endAddress()); + } } - /** - * The last host address in the range given by this address's subnet ie - * the last address prior to the Broadcast Address - * @memberof Address4 - * @instance - * @returns {Address4} - */ - endAddressExclusive() { - const adjust = new jsbn_1.BigInteger('1'); - return Address4.fromBigInteger(this._endAddress().subtract(adjust)); + } + + [_flush] () { + if (this[_queue].length === 0) { + if (this[_ended]) { + this[_onwrite](null, 0) + } + } else if (this[_queue].length === 1) { + this[_write](this[_queue].pop()) + } else { + const iovec = this[_queue] + this[_queue] = [] + writev(this[_fd], iovec, this[_pos], + (er, bw) => this[_onwrite](er, bw)) } - /** - * Converts a BigInteger to a v4 address object - * @memberof Address4 - * @static - * @param {BigInteger} bigInteger - a BigInteger to convert - * @returns {Address4} - */ - static fromBigInteger(bigInteger) { - return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); + } + + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.close(fd, er => er ? this.emit('error', er) : this.emit('close')) } - /** - * Returns the first n bits of the address, defaulting to the - * subnet mask - * @memberof Address4 - * @instance - * @returns {String} - */ - mask(mask) { - if (mask === undefined) { - mask = this.subnetMask; + } +} + +class WriteStreamSync extends WriteStream { + [_open] () { + let fd + // only wrap in a try{} block if we know we'll retry, to avoid + // the rethrow obscuring the error's source frame in most cases. + if (this[_defaultFlag] && this[_flags] === 'r+') { + try { + fd = fs.openSync(this[_path], this[_flags], this[_mode]) + } catch (er) { + if (er.code === 'ENOENT') { + this[_flags] = 'w' + return this[_open]() + } else { + throw er } - return this.getBitsBase2(0, mask); + } + } else { + fd = fs.openSync(this[_path], this[_flags], this[_mode]) } - /** - * Returns the bits in the given range as a base-2 string - * @memberof Address4 - * @instance - * @returns {string} - */ - getBitsBase2(start, end) { - return this.binaryZeroPad().slice(start, end); + + this[_onopen](null, fd) + } + + [_close] () { + if (this[_autoClose] && typeof this[_fd] === 'number') { + const fd = this[_fd] + this[_fd] = null + fs.closeSync(fd) + this.emit('close') } - /** - * Return the reversed ip6.arpa form of the address - * @memberof Address4 - * @param {Object} options - * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix - * @instance - * @returns {String} - */ - reverseForm(options) { - if (!options) { - options = {}; - } - const reversed = this.correctForm().split('.').reverse().join('.'); - if (options.omitSuffix) { - return reversed; + } + + [_write] (buf) { + // throw the original, but try to close if it fails + let threw = true + try { + this[_onwrite](null, + fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos])) + threw = false + } finally { + if (threw) { + try { + this[_close]() + } catch { + // ok error } - return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed); - } - /** - * Returns true if the given address is a multicast address - * @memberof Address4 - * @instance - * @returns {boolean} - */ - isMulticast() { - return this.isInSubnet(new Address4('224.0.0.0/4')); - } - /** - * Returns a zero-padded base-2 string representation of the address - * @memberof Address4 - * @instance - * @returns {string} - */ - binaryZeroPad() { - return this.bigInteger().toString(2).padStart(constants.BITS, '0'); - } - /** - * Groups an IPv4 address for inclusion at the end of an IPv6 address - * @returns {String} - */ - groupForV6() { - const segments = this.parsedAddress; - return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.'))); + } } + } } -exports.Address4 = Address4; -//# sourceMappingURL=ipv4.js.map + +exports.ReadStream = ReadStream +exports.ReadStreamSync = ReadStreamSync + +exports.WriteStream = WriteStream +exports.WriteStreamSync = WriteStreamSync + /***/ }), -/***/ 38096: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 83813: +/***/ ((module) => { "use strict"; -/* eslint-disable prefer-destructuring */ -/* eslint-disable no-param-reassign */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Address6 = void 0; -const common = __importStar(__nccwpck_require__(45864)); -const constants4 = __importStar(__nccwpck_require__(66437)); -const constants6 = __importStar(__nccwpck_require__(75280)); -const helpers = __importStar(__nccwpck_require__(20339)); -const ipv4_1 = __nccwpck_require__(17946); -const regular_expressions_1 = __nccwpck_require__(72016); -const address_error_1 = __nccwpck_require__(68850); -const jsbn_1 = __nccwpck_require__(95947); -const sprintf_js_1 = __nccwpck_require__(72701); -function assert(condition) { - if (!condition) { - throw new Error('Assertion failed.'); - } + + +/***/ }), + +/***/ 12203: +/***/ ((module) => { + +"use strict"; + +// rfc7231 6.1 +const statusCodeCacheableByDefault = new Set([ + 200, + 203, + 204, + 206, + 300, + 301, + 308, + 404, + 405, + 410, + 414, + 501, +]); + +// This implementation does not understand partial responses (206) +const understoodStatuses = new Set([ + 200, + 203, + 204, + 300, + 301, + 302, + 303, + 307, + 308, + 404, + 405, + 410, + 414, + 501, +]); + +const errorStatusCodes = new Set([ + 500, + 502, + 503, + 504, +]); + +const hopByHopHeaders = { + date: true, // included, because we add Age update Date + connection: true, + 'keep-alive': true, + 'proxy-authenticate': true, + 'proxy-authorization': true, + te: true, + trailer: true, + 'transfer-encoding': true, + upgrade: true, +}; + +const excludedFromRevalidationUpdate = { + // Since the old body is reused, it doesn't make sense to change properties of the body + 'content-length': true, + 'content-encoding': true, + 'transfer-encoding': true, + 'content-range': true, +}; + +function toNumberOrZero(s) { + const n = parseInt(s, 10); + return isFinite(n) ? n : 0; } -function addCommas(number) { - const r = /(\d+)(\d{3})/; - while (r.test(number)) { - number = number.replace(r, '$1,$2'); + +// RFC 5861 +function isErrorResponse(response) { + // consider undefined response as faulty + if(!response) { + return true } - return number; -} -function spanLeadingZeroes4(n) { - n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); - n = n.replace(/^(0{1,})(0)$/, '$1$2'); - return n; + return errorStatusCodes.has(response.status); } -/* - * A helper function to compact an array - */ -function compact(address, slice) { - const s1 = []; - const s2 = []; - let i; - for (i = 0; i < address.length; i++) { - if (i < slice[0]) { - s1.push(address[i]); - } - else if (i > slice[1]) { - s2.push(address[i]); - } + +function parseCacheControl(header) { + const cc = {}; + if (!header) return cc; + + // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives), + // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale + const parts = header.trim().split(/,/); + for (const part of parts) { + const [k, v] = part.split(/=/, 2); + cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, ''); } - return s1.concat(['compact']).concat(s2); -} -function paddedHex(octet) { - return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16)); -} -function unsignByte(b) { - // eslint-disable-next-line no-bitwise - return b & 0xff; + + return cc; } -/** - * Represents an IPv6 address - * @class Address6 - * @param {string} address - An IPv6 address string - * @param {number} [groups=8] - How many octets to parse - * @example - * var address = new Address6('2001::/32'); - */ -class Address6 { - constructor(address, optionalGroups) { - this.addressMinusSuffix = ''; - this.parsedSubnet = ''; - this.subnet = '/128'; - this.subnetMask = 128; - this.v4 = false; - this.zone = ''; - // #region Attributes - /** - * Returns true if the given address is in the subnet of the current address - * @memberof Address6 - * @instance - * @returns {boolean} - */ - this.isInSubnet = common.isInSubnet; - /** - * Returns true if the address is correct, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - this.isCorrect = common.isCorrect(constants6.BITS); - if (optionalGroups === undefined) { - this.groups = constants6.GROUPS; - } - else { - this.groups = optionalGroups; - } - this.address = address; - const subnet = constants6.RE_SUBNET_STRING.exec(address); - if (subnet) { - this.parsedSubnet = subnet[0].replace('/', ''); - this.subnetMask = parseInt(this.parsedSubnet, 10); - this.subnet = `/${this.subnetMask}`; - if (Number.isNaN(this.subnetMask) || - this.subnetMask < 0 || - this.subnetMask > constants6.BITS) { - throw new address_error_1.AddressError('Invalid subnet mask.'); - } - address = address.replace(constants6.RE_SUBNET_STRING, ''); - } - else if (/\//.test(address)) { - throw new address_error_1.AddressError('Invalid subnet mask.'); - } - const zone = constants6.RE_ZONE_STRING.exec(address); - if (zone) { - this.zone = zone[0]; - address = address.replace(constants6.RE_ZONE_STRING, ''); - } - this.addressMinusSuffix = address; - this.parsedAddress = this.parse(this.addressMinusSuffix); - } - static isValid(address) { - try { - // eslint-disable-next-line no-new - new Address6(address); - return true; - } - catch (e) { - return false; - } - } - /** - * Convert a BigInteger to a v6 address object - * @memberof Address6 - * @static - * @param {BigInteger} bigInteger - a BigInteger to convert - * @returns {Address6} - * @example - * var bigInteger = new BigInteger('1000000000000'); - * var address = Address6.fromBigInteger(bigInteger); - * address.correctForm(); // '::e8:d4a5:1000' - */ - static fromBigInteger(bigInteger) { - const hex = bigInteger.toString(16).padStart(32, '0'); - const groups = []; - let i; - for (i = 0; i < constants6.GROUPS; i++) { - groups.push(hex.slice(i * 4, (i + 1) * 4)); - } - return new Address6(groups.join(':')); - } - /** - * Convert a URL (with optional port number) to an address object - * @memberof Address6 - * @static - * @param {string} url - a URL with optional port number - * @example - * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); - * addressAndPort.address.correctForm(); // 'ffff::' - * addressAndPort.port; // 8080 - */ - static fromURL(url) { - let host; - let port = null; - let result; - // If we have brackets parse them and find a port - if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) { - result = constants6.RE_URL_WITH_PORT.exec(url); - if (result === null) { - return { - error: 'failed to parse address with port', - address: null, - port: null, - }; - } - host = result[1]; - port = result[2]; - // If there's a URL extract the address - } - else if (url.indexOf('/') !== -1) { - // Remove the protocol prefix - url = url.replace(/^[a-z0-9]+:\/\//, ''); - // Parse the address - result = constants6.RE_URL.exec(url); - if (result === null) { - return { - error: 'failed to parse address from URL', - address: null, - port: null, - }; - } - host = result[1]; - // Otherwise just assign the URL to the host and let the library parse it - } - else { - host = url; - } - // If there's a port convert it to an integer - if (port) { - port = parseInt(port, 10); - // squelch out of range ports - if (port < 0 || port > 65536) { - port = null; - } - } - else { - // Standardize `undefined` to `null` - port = null; - } - return { - address: new Address6(host), - port, - }; - } - /** - * Create an IPv6-mapped address given an IPv4 address - * @memberof Address6 - * @static - * @param {string} address - An IPv4 address string - * @returns {Address6} - * @example - * var address = Address6.fromAddress4('192.168.0.1'); - * address.correctForm(); // '::ffff:c0a8:1' - * address.to4in6(); // '::ffff:192.168.0.1' - */ - static fromAddress4(address) { - const address4 = new ipv4_1.Address4(address); - const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); - return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); - } - /** - * Return an address from ip6.arpa form - * @memberof Address6 - * @static - * @param {string} arpaFormAddress - an 'ip6.arpa' form address - * @returns {Adress6} - * @example - * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) - * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' - */ - static fromArpa(arpaFormAddress) { - // remove ending ".ip6.arpa." or just "." - let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ''); - const semicolonAmount = 7; - // correct ip6.arpa form with ending removed will be 63 characters - if (address.length !== 63) { - throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); - } - const parts = address.split('.').reverse(); - for (let i = semicolonAmount; i > 0; i--) { - const insertIndex = i * 4; - parts.splice(insertIndex, 0, ':'); - } - address = parts.join(''); - return new Address6(address); - } - /** - * Return the Microsoft UNC transcription of the address - * @memberof Address6 - * @instance - * @returns {String} the Microsoft UNC transcription of the address - */ - microsoftTranscription() { - return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-')); - } - /** - * Return the first n bits of the address, defaulting to the subnet mask - * @memberof Address6 - * @instance - * @param {number} [mask=subnet] - the number of bits to mask - * @returns {String} the first n bits of the address as a string - */ - mask(mask = this.subnetMask) { - return this.getBitsBase2(0, mask); - } - /** - * Return the number of possible subnets of a given size in the address - * @memberof Address6 - * @instance - * @param {number} [size=128] - the subnet size - * @returns {String} - */ - // TODO: probably useful to have a numeric version of this too - possibleSubnets(subnetSize = 128) { - const availableBits = constants6.BITS - this.subnetMask; - const subnetBits = Math.abs(subnetSize - constants6.BITS); - const subnetPowers = availableBits - subnetBits; - if (subnetPowers < 0) { - return '0'; - } - return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10)); - } - /** - * Helper function getting start address. - * @memberof Address6 - * @instance - * @returns {BigInteger} - */ - _startAddress() { - return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2); + +function formatCacheControl(cc) { + let parts = []; + for (const k in cc) { + const v = cc[k]; + parts.push(v === true ? k : k + '=' + v); } - /** - * The first address in the range given by this address' subnet - * Often referred to as the Network Address. - * @memberof Address6 - * @instance - * @returns {Address6} - */ - startAddress() { - return Address6.fromBigInteger(this._startAddress()); + if (!parts.length) { + return undefined; } - /** - * The first host address in the range given by this address's subnet ie - * the first address after the Network Address - * @memberof Address6 - * @instance - * @returns {Address6} - */ - startAddressExclusive() { - const adjust = new jsbn_1.BigInteger('1'); - return Address6.fromBigInteger(this._startAddress().add(adjust)); + return parts.join(', '); +} + +module.exports = class CachePolicy { + constructor( + req, + res, + { + shared, + cacheHeuristic, + immutableMinTimeToLive, + ignoreCargoCult, + _fromObject, + } = {} + ) { + if (_fromObject) { + this._fromObject(_fromObject); + return; + } + + if (!res || !res.headers) { + throw Error('Response headers missing'); + } + this._assertRequestHasHeaders(req); + + this._responseTime = this.now(); + this._isShared = shared !== false; + this._cacheHeuristic = + undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE + this._immutableMinTtl = + undefined !== immutableMinTimeToLive + ? immutableMinTimeToLive + : 24 * 3600 * 1000; + + this._status = 'status' in res ? res.status : 200; + this._resHeaders = res.headers; + this._rescc = parseCacheControl(res.headers['cache-control']); + this._method = 'method' in req ? req.method : 'GET'; + this._url = req.url; + this._host = req.headers.host; + this._noAuthorization = !req.headers.authorization; + this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used + this._reqcc = parseCacheControl(req.headers['cache-control']); + + // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching, + // so there's no point stricly adhering to the blindly copy&pasted directives. + if ( + ignoreCargoCult && + 'pre-check' in this._rescc && + 'post-check' in this._rescc + ) { + delete this._rescc['pre-check']; + delete this._rescc['post-check']; + delete this._rescc['no-cache']; + delete this._rescc['no-store']; + delete this._rescc['must-revalidate']; + this._resHeaders = Object.assign({}, this._resHeaders, { + 'cache-control': formatCacheControl(this._rescc), + }); + delete this._resHeaders.expires; + delete this._resHeaders.pragma; + } + + // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive + // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1). + if ( + res.headers['cache-control'] == null && + /no-cache/.test(res.headers.pragma) + ) { + this._rescc['no-cache'] = true; + } } - /** - * Helper function getting end address. - * @memberof Address6 - * @instance - * @returns {BigInteger} - */ - _endAddress() { - return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2); + + now() { + return Date.now(); } - /** - * The last address in the range given by this address' subnet - * Often referred to as the Broadcast - * @memberof Address6 - * @instance - * @returns {Address6} - */ - endAddress() { - return Address6.fromBigInteger(this._endAddress()); + + storable() { + // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it. + return !!( + !this._reqcc['no-store'] && + // A cache MUST NOT store a response to any request, unless: + // The request method is understood by the cache and defined as being cacheable, and + ('GET' === this._method || + 'HEAD' === this._method || + ('POST' === this._method && this._hasExplicitExpiration())) && + // the response status code is understood by the cache, and + understoodStatuses.has(this._status) && + // the "no-store" cache directive does not appear in request or response header fields, and + !this._rescc['no-store'] && + // the "private" response directive does not appear in the response, if the cache is shared, and + (!this._isShared || !this._rescc.private) && + // the Authorization header field does not appear in the request, if the cache is shared, + (!this._isShared || + this._noAuthorization || + this._allowsStoringAuthenticated()) && + // the response either: + // contains an Expires header field, or + (this._resHeaders.expires || + // contains a max-age response directive, or + // contains a s-maxage response directive and the cache is shared, or + // contains a public response directive. + this._rescc['max-age'] || + (this._isShared && this._rescc['s-maxage']) || + this._rescc.public || + // has a status code that is defined as cacheable by default + statusCodeCacheableByDefault.has(this._status)) + ); } - /** - * The last host address in the range given by this address's subnet ie - * the last address prior to the Broadcast Address - * @memberof Address6 - * @instance - * @returns {Address6} - */ - endAddressExclusive() { - const adjust = new jsbn_1.BigInteger('1'); - return Address6.fromBigInteger(this._endAddress().subtract(adjust)); + + _hasExplicitExpiration() { + // 4.2.1 Calculating Freshness Lifetime + return ( + (this._isShared && this._rescc['s-maxage']) || + this._rescc['max-age'] || + this._resHeaders.expires + ); } - /** - * Return the scope of the address - * @memberof Address6 - * @instance - * @returns {String} - */ - getScope() { - let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; - if (this.getType() === 'Global unicast' && scope !== 'Link local') { - scope = 'Global'; + + _assertRequestHasHeaders(req) { + if (!req || !req.headers) { + throw Error('Request headers missing'); } - return scope || 'Unknown'; } - /** - * Return the type of the address - * @memberof Address6 - * @instance - * @returns {String} - */ - getType() { - for (const subnet of Object.keys(constants6.TYPES)) { - if (this.isInSubnet(new Address6(subnet))) { - return constants6.TYPES[subnet]; + + satisfiesWithoutRevalidation(req) { + this._assertRequestHasHeaders(req); + + // When presented with a request, a cache MUST NOT reuse a stored response, unless: + // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive, + // unless the stored response is successfully validated (Section 4.3), and + const requestCC = parseCacheControl(req.headers['cache-control']); + if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) { + return false; + } + + if (requestCC['max-age'] && this.age() > requestCC['max-age']) { + return false; + } + + if ( + requestCC['min-fresh'] && + this.timeToLive() < 1000 * requestCC['min-fresh'] + ) { + return false; + } + + // the stored response is either: + // fresh, or allowed to be served stale + if (this.stale()) { + const allowsStale = + requestCC['max-stale'] && + !this._rescc['must-revalidate'] && + (true === requestCC['max-stale'] || + requestCC['max-stale'] > this.age() - this.maxAge()); + if (!allowsStale) { + return false; } } - return 'Global unicast'; + + return this._requestMatches(req, false); } - /** - * Return the bits in the given range as a BigInteger - * @memberof Address6 - * @instance - * @returns {BigInteger} - */ - getBits(start, end) { - return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); + + _requestMatches(req, allowHeadMethod) { + // The presented effective request URI and that of the stored response match, and + return ( + (!this._url || this._url === req.url) && + this._host === req.headers.host && + // the request method associated with the stored response allows it to be used for the presented request, and + (!req.method || + this._method === req.method || + (allowHeadMethod && 'HEAD' === req.method)) && + // selecting header fields nominated by the stored response (if any) match those presented, and + this._varyMatches(req) + ); } - /** - * Return the bits in the given range as a base-2 string - * @memberof Address6 - * @instance - * @returns {String} - */ - getBitsBase2(start, end) { - return this.binaryZeroPad().slice(start, end); + + _allowsStoringAuthenticated() { + // following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage. + return ( + this._rescc['must-revalidate'] || + this._rescc.public || + this._rescc['s-maxage'] + ); } - /** - * Return the bits in the given range as a base-16 string - * @memberof Address6 - * @instance - * @returns {String} - */ - getBitsBase16(start, end) { - const length = end - start; - if (length % 4 !== 0) { - throw new Error('Length of bits to retrieve must be divisible by four'); + + _varyMatches(req) { + if (!this._resHeaders.vary) { + return true; } - return this.getBits(start, end) - .toString(16) - .padStart(length / 4, '0'); - } - /** - * Return the bits that are set past the subnet mask length - * @memberof Address6 - * @instance - * @returns {String} - */ - getBitsPastSubnet() { - return this.getBitsBase2(this.subnetMask, constants6.BITS); + + // A Vary header field-value of "*" always fails to match + if (this._resHeaders.vary === '*') { + return false; + } + + const fields = this._resHeaders.vary + .trim() + .toLowerCase() + .split(/\s*,\s*/); + for (const name of fields) { + if (req.headers[name] !== this._reqHeaders[name]) return false; + } + return true; } - /** - * Return the reversed ip6.arpa form of the address - * @memberof Address6 - * @param {Object} options - * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix - * @instance - * @returns {String} - */ - reverseForm(options) { - if (!options) { - options = {}; + + _copyWithoutHopByHopHeaders(inHeaders) { + const headers = {}; + for (const name in inHeaders) { + if (hopByHopHeaders[name]) continue; + headers[name] = inHeaders[name]; } - const characters = Math.floor(this.subnetMask / 4); - const reversed = this.canonicalForm() - .replace(/:/g, '') - .split('') - .slice(0, characters) - .reverse() - .join('.'); - if (characters > 0) { - if (options.omitSuffix) { - return reversed; + // 9.1. Connection + if (inHeaders.connection) { + const tokens = inHeaders.connection.trim().split(/\s*,\s*/); + for (const name of tokens) { + delete headers[name]; } - return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed); } - if (options.omitSuffix) { - return ''; + if (headers.warning) { + const warnings = headers.warning.split(/,/).filter(warning => { + return !/^\s*1[0-9][0-9]/.test(warning); + }); + if (!warnings.length) { + delete headers.warning; + } else { + headers.warning = warnings.join(',').trim(); + } } - return 'ip6.arpa.'; + return headers; + } + + responseHeaders() { + const headers = this._copyWithoutHopByHopHeaders(this._resHeaders); + const age = this.age(); + + // A cache SHOULD generate 113 warning if it heuristically chose a freshness + // lifetime greater than 24 hours and the response's age is greater than 24 hours. + if ( + age > 3600 * 24 && + !this._hasExplicitExpiration() && + this.maxAge() > 3600 * 24 + ) { + headers.warning = + (headers.warning ? `${headers.warning}, ` : '') + + '113 - "rfc7234 5.5.4"'; + } + headers.age = `${Math.round(age)}`; + headers.date = new Date(this.now()).toUTCString(); + return headers; } + /** - * Return the correct form of the address - * @memberof Address6 - * @instance - * @returns {String} + * Value of the Date response header or current time if Date was invalid + * @return timestamp */ - correctForm() { - let i; - let groups = []; - let zeroCounter = 0; - const zeroes = []; - for (i = 0; i < this.parsedAddress.length; i++) { - const value = parseInt(this.parsedAddress[i], 16); - if (value === 0) { - zeroCounter++; - } - if (value !== 0 && zeroCounter > 0) { - if (zeroCounter > 1) { - zeroes.push([i - zeroCounter, i - 1]); - } - zeroCounter = 0; - } - } - // Do we end with a string of zeroes? - if (zeroCounter > 1) { - zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); - } - const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); - if (zeroes.length > 0) { - const index = zeroLengths.indexOf(Math.max(...zeroLengths)); - groups = compact(this.parsedAddress, zeroes[index]); - } - else { - groups = this.parsedAddress; - } - for (i = 0; i < groups.length; i++) { - if (groups[i] !== 'compact') { - groups[i] = parseInt(groups[i], 16).toString(16); - } + date() { + const serverDate = Date.parse(this._resHeaders.date); + if (isFinite(serverDate)) { + return serverDate; } - let correct = groups.join(':'); - correct = correct.replace(/^compact$/, '::'); - correct = correct.replace(/^compact|compact$/, ':'); - correct = correct.replace(/compact/, ''); - return correct; + return this._responseTime; } + /** - * Return a zero-padded base-2 string representation of the address - * @memberof Address6 - * @instance - * @returns {String} - * @example - * var address = new Address6('2001:4860:4001:803::1011'); - * address.binaryZeroPad(); - * // '0010000000000001010010000110000001000000000000010000100000000011 - * // 0000000000000000000000000000000000000000000000000001000000010001' + * Value of the Age header, in seconds, updated for the current time. + * May be fractional. + * + * @return Number */ - binaryZeroPad() { - return this.bigInteger().toString(2).padStart(constants6.BITS, '0'); + age() { + let age = this._ageValue(); + + const residentTime = (this.now() - this._responseTime) / 1000; + return age + residentTime; } - // TODO: Improve the semantics of this helper function - parse4in6(address) { - const groups = address.split(':'); - const lastGroup = groups.slice(-1)[0]; - const address4 = lastGroup.match(constants4.RE_ADDRESS); - if (address4) { - this.parsedAddress4 = address4[0]; - this.address4 = new ipv4_1.Address4(this.parsedAddress4); - for (let i = 0; i < this.address4.groups; i++) { - if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { - throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'))); - } - } - this.v4 = true; - groups[groups.length - 1] = this.address4.toGroup6(); - address = groups.join(':'); - } - return address; + + _ageValue() { + return toNumberOrZero(this._resHeaders.age); } - // TODO: Make private? - parse(address) { - address = this.parse4in6(address); - const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); - if (badCharacters) { - throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '$1')); + + /** + * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`. + * + * For an up-to-date value, see `timeToLive()`. + * + * @return Number + */ + maxAge() { + if (!this.storable() || this._rescc['no-cache']) { + return 0; } - const badAddress = address.match(constants6.RE_BAD_ADDRESS); - if (badAddress) { - throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '$1')); + + // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default + // so this implementation requires explicit opt-in via public header + if ( + this._isShared && + (this._resHeaders['set-cookie'] && + !this._rescc.public && + !this._rescc.immutable) + ) { + return 0; } - let groups = []; - const halves = address.split('::'); - if (halves.length === 2) { - let first = halves[0].split(':'); - let last = halves[1].split(':'); - if (first.length === 1 && first[0] === '') { - first = []; - } - if (last.length === 1 && last[0] === '') { - last = []; - } - const remaining = this.groups - (first.length + last.length); - if (!remaining) { - throw new address_error_1.AddressError('Error parsing groups'); + + if (this._resHeaders.vary === '*') { + return 0; + } + + if (this._isShared) { + if (this._rescc['proxy-revalidate']) { + return 0; } - this.elidedGroups = remaining; - this.elisionBegin = first.length; - this.elisionEnd = first.length + this.elidedGroups; - groups = groups.concat(first); - for (let i = 0; i < remaining; i++) { - groups.push('0'); + // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field. + if (this._rescc['s-maxage']) { + return toNumberOrZero(this._rescc['s-maxage']); } - groups = groups.concat(last); } - else if (halves.length === 1) { - groups = address.split(':'); - this.elidedGroups = 0; + + // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field. + if (this._rescc['max-age']) { + return toNumberOrZero(this._rescc['max-age']); } - else { - throw new address_error_1.AddressError('Too many :: groups found'); + + const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0; + + const serverDate = this.date(); + if (this._resHeaders.expires) { + const expires = Date.parse(this._resHeaders.expires); + // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired"). + if (Number.isNaN(expires) || expires < serverDate) { + return 0; + } + return Math.max(defaultMinTtl, (expires - serverDate) / 1000); } - groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16))); - if (groups.length !== this.groups) { - throw new address_error_1.AddressError('Incorrect number of groups found'); + + if (this._resHeaders['last-modified']) { + const lastModified = Date.parse(this._resHeaders['last-modified']); + if (isFinite(lastModified) && serverDate > lastModified) { + return Math.max( + defaultMinTtl, + ((serverDate - lastModified) / 1000) * this._cacheHeuristic + ); + } } - return groups; + + return defaultMinTtl; } - /** - * Return the canonical form of the address - * @memberof Address6 - * @instance - * @returns {String} - */ - canonicalForm() { - return this.parsedAddress.map(paddedHex).join(':'); + + timeToLive() { + const age = this.maxAge() - this.age(); + const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']); + const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']); + return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000; } - /** - * Return the decimal form of the address - * @memberof Address6 - * @instance - * @returns {String} - */ - decimal() { - return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':'); + + stale() { + return this.maxAge() <= this.age(); } - /** - * Return the address as a BigInteger - * @memberof Address6 - * @instance - * @returns {BigInteger} - */ - bigInteger() { - return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16); + + _useStaleIfError() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age(); } - /** - * Return the last two groups of this address as an IPv4 address string - * @memberof Address6 - * @instance - * @returns {Address4} - * @example - * var address = new Address6('2001:4860:4001::1825:bf11'); - * address.to4().correctForm(); // '24.37.191.17' - */ - to4() { - const binary = this.binaryZeroPad().split(''); - return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16)); + + useStaleWhileRevalidate() { + return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age(); + } + + static fromObject(obj) { + return new this(undefined, undefined, { _fromObject: obj }); + } + + _fromObject(obj) { + if (this._responseTime) throw Error('Reinitialized'); + if (!obj || obj.v !== 1) throw Error('Invalid serialization'); + + this._responseTime = obj.t; + this._isShared = obj.sh; + this._cacheHeuristic = obj.ch; + this._immutableMinTtl = + obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000; + this._status = obj.st; + this._resHeaders = obj.resh; + this._rescc = obj.rescc; + this._method = obj.m; + this._url = obj.u; + this._host = obj.h; + this._noAuthorization = obj.a; + this._reqHeaders = obj.reqh; + this._reqcc = obj.reqcc; + } + + toObject() { + return { + v: 1, + t: this._responseTime, + sh: this._isShared, + ch: this._cacheHeuristic, + imm: this._immutableMinTtl, + st: this._status, + resh: this._resHeaders, + rescc: this._rescc, + m: this._method, + u: this._url, + h: this._host, + a: this._noAuthorization, + reqh: this._reqHeaders, + reqcc: this._reqcc, + }; } + /** - * Return the v4-in-v6 form of the address - * @memberof Address6 - * @instance - * @returns {String} + * Headers for sending to the origin server to revalidate stale response. + * Allows server to return 304 to allow reuse of the previous response. + * + * Hop by hop headers are always stripped. + * Revalidation headers may be added or removed, depending on request. */ - to4in6() { - const address4 = this.to4(); - const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6); - const correct = address6.correctForm(); - let infix = ''; - if (!/:$/.test(correct)) { - infix = ':'; + revalidationHeaders(incomingReq) { + this._assertRequestHasHeaders(incomingReq); + const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers); + + // This implementation does not understand range requests + delete headers['if-range']; + + if (!this._requestMatches(incomingReq, true) || !this.storable()) { + // revalidation allowed via HEAD + // not for the same resource, or wasn't allowed to be cached anyway + delete headers['if-none-match']; + delete headers['if-modified-since']; + return headers; } - return correct + infix + address4.address; + + /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */ + if (this._resHeaders.etag) { + headers['if-none-match'] = headers['if-none-match'] + ? `${headers['if-none-match']}, ${this._resHeaders.etag}` + : this._resHeaders.etag; + } + + // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request. + const forbidsWeakValidators = + headers['accept-ranges'] || + headers['if-match'] || + headers['if-unmodified-since'] || + (this._method && this._method != 'GET'); + + /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server. + Note: This implementation does not understand partial responses (206) */ + if (forbidsWeakValidators) { + delete headers['if-modified-since']; + + if (headers['if-none-match']) { + const etags = headers['if-none-match'] + .split(/,/) + .filter(etag => { + return !/^\s*W\//.test(etag); + }); + if (!etags.length) { + delete headers['if-none-match']; + } else { + headers['if-none-match'] = etags.join(',').trim(); + } + } + } else if ( + this._resHeaders['last-modified'] && + !headers['if-modified-since'] + ) { + headers['if-modified-since'] = this._resHeaders['last-modified']; + } + + return headers; } + /** - * Return an object containing the Teredo properties of the address - * @memberof Address6 - * @instance - * @returns {Object} + * Creates new CachePolicy with information combined from the previews response, + * and the new revalidation response. + * + * Returns {policy, modified} where modified is a boolean indicating + * whether the response body has been modified, and old cached body can't be used. + * + * @return {Object} {policy: CachePolicy, modified: Boolean} */ - inspectTeredo() { - /* - - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32). - - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that - is used. - - Bits 64 to 79 can be used to define some flags. Currently only the - higher order bit is used; it is set to 1 if the Teredo client is - located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista - and Windows Server 2008 implementations, more bits are used. In those - implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA", - where "C" remains the "Cone" flag. The "R" bit is reserved for future - use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit - is Individual/Group flag (set to 0). The A bits are set to a 12-bit - randomly generated number chosen by the Teredo client to introduce - additional protection for the Teredo node against IPv6-based scanning - attacks. - - Bits 80 to 95 contains the obfuscated UDP port number. This is the - port number that is mapped by the NAT to the Teredo client with all - bits inverted. - - Bits 96 to 127 contains the obfuscated IPv4 address. This is the - public IPv4 address of the NAT with all bits inverted. - */ - const prefix = this.getBitsBase16(0, 32); - const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString(); - const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); - const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16)); - const flags = this.getBits(64, 80); - const flagsBase2 = this.getBitsBase2(64, 80); - const coneNat = flags.testBit(15); - const reserved = flags.testBit(14); - const groupIndividual = flags.testBit(8); - const universalLocal = flags.testBit(9); - const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10); + revalidatedPolicy(request, response) { + this._assertRequestHasHeaders(request); + if(this._useStaleIfError() && isErrorResponse(response)) { // I consider the revalidation request unsuccessful + return { + modified: false, + matches: false, + policy: this, + }; + } + if (!response || !response.headers) { + throw Error('Response headers missing'); + } + + // These aren't going to be supported exactly, since one CachePolicy object + // doesn't know about all the other cached objects. + let matches = false; + if (response.status !== undefined && response.status != 304) { + matches = false; + } else if ( + response.headers.etag && + !/^\s*W\//.test(response.headers.etag) + ) { + // "All of the stored responses with the same strong validator are selected. + // If none of the stored responses contain the same strong validator, + // then the cache MUST NOT use the new response to update any stored responses." + matches = + this._resHeaders.etag && + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag; + } else if (this._resHeaders.etag && response.headers.etag) { + // "If the new response contains a weak validator and that validator corresponds + // to one of the cache's stored responses, + // then the most recent of those matching stored responses is selected for update." + matches = + this._resHeaders.etag.replace(/^\s*W\//, '') === + response.headers.etag.replace(/^\s*W\//, ''); + } else if (this._resHeaders['last-modified']) { + matches = + this._resHeaders['last-modified'] === + response.headers['last-modified']; + } else { + // If the new response does not include any form of validator (such as in the case where + // a client generates an If-Modified-Since request from a source other than the Last-Modified + // response header field), and there is only one stored response, and that stored response also + // lacks a validator, then that stored response is selected for update. + if ( + !this._resHeaders.etag && + !this._resHeaders['last-modified'] && + !response.headers.etag && + !response.headers['last-modified'] + ) { + matches = true; + } + } + + if (!matches) { + return { + policy: new this.constructor(request, response), + // Client receiving 304 without body, even if it's invalid/mismatched has no option + // but to reuse a cached body. We don't have a good way to tell clients to do + // error recovery in such case. + modified: response.status != 304, + matches: false, + }; + } + + // use other header fields provided in the 304 (Not Modified) response to replace all instances + // of the corresponding header fields in the stored response. + const headers = {}; + for (const k in this._resHeaders) { + headers[k] = + k in response.headers && !excludedFromRevalidationUpdate[k] + ? response.headers[k] + : this._resHeaders[k]; + } + + const newResponse = Object.assign({}, response, { + status: this._status, + method: this._method, + headers, + }); return { - prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)), - server4: server4.address, - client4: client4.address, - flags: flagsBase2, - coneNat, - microsoft: { - reserved, - universalLocal, - groupIndividual, - nonce, - }, - udpPort, + policy: new this.constructor(request, newResponse, { + shared: this._isShared, + cacheHeuristic: this._cacheHeuristic, + immutableMinTimeToLive: this._immutableMinTtl, + }), + modified: false, + matches: true, }; } - /** - * Return an object containing the 6to4 properties of the address - * @memberof Address6 - * @instance - * @returns {Object} - */ - inspect6to4() { - /* - - Bits 0 to 15 are set to the 6to4 prefix (2002::/16). - - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used. - */ - const prefix = this.getBitsBase16(0, 16); - const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); - return { - prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)), - gateway: gateway.address, +}; + + +/***/ }), + +/***/ 81970: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpProxyAgent = void 0; +const net = __importStar(__nccwpck_require__(69278)); +const tls = __importStar(__nccwpck_require__(64756)); +const debug_1 = __importDefault(__nccwpck_require__(2830)); +const events_1 = __nccwpck_require__(24434); +const agent_base_1 = __nccwpck_require__(98894); +const url_1 = __nccwpck_require__(87016); +const debug = (0, debug_1.default)('http-proxy-agent'); +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + */ +class HttpProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + ...(opts ? omit(opts, 'headers') : null), + host, + port, }; } - /** - * Return a v6 6to4 address from a v6 v4inv6 address - * @memberof Address6 - * @instance - * @returns {Address6} - */ - to6to4() { - if (!this.is4()) { - return null; + addRequest(req, opts) { + req._header = null; + this.setRequestProps(req, opts); + // @ts-expect-error `addRequest()` isn't defined in `@types/node` + super.addRequest(req, opts); + } + setRequestProps(req, opts) { + const { proxy } = this; + const protocol = opts.secureEndpoint ? 'https:' : 'http:'; + const hostname = req.getHeader('host') || 'localhost'; + const base = `${protocol}//${hostname}`; + const url = new url_1.URL(req.path, base); + if (opts.port !== 80) { + url.port = String(opts.port); + } + // Change the `http.ClientRequest` instance's "path" field + // to the absolute path of the URL that will be requested. + req.path = String(url); + // Inject the `Proxy-Authorization` header if necessary. + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + const value = headers[name]; + if (value) { + req.setHeader(name, value); + } + } + } + async connect(req, opts) { + req._header = null; + if (!req.path.includes('://')) { + this.setRequestProps(req, opts); + } + // At this point, the http ClientRequest's internal `_header` field + // might have already been set. If this is the case then we'll need + // to re-generate the string since we just changed the `req.path`. + let first; + let endOfHeaders; + debug('Regenerating stored HTTP header string for request'); + req._implicitHeader(); + if (req.outputData && req.outputData.length > 0) { + debug('Patching connection write() output buffer with updated header'); + first = req.outputData[0].data; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.outputData[0].data = + req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.outputData[0].data); + } + // Create a socket connection to the proxy server. + let socket; + if (this.proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + socket = tls.connect(this.connectOpts); + } + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); } - const addr6to4 = [ - '2002', - this.getBitsBase16(96, 112), - this.getBitsBase16(112, 128), - '', - '/16', - ].join(':'); - return new Address6(addr6to4); + // Wait for the socket's `connect` event, so that this `callback()` + // function throws instead of the `http` request machinery. This is + // important for i.e. `PacProxyAgent` which determines a failed proxy + // connection via the `callback()` function throwing. + await (0, events_1.once)(socket, 'connect'); + return socket; } - /** - * Return a byte array - * @memberof Address6 - * @instance - * @returns {Array} - */ - toByteArray() { - const byteArray = this.bigInteger().toByteArray(); - // work around issue where `toByteArray` returns a leading 0 element - if (byteArray.length === 17 && byteArray[0] === 0) { - return byteArray.slice(1); +} +HttpProxyAgent.protocols = ['http', 'https']; +exports.HttpProxyAgent = HttpProxyAgent; +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; } - return byteArray; } - /** - * Return an unsigned byte array - * @memberof Address6 - * @instance - * @returns {Array} - */ - toUnsignedByteArray() { - return this.toByteArray().map(unsignByte); + return ret; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 3669: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - /** - * Convert a byte array to an Address6 object - * @memberof Address6 - * @static - * @returns {Address6} - */ - static fromByteArray(bytes) { - return this.fromUnsignedByteArray(bytes.map(unsignByte)); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpsProxyAgent = void 0; +const net = __importStar(__nccwpck_require__(69278)); +const tls = __importStar(__nccwpck_require__(64756)); +const assert_1 = __importDefault(__nccwpck_require__(42613)); +const debug_1 = __importDefault(__nccwpck_require__(2830)); +const agent_base_1 = __nccwpck_require__(98894); +const url_1 = __nccwpck_require__(87016); +const parse_proxy_response_1 = __nccwpck_require__(37943); +const debug = (0, debug_1.default)('https-proxy-agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href); + // Trim off the brackets from IPv6 addresses + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ''); + const port = this.proxy.port + ? parseInt(this.proxy.port, 10) + : this.proxy.protocol === 'https:' + ? 443 + : 80; + this.connectOpts = { + // Attempt to negotiate http/1.1 for proxy servers that support http/2 + ALPNProtocols: ['http/1.1'], + ...(opts ? omit(opts, 'headers') : null), + host, + port, + }; } /** - * Convert an unsigned byte array to an Address6 object - * @memberof Address6 - * @static - * @returns {Address6} + * Called when the node-core HTTP client library is creating a + * new HTTP request. */ - static fromUnsignedByteArray(bytes) { - const BYTE_MAX = new jsbn_1.BigInteger('256', 10); - let result = new jsbn_1.BigInteger('0', 10); - let multiplier = new jsbn_1.BigInteger('1', 10); - for (let i = bytes.length - 1; i >= 0; i--) { - result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10))); - multiplier = multiplier.multiply(BYTE_MAX); + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); } - return Address6.fromBigInteger(result); - } - /** - * Returns true if the address is in the canonical form, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - isCanonical() { - return this.addressMinusSuffix === this.canonicalForm(); - } - /** - * Returns true if the address is a link local address, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - isLinkLocal() { - // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10' - if (this.getBitsBase2(0, 64) === - '1111111010000000000000000000000000000000000000000000000000000000') { - return true; + // Create a socket connection to the proxy server. + let socket; + if (proxy.protocol === 'https:') { + debug('Creating `tls.Socket`: %o', this.connectOpts); + const servername = this.connectOpts.servername || this.connectOpts.host; + socket = tls.connect({ + ...this.connectOpts, + servername, + }); } - return false; - } - /** - * Returns true if the address is a multicast address, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - isMulticast() { - return this.getType() === 'Multicast'; - } - /** - * Returns true if the address is a v4-in-v6 address, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - is4() { - return this.v4; - } - /** - * Returns true if the address is a Teredo address, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - isTeredo() { - return this.isInSubnet(new Address6('2001::/32')); - } - /** - * Returns true if the address is a 6to4 address, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - is6to4() { - return this.isInSubnet(new Address6('2002::/16')); + else { + debug('Creating `net.Socket`: %o', this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === 'function' + ? this.proxyHeaders() + : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers['Proxy-Connection']) { + headers['Proxy-Connection'] = this.keepAlive + ? 'Keep-Alive' + : 'close'; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r\n`); + const { connect, buffered } = await proxyResponsePromise; + req.emit('proxyConnect', connect); + this.emit('proxyConnect', connect, req); + if (connect.statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls.connect({ + ...omit(opts, 'host', 'path', 'port'), + socket, + servername, + }); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('Replaying proxy buffer for failed request'); + (0, assert_1.default)(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; } - /** - * Returns true if the address is a loopback address, false otherwise - * @memberof Address6 - * @instance - * @returns {boolean} - */ - isLoopback() { - return this.getType() === 'Loopback'; +} +HttpsProxyAgent.protocols = ['http', 'https']; +exports.HttpsProxyAgent = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } } - // #endregion - // #region HTML - /** - * @returns {String} the address in link form with a default port of 80 - */ - href(optionalPort) { - if (optionalPort === undefined) { - optionalPort = ''; + return ret; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 37943: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseProxyResponse = void 0; +const debug_1 = __importDefault(__nccwpck_require__(2830)); +const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); } - else { - optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort); + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('readable', read); + } + function onend() { + cleanup(); + debug('onend'); + reject(new Error('Proxy connection ended before receiving CONNECT response')); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const headerParts = buffered + .slice(0, endOfHeaders) + .toString('ascii') + .split('\r\n'); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error('No header received from proxy CONNECT response')); + } + const firstLineParts = firstLine.split(' '); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(' '); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(':'); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === 'string') { + headers[key] = [current, value]; + } + else if (Array.isArray(current)) { + current.push(value); + } + else { + headers[key] = value; + } + } + debug('got proxy server response: %o %o', firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers, + }, + buffered, + }); + } + socket.on('error', onerror); + socket.on('end', onend); + read(); + }); +} +exports.parseProxyResponse = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map + +/***/ }), + +/***/ 7978: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = (__nccwpck_require__(12803).Buffer); + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 common decode nodes. + var commonThirdByteNodeIdx = this.decodeTables.length; + this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + + var commonFourthByteNodeIdx = this.decodeTables.length; + this.decodeTables.push(UNASSIGNED_NODE.slice(0)); + + // Fill out the tree + var firstByteNode = this.decodeTables[0]; + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]]; + for (var j = 0x30; j <= 0x39; j++) { + if (secondByteNode[j] === UNASSIGNED) { + secondByteNode[j] = NODE_START - commonThirdByteNodeIdx; + } else if (secondByteNode[j] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 2"); + } + + var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]]; + for (var k = 0x81; k <= 0xFE; k++) { + if (thirdByteNode[k] === UNASSIGNED) { + thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx; + } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) { + continue; + } else if (thirdByteNode[k] > NODE_START) { + throw new Error("gb18030 decode tables conflict at byte 3"); + } + + var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]]; + for (var l = 0x30; l <= 0x39; l++) { + if (fourthByteNode[l] === UNASSIGNED) + fourthByteNode[l] = GB18030_CODE; + } + } + } } - return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort); } - /** - * @returns {String} a link suitable for conveying the address via a URL hash - */ - link(options) { - if (!options) { - options = {}; - } - if (options.className === undefined) { - options.className = ''; - } - if (options.prefix === undefined) { - options.prefix = '/#address='; - } - if (options.v4 === undefined) { - options.v4 = false; - } - let formFunction = this.correctForm; - if (options.v4) { - formFunction = this.to4in6; - } - if (options.className) { - return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; } - return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this)); + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } - /** - * Groups an address - * @returns {String} - */ - group() { - if (this.elidedGroups === 0) { - // The simple case - return helpers.simpleGroup(this.address).join(':'); - } - assert(typeof this.elidedGroups === 'number'); - assert(typeof this.elisionBegin === 'number'); - // The elided case - const output = []; - const [left, right] = this.address.split('::'); - if (left.length) { - output.push(...helpers.simpleGroup(left)); - } - else { - output.push(''); + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); } - const classes = ['hover-group']; - for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { - classes.push((0, sprintf_js_1.sprintf)('group-%d', i)); + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; } - output.push((0, sprintf_js_1.sprintf)('', classes.join(' '))); - if (right.length) { - output.push(...helpers.simpleGroup(right, this.elisionEnd)); + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; else { - output.push(''); - } - if (this.is4()) { - assert(this.address4 instanceof ipv4_1.Address4); - output.pop(); - output.push(this.address4.groupForV6()); + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal } - return output.join(':'); } - // #endregion - // #region Regular expressions - /** - * Generate a regular expression string that can be used to find or validate - * all variations of this address - * @memberof Address6 - * @instance - * @param {boolean} substringSearch - * @returns {string} - */ - regularExpressionString(substringSearch = false) { - let output = []; - // TODO: revisit why this is necessary - const address6 = new Address6(this.correctForm()); - if (address6.elidedGroups === 0) { - // The simple case - output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + var hasValues = false; + var subNodeEmpty = {}; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) { + this._setEncodeChar(uCode, mbCode); + hasValues = true; + } else if (uCode <= NODE_START) { + var subNodeIdx = NODE_START - uCode; + if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030). + var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive. + if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars)) + hasValues = true; + else + subNodeEmpty[subNodeIdx] = true; + } + } else if (uCode <= SEQ_START) { + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + hasValues = true; } - else if (address6.elidedGroups === constants6.GROUPS) { - // A completely elided address - output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + } + return hasValues; +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); } else { - // A partially elided address - const halves = address6.address.split('::'); - if (halves[0].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':'))); - } - assert(typeof address6.elidedGroups === 'number'); - output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); - if (halves[1].length) { - output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':'))); + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + } - output = [output.join(':')]; } - if (!substringSearch) { - output = [ - '(?=^|', - regular_expressions_1.ADDRESS_BOUNDARY, - '|[^\\w\\:])(', - ...output, - ')(?=[^\\w\\:]|', - regular_expressions_1.ADDRESS_BOUNDARY, - '|$)', - ]; + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; } - return output.join(''); - } - /** - * Generate a regular expression that can be used to find or validate all - * variations of this address. - * @memberof Address6 - * @instance - * @param {boolean} substringSearch - * @returns {RegExp} - */ - regularExpression(substringSearch = false) { - return new RegExp(this.regularExpressionString(substringSearch), 'i'); - } -} -exports.Address6 = Address6; -//# sourceMappingURL=ipv6.js.map - -/***/ }), -/***/ 66437: -/***/ ((__unused_webpack_module, exports) => { + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; -"use strict"; + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; -exports.BITS = 32; -exports.GROUPS = 4; -exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; -exports.RE_SUBNET_STRING = /\/\d{1,2}$/; -//# sourceMappingURL=constants.js.map + } else if (resCode == undefined) { // Current character is not part of the sequence. -/***/ }), + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. -/***/ 75280: -/***/ ((__unused_webpack_module, exports) => { + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } -"use strict"; + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; -exports.BITS = 128; -exports.GROUPS = 8; -/** - * Represents IPv6 address scopes - * @memberof Address6 - * @static - */ -exports.SCOPES = { - 0: 'Reserved', - 1: 'Interface local', - 2: 'Link local', - 4: 'Admin local', - 5: 'Site local', - 8: 'Organization local', - 14: 'Global', - 15: 'Reserved', -}; -/** - * Represents IPv6 address types - * @memberof Address6 - * @static - */ -exports.TYPES = { - 'ff01::1/128': 'Multicast (All nodes on this interface)', - 'ff01::2/128': 'Multicast (All routers on this interface)', - 'ff02::1/128': 'Multicast (All nodes on this link)', - 'ff02::2/128': 'Multicast (All routers on this link)', - 'ff05::2/128': 'Multicast (All routers in this site)', - 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)', - 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)', - 'ff02::9/128': 'Multicast (RIP routers)', - 'ff02::a/128': 'Multicast (EIGRP routers)', - 'ff02::d/128': 'Multicast (PIM routers)', - 'ff02::16/128': 'Multicast (MLDv2 reports)', - 'ff01::fb/128': 'Multicast (mDNSv6)', - 'ff02::fb/128': 'Multicast (mDNSv6)', - 'ff05::fb/128': 'Multicast (mDNSv6)', - 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)', - 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)', - 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)', - 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)', - '::/128': 'Unspecified', - '::1/128': 'Loopback', - 'ff00::/8': 'Multicast', - 'fe80::/10': 'Link-local unicast', -}; -/** - * A regular expression that matches bad characters in an IPv6 address - * @memberof Address6 - * @static - */ -exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; -/** - * A regular expression that matches an incorrect IPv6 address - * @memberof Address6 - * @static - */ -exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; -/** - * A regular expression that matches an IPv6 subnet - * @memberof Address6 - * @static - */ -exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; -/** - * A regular expression that matches an IPv6 zone - * @memberof Address6 - * @static - */ -exports.RE_ZONE_STRING = /%.*$/; -exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/); -exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/); -//# sourceMappingURL=constants.js.map + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else if (dbcsCode < 0x1000000) { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } else { + newBuf[j++] = dbcsCode >>> 24; + newBuf[j++] = (dbcsCode >>> 16) & 0xFF; + newBuf[j++] = (dbcsCode >>> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } -/***/ }), + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} -/***/ 20339: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. -"use strict"; + var newBuf = Buffer.alloc(10), j = 0; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0; -const sprintf_js_1 = __nccwpck_require__(72701); -/** - * @returns {String} the string with all zeroes contained in a - */ -function spanAllZeroes(s) { - return s.replace(/(0+)/g, '$1'); -} -exports.spanAllZeroes = spanAllZeroes; -/** - * @returns {String} the string with each character contained in a - */ -function spanAll(s, offset = 0) { - const letters = s.split(''); - return letters - .map((n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead? - ) - .join(''); -} -exports.spanAll = spanAll; -function spanLeadingZeroesSimple(group) { - return group.replace(/^(0+)/, '$1'); -} -/** - * @returns {String} the string with leading zeroes contained in a - */ -function spanLeadingZeroes(address) { - const groups = address.split(':'); - return groups.map((g) => spanLeadingZeroesSimple(g)).join(':'); -} -exports.spanLeadingZeroes = spanLeadingZeroes; -/** - * Groups an address - * @returns {String} a grouped address - */ -function simpleGroup(addressString, offset = 0) { - const groups = addressString.split(':'); - return groups.map((g, i) => { - if (/group-v4/.test(g)) { - return g; + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. } - return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g)); - }); + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); } -exports.simpleGroup = simpleGroup; -//# sourceMappingURL=helpers.js.map -/***/ }), +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; -/***/ 72016: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -"use strict"; +// == Decoder ================================================================== -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0; -const v6 = __importStar(__nccwpck_require__(75280)); -const sprintf_js_1 = __nccwpck_require__(72701); -function groupPossibilities(possibilities) { - return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|')); -} -exports.groupPossibilities = groupPossibilities; -function padGroup(group) { - if (group.length < 4) { - return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group); - } - return group; +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBytes = []; + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; } -exports.padGroup = padGroup; -exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; -function simpleRegularExpression(groups) { - const zeroIndexes = []; - groups.forEach((group, i) => { - const groupInteger = parseInt(group, 16); - if (groupInteger === 0) { - zeroIndexes.push(i); + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBytes = this.prevBytes, prevOffset = this.prevBytes.length, + seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence. + uCode; + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. } - }); - // You can technically elide a single 0, this creates the regular expressions - // to match that eventuality - const possibilities = zeroIndexes.map((zeroIndex) => groups - .map((group, i) => { - if (i === zeroIndex) { - const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : ''; - return groupPossibilities([padGroup(group), elision]); + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + uCode = this.defaultCharUnicode.charCodeAt(0); + i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again. } - return padGroup(group); - }) - .join(':')); - // The simplest case - possibilities.push(groups.map(padGroup).join(':')); - return groupPossibilities(possibilities); -} -exports.simpleRegularExpression = simpleRegularExpression; -function possibleElisions(elidedGroups, moreLeft, moreRight) { - const left = moreLeft ? '' : ':'; - const right = moreRight ? '' : ':'; - const possibilities = []; - // 1. elision of everything (::) - if (!moreLeft && !moreRight) { - possibilities.push('::'); - } - // 2. complete elision of the middle - if (moreLeft && moreRight) { - possibilities.push(''); + else if (uCode === GB18030_CODE) { + if (i >= 3) { + var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30); + } else { + var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + + (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + + (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + + (curByte-0x30); + } + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode >= 0x10000) { + uCode -= 0x10000; + var uCodeLead = 0xD800 | (uCode >> 10); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 | (uCode & 0x3FF); + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; } - if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) { - // 3. complete elision of one side - possibilities.push(':'); + + this.nodeIdx = nodeIdx; + this.prevBytes = (seqStart >= 0) + ? Array.prototype.slice.call(buf, seqStart) + : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf)); + + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBytes.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var bytesArr = this.prevBytes.slice(1); + + // Parse remaining as usual. + this.prevBytes = []; + this.nodeIdx = 0; + if (bytesArr.length > 0) + ret += this.write(bytesArr); } - // 4. elision from the left side - possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1)); - // 5. elision from the right side - possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right)); - // 6. no elision - possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1)); - // 7. elision (including sloppy elision) from the middle - for (let groups = 1; groups < elidedGroups - 1; groups++) { - for (let position = 1; position < elidedGroups - groups; position++) { - possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1)); - } + + this.prevBytes = []; + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + ((r-l+1) >> 1); + if (table[mid] <= val) + l = mid; + else + r = mid; } - return groupPossibilities(possibilities); + return l; } -exports.possibleElisions = possibleElisions; -//# sourceMappingURL=regular-expressions.js.map + + /***/ }), -/***/ 72701: -/***/ ((__unused_webpack_module, exports) => { +/***/ 11802: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* global window, exports, define */ +"use strict"; -!function() { - 'use strict' - var re = { - not_string: /[^s]/, - not_bool: /[^t]/, - not_type: /[^T]/, - not_primitive: /[^v]/, - number: /[diefg]/, - numeric_arg: /[bcdiefguxX]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[+-]/ - } +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. - function sprintf(key) { - // `arguments` is not an array, but should be fine for this call - return sprintf_format(sprintf_parse(key), arguments) - } +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - function vsprintf(fmt, argv) { - return sprintf.apply(null, [fmt].concat(argv || [])) - } + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - function sprintf_format(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign - for (i = 0; i < tree_length; i++) { - if (typeof parse_tree[i] === 'string') { - output += parse_tree[i] - } - else if (typeof parse_tree[i] === 'object') { - ph = parse_tree[i] // convenience purposes only - if (ph.keys) { // keyword argument - arg = argv[cursor] - for (k = 0; k < ph.keys.length; k++) { - if (arg == undefined) { - throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1])) - } - arg = arg[ph.keys[k]] - } - } - else if (ph.param_no) { // positional argument (explicit) - arg = argv[ph.param_no] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } + 'shiftjis': { + type: '_dbcs', + table: function() { return __nccwpck_require__(40679) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', - if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) { - arg = arg() - } + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(56406) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, - if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) { - throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) - } + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - if (re.number.test(ph.type)) { - is_positive = arg >= 0 - } - switch (ph.type) { - case 'b': - arg = parseInt(arg, 10).toString(2) - break - case 'c': - arg = String.fromCharCode(parseInt(arg, 10)) - break - case 'd': - case 'i': - arg = parseInt(arg, 10) - break - case 'j': - arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0) - break - case 'e': - arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential() - break - case 'f': - arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg) - break - case 'g': - arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg) - break - case 'o': - arg = (parseInt(arg, 10) >>> 0).toString(8) - break - case 's': - arg = String(arg) - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 't': - arg = String(!!arg) - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 'T': - arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 'u': - arg = parseInt(arg, 10) >>> 0 - break - case 'v': - arg = arg.valueOf() - arg = (ph.precision ? arg.substring(0, ph.precision) : arg) - break - case 'x': - arg = (parseInt(arg, 10) >>> 0).toString(16) - break - case 'X': - arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() - break - } - if (re.json.test(ph.type)) { - output += arg - } - else { - if (re.number.test(ph.type) && (!is_positive || ph.sign)) { - sign = is_positive ? '+' : '-' - arg = arg.toString().replace(re.sign, '') - } - else { - sign = '' - } - pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ' - pad_length = ph.width - (sign + arg).length - pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' - output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) - } - } - } - return output - } + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', - var sprintf_cache = Object.create(null) + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return __nccwpck_require__(74488) }, + }, - function sprintf_parse(fmt) { - if (sprintf_cache[fmt]) { - return sprintf_cache[fmt] - } + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', - var _fmt = fmt, match, parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree.push(match[0]) - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree.push('%') - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - } - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') - } + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) }, + gb18030: function() { return __nccwpck_require__(99129) }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, - parse_tree.push( - { - placeholder: match[0], - param_no: match[1], - keys: match[2], - sign: match[3], - pad_char: match[4], - align: match[5], - width: match[6], - precision: match[7], - type: match[8] - } - ) - } - else { - throw new SyntaxError('[sprintf] unexpected placeholder') - } - _fmt = _fmt.substring(match[0].length) - } - return sprintf_cache[fmt] = parse_tree - } + 'chinese': 'gb18030', - /** - * export to either browser or node.js - */ - /* eslint-disable quote-props */ - if (true) { - exports.sprintf = sprintf - exports.vsprintf = vsprintf - } - if (typeof window !== 'undefined') { - window['sprintf'] = sprintf - window['vsprintf'] = vsprintf - if (typeof define === 'function' && define['amd']) { - define(function() { - return { - 'sprintf': sprintf, - 'vsprintf': vsprintf - } - }) - } - } - /* eslint-enable quote-props */ -}(); // eslint-disable-line + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return __nccwpck_require__(21166) }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', -/***/ }), + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. -/***/ 21608: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(72324) }, + }, -"use strict"; + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return (__nccwpck_require__(72324).concat)(__nccwpck_require__(43267)) }, + encodeSkipVals: [ + // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of + // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. + // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. + 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, + 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, + 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, + 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, + 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.experimental_jwksCache = exports.jwksCache = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0; -var decrypt_js_1 = __nccwpck_require__(14298); -Object.defineProperty(exports, "compactDecrypt", ({ enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } })); -var decrypt_js_2 = __nccwpck_require__(59344); -Object.defineProperty(exports, "flattenedDecrypt", ({ enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } })); -var decrypt_js_3 = __nccwpck_require__(49783); -Object.defineProperty(exports, "generalDecrypt", ({ enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } })); -var encrypt_js_1 = __nccwpck_require__(71907); -Object.defineProperty(exports, "GeneralEncrypt", ({ enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } })); -var verify_js_1 = __nccwpck_require__(94212); -Object.defineProperty(exports, "compactVerify", ({ enumerable: true, get: function () { return verify_js_1.compactVerify; } })); -var verify_js_2 = __nccwpck_require__(56358); -Object.defineProperty(exports, "flattenedVerify", ({ enumerable: true, get: function () { return verify_js_2.flattenedVerify; } })); -var verify_js_3 = __nccwpck_require__(88323); -Object.defineProperty(exports, "generalVerify", ({ enumerable: true, get: function () { return verify_js_3.generalVerify; } })); -var verify_js_4 = __nccwpck_require__(35297); -Object.defineProperty(exports, "jwtVerify", ({ enumerable: true, get: function () { return verify_js_4.jwtVerify; } })); -var decrypt_js_4 = __nccwpck_require__(95339); -Object.defineProperty(exports, "jwtDecrypt", ({ enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } })); -var encrypt_js_2 = __nccwpck_require__(4434); -Object.defineProperty(exports, "CompactEncrypt", ({ enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } })); -var encrypt_js_3 = __nccwpck_require__(62372); -Object.defineProperty(exports, "FlattenedEncrypt", ({ enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } })); -var sign_js_1 = __nccwpck_require__(21760); -Object.defineProperty(exports, "CompactSign", ({ enumerable: true, get: function () { return sign_js_1.CompactSign; } })); -var sign_js_2 = __nccwpck_require__(86170); -Object.defineProperty(exports, "FlattenedSign", ({ enumerable: true, get: function () { return sign_js_2.FlattenedSign; } })); -var sign_js_3 = __nccwpck_require__(50443); -Object.defineProperty(exports, "GeneralSign", ({ enumerable: true, get: function () { return sign_js_3.GeneralSign; } })); -var sign_js_4 = __nccwpck_require__(22713); -Object.defineProperty(exports, "SignJWT", ({ enumerable: true, get: function () { return sign_js_4.SignJWT; } })); -var encrypt_js_4 = __nccwpck_require__(38375); -Object.defineProperty(exports, "EncryptJWT", ({ enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } })); -var thumbprint_js_1 = __nccwpck_require__(45396); -Object.defineProperty(exports, "calculateJwkThumbprint", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } })); -Object.defineProperty(exports, "calculateJwkThumbprintUri", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } })); -var embedded_js_1 = __nccwpck_require__(88541); -Object.defineProperty(exports, "EmbeddedJWK", ({ enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } })); -var local_js_1 = __nccwpck_require__(25275); -Object.defineProperty(exports, "createLocalJWKSet", ({ enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } })); -var remote_js_1 = __nccwpck_require__(69260); -Object.defineProperty(exports, "createRemoteJWKSet", ({ enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } })); -Object.defineProperty(exports, "jwksCache", ({ enumerable: true, get: function () { return remote_js_1.jwksCache; } })); -Object.defineProperty(exports, "experimental_jwksCache", ({ enumerable: true, get: function () { return remote_js_1.experimental_jwksCache; } })); -var unsecured_js_1 = __nccwpck_require__(40560); -Object.defineProperty(exports, "UnsecuredJWT", ({ enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } })); -var export_js_1 = __nccwpck_require__(48108); -Object.defineProperty(exports, "exportPKCS8", ({ enumerable: true, get: function () { return export_js_1.exportPKCS8; } })); -Object.defineProperty(exports, "exportSPKI", ({ enumerable: true, get: function () { return export_js_1.exportSPKI; } })); -Object.defineProperty(exports, "exportJWK", ({ enumerable: true, get: function () { return export_js_1.exportJWK; } })); -var import_js_1 = __nccwpck_require__(45647); -Object.defineProperty(exports, "importSPKI", ({ enumerable: true, get: function () { return import_js_1.importSPKI; } })); -Object.defineProperty(exports, "importPKCS8", ({ enumerable: true, get: function () { return import_js_1.importPKCS8; } })); -Object.defineProperty(exports, "importX509", ({ enumerable: true, get: function () { return import_js_1.importX509; } })); -Object.defineProperty(exports, "importJWK", ({ enumerable: true, get: function () { return import_js_1.importJWK; } })); -var decode_protected_header_js_1 = __nccwpck_require__(14704); -Object.defineProperty(exports, "decodeProtectedHeader", ({ enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } })); -var decode_jwt_js_1 = __nccwpck_require__(60002); -Object.defineProperty(exports, "decodeJwt", ({ enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } })); -exports.errors = __nccwpck_require__(15974); -var generate_key_pair_js_1 = __nccwpck_require__(87820); -Object.defineProperty(exports, "generateKeyPair", ({ enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } })); -var generate_secret_js_1 = __nccwpck_require__(37152); -Object.defineProperty(exports, "generateSecret", ({ enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } })); -exports.base64url = __nccwpck_require__(78305); -var runtime_js_1 = __nccwpck_require__(25021); -Object.defineProperty(exports, "cryptoRuntime", ({ enumerable: true, get: function () { return runtime_js_1.default; } })); + // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 + 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, + ], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; /***/ }), -/***/ 14298: +/***/ 27585: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.compactDecrypt = compactDecrypt; -const decrypt_js_1 = __nccwpck_require__(59344); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -async function compactDecrypt(jwe, key, options) { - if (jwe instanceof Uint8Array) { - jwe = buffer_utils_js_1.decoder.decode(jwe); - } - if (typeof jwe !== 'string') { - throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array'); - } - const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); - if (length !== 5) { - throw new errors_js_1.JWEInvalid('Invalid Compact JWE'); - } - const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({ - ciphertext, - iv: iv || undefined, - protected: protectedHeader, - tag: tag || undefined, - encrypted_key: encryptedKey || undefined, - }, key, options); - const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __nccwpck_require__(72356), + __nccwpck_require__(62021), + __nccwpck_require__(8771), + __nccwpck_require__(28231), + __nccwpck_require__(82473), + __nccwpck_require__(97083), + __nccwpck_require__(69487), + __nccwpck_require__(7978), + __nccwpck_require__(11802), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; } /***/ }), -/***/ 4434: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 72356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CompactEncrypt = void 0; -const encrypt_js_1 = __nccwpck_require__(62372); -class CompactEncrypt { - _flattened; - constructor(plaintext) { - this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext); - } - setContentEncryptionKey(cek) { - this._flattened.setContentEncryptionKey(cek); - return this; - } - setInitializationVector(iv) { - this._flattened.setInitializationVector(iv); - return this; - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - setKeyManagementParameters(parameters) { - this._flattened.setKeyManagementParameters(parameters); - return this; - } - async encrypt(key, options) { - const jwe = await this._flattened.encrypt(key, options); - return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); - } -} -exports.CompactEncrypt = CompactEncrypt; +var Buffer = (__nccwpck_require__(12803).Buffer); +// Export Node.js internal encodings. -/***/ }), +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", -/***/ 59344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", -"use strict"; + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.flattenedDecrypt = flattenedDecrypt; -const base64url_js_1 = __nccwpck_require__(12635); -const decrypt_js_1 = __nccwpck_require__(52806); -const errors_js_1 = __nccwpck_require__(15974); -const is_disjoint_js_1 = __nccwpck_require__(21853); -const is_object_js_1 = __nccwpck_require__(92242); -const decrypt_key_management_js_1 = __nccwpck_require__(56243); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const cek_js_1 = __nccwpck_require__(87937); -const validate_crit_js_1 = __nccwpck_require__(15595); -const validate_algorithms_js_1 = __nccwpck_require__(19917); -async function flattenedDecrypt(jwe, key, options) { - if (!(0, is_object_js_1.default)(jwe)) { - throw new errors_js_1.JWEInvalid('Flattened JWE must be an object'); - } - if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { - throw new errors_js_1.JWEInvalid('JOSE Header missing'); - } - if (jwe.iv !== undefined && typeof jwe.iv !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Initialization Vector incorrect type'); - } - if (typeof jwe.ciphertext !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type'); - } - if (jwe.tag !== undefined && typeof jwe.tag !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Authentication Tag incorrect type'); - } - if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type'); - } - if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { - throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type'); - } - if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { - throw new errors_js_1.JWEInvalid('JWE AAD incorrect type'); - } - if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) { - throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type'); - } - if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) { - throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); - } - let parsedProt; - if (jwe.protected) { - try { - const protectedHeader = (0, base64url_js_1.decode)(jwe.protected); - parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); - } - catch { - throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid'); - } - } - if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) { - throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...parsedProt, - ...jwe.header, - ...jwe.unprotected, - }; - (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader); - if (joseHeader.zip !== undefined) { - throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); - } - if (typeof enc !== 'string' || !enc) { - throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); - } - const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms); - const contentEncryptionAlgorithms = options && - (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); - if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) || - (!keyManagementAlgorithms && alg.startsWith('PBES2'))) { - throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { - throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); - } - let encryptedKey; - if (jwe.encrypted_key !== undefined) { - try { - encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key'); - } - } - let resolvedKey = false; - if (typeof key === 'function') { - key = await key(parsedProt, jwe); - resolvedKey = true; - } - let cek; - try { - cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options); - } - catch (err) { - if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) { - throw err; - } - cek = (0, cek_js_1.default)(enc); - } - let iv; - let tag; - if (jwe.iv !== undefined) { - try { - iv = (0, base64url_js_1.decode)(jwe.iv); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); - } - } - if (jwe.tag !== undefined) { - try { - tag = (0, base64url_js_1.decode)(jwe.tag); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); - } - } - const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? ''); - let additionalData; - if (jwe.aad !== undefined) { - additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad)); - } - else { - additionalData = protectedHeader; - } - let ciphertext; - try { - ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext'); - } - const plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData); - const result = { plaintext }; - if (jwe.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jwe.aad !== undefined) { - try { - result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad'); + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; } } - if (jwe.unprotected !== undefined) { - result.sharedUnprotectedHeader = jwe.unprotected; - } - if (jwe.header !== undefined) { - result.unprotectedHeader = jwe.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; } +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; -/***/ }), +//------------------------------------------------------------------------------ -/***/ 62372: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = (__nccwpck_require__(13193).StringDecoder); -"use strict"; +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FlattenedEncrypt = void 0; -const base64url_js_1 = __nccwpck_require__(12635); -const private_symbols_js_1 = __nccwpck_require__(46433); -const encrypt_js_1 = __nccwpck_require__(36286); -const encrypt_key_management_js_1 = __nccwpck_require__(96539); -const errors_js_1 = __nccwpck_require__(15974); -const is_disjoint_js_1 = __nccwpck_require__(21853); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const validate_crit_js_1 = __nccwpck_require__(15595); -class FlattenedEncrypt { - _plaintext; - _protectedHeader; - _sharedUnprotectedHeader; - _unprotectedHeader; - _aad; - _cek; - _iv; - _keyManagementParameters; - constructor(plaintext) { - if (!(plaintext instanceof Uint8Array)) { - throw new TypeError('plaintext must be an instance of Uint8Array'); - } - this._plaintext = plaintext; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._sharedUnprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); - } - this._sharedUnprotectedHeader = sharedUnprotectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - async encrypt(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { - throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); - } - if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { - throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...this._sharedUnprotectedHeader, - }; - (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); - } - const { alg, enc } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (typeof enc !== 'string' || !enc) { - throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - let encryptedKey; - if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) { - throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); - } - let cek; - { - let parameters; - ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters)); - if (parameters) { - if (options && private_symbols_js_1.unprotected in options) { - if (!this._unprotectedHeader) { - this.setUnprotectedHeader(parameters); - } - else { - this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; - } - } - else if (!this._protectedHeader) { - this.setProtectedHeader(parameters); - } - else { - this._protectedHeader = { ...this._protectedHeader, ...parameters }; - } - } - } - let additionalData; - let protectedHeader; - let aadMember; - if (this._protectedHeader) { - protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = buffer_utils_js_1.encoder.encode(''); - } - if (this._aad) { - aadMember = (0, base64url_js_1.encode)(this._aad); - additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember)); - } - else { - additionalData = protectedHeader; - } - const { ciphertext, tag, iv } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData); - const jwe = { - ciphertext: (0, base64url_js_1.encode)(ciphertext), - }; - if (iv) { - jwe.iv = (0, base64url_js_1.encode)(iv); - } - if (tag) { - jwe.tag = (0, base64url_js_1.encode)(tag); - } - if (encryptedKey) { - jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); - } - if (aadMember) { - jwe.aad = aadMember; - } - if (this._protectedHeader) { - jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader); - } - if (this._sharedUnprotectedHeader) { - jwe.unprotected = this._sharedUnprotectedHeader; - } - if (this._unprotectedHeader) { - jwe.header = this._unprotectedHeader; - } - return jwe; + +function InternalDecoder(options, codec) { + this.decoder = new StringDecoder(codec.enc); +} + +InternalDecoder.prototype.write = function(buf) { + if (!Buffer.isBuffer(buf)) { + buf = Buffer.from(buf); } + + return this.decoder.write(buf); } -exports.FlattenedEncrypt = FlattenedEncrypt; +InternalDecoder.prototype.end = function() { + return this.decoder.end(); +} -/***/ }), -/***/ 49783: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +//------------------------------------------------------------------------------ +// Encoder is mostly trivial -"use strict"; +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generalDecrypt = generalDecrypt; -const decrypt_js_1 = __nccwpck_require__(59344); -const errors_js_1 = __nccwpck_require__(15974); -const is_object_js_1 = __nccwpck_require__(92242); -async function generalDecrypt(jwe, key, options) { - if (!(0, is_object_js_1.default)(jwe)) { - throw new errors_js_1.JWEInvalid('General JWE must be an object'); - } - if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) { - throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type'); - } - if (!jwe.recipients.length) { - throw new errors_js_1.JWEInvalid('JWE Recipients has no members'); - } - for (const recipient of jwe.recipients) { - try { - return await (0, decrypt_js_1.flattenedDecrypt)({ - aad: jwe.aad, - ciphertext: jwe.ciphertext, - encrypted_key: recipient.encrypted_key, - header: recipient.header, - iv: jwe.iv, - protected: jwe.protected, - tag: jwe.tag, - unprotected: jwe.unprotected, - }, key, options); - } - catch { - } - } - throw new errors_js_1.JWEDecryptionFailed(); +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} + +InternalEncoder.prototype.end = function() { } -/***/ }), +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. -/***/ 71907: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} -"use strict"; +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GeneralEncrypt = void 0; -const encrypt_js_1 = __nccwpck_require__(62372); -const private_symbols_js_1 = __nccwpck_require__(46433); -const errors_js_1 = __nccwpck_require__(15974); -const cek_js_1 = __nccwpck_require__(87937); -const is_disjoint_js_1 = __nccwpck_require__(21853); -const encrypt_key_management_js_1 = __nccwpck_require__(96539); -const base64url_js_1 = __nccwpck_require__(12635); -const validate_crit_js_1 = __nccwpck_require__(15595); -class IndividualRecipient { - parent; - unprotectedHeader; - key; - options; - constructor(enc, key, options) { - this.parent = enc; - this.key = key; - this.options = options; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addRecipient(...args) { - return this.parent.addRecipient(...args); - } - encrypt(...args) { - return this.parent.encrypt(...args); - } - done() { - return this.parent; - } + return Buffer.from(str, "base64"); } -class GeneralEncrypt { - _plaintext; - _recipients = []; - _protectedHeader; - _unprotectedHeader; - _aad; - constructor(plaintext) { - this._plaintext = plaintext; - } - addRecipient(key, options) { - const recipient = new IndividualRecipient(this, key, { crit: options?.crit }); - this._recipients.push(recipient); - return recipient; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } - this._protectedHeader = protectedHeader; - return this; - } - setSharedUnprotectedHeader(sharedUnprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setSharedUnprotectedHeader can only be called once'); + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } - this._unprotectedHeader = sharedUnprotectedHeader; - return this; } - setAdditionalAuthenticatedData(aad) { - this._aad = aad; - return this; - } - async encrypt() { - if (!this._recipients.length) { - throw new errors_js_1.JWEInvalid('at least one recipient must be added'); - } - if (this._recipients.length === 1) { - const [recipient] = this._recipients; - const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .encrypt(recipient.key, { ...recipient.options }); - const jwe = { - ciphertext: flattened.ciphertext, - iv: flattened.iv, - recipients: [{}], - tag: flattened.tag, - }; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - if (flattened.encrypted_key) - jwe.recipients[0].encrypted_key = flattened.encrypted_key; - if (flattened.header) - jwe.recipients[0].header = flattened.header; - return jwe; - } - let enc; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { - throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); - } - if (alg === 'dir' || alg === 'ECDH-ES') { - throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); - } - if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { - throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); - } - if (!enc) { - enc = joseHeader.enc; - } - else if (enc !== joseHeader.enc) { - throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; } - (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); - if (joseHeader.zip !== undefined) { - throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; } - } - const cek = (0, cek_js_1.default)(enc); - const jwe = { - ciphertext: '', - iv: '', - recipients: [], - tag: '', - }; - for (let i = 0; i < this._recipients.length; i++) { - const recipient = this._recipients[i]; - const target = {}; - jwe.recipients.push(target); - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - ...recipient.unprotectedHeader, - }; - const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; - if (i === 0) { - const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) - .setAdditionalAuthenticatedData(this._aad) - .setContentEncryptionKey(cek) - .setProtectedHeader(this._protectedHeader) - .setSharedUnprotectedHeader(this._unprotectedHeader) - .setUnprotectedHeader(recipient.unprotectedHeader) - .setKeyManagementParameters({ p2c }) - .encrypt(recipient.key, { - ...recipient.options, - [private_symbols_js_1.unprotected]: true, - }); - jwe.ciphertext = flattened.ciphertext; - jwe.iv = flattened.iv; - jwe.tag = flattened.tag; - if (flattened.aad) - jwe.aad = flattened.aad; - if (flattened.protected) - jwe.protected = flattened.protected; - if (flattened.unprotected) - jwe.unprotected = flattened.unprotected; - target.encrypted_key = flattened.encrypted_key; - if (flattened.header) - target.header = flattened.header; - continue; + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; } - const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg || - this._protectedHeader?.alg || - this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); - target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); - if (recipient.unprotectedHeader || parameters) - target.header = { ...recipient.unprotectedHeader, ...parameters }; } - return jwe; } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; } -exports.GeneralEncrypt = GeneralEncrypt; /***/ }), -/***/ 88541: +/***/ 82473: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.EmbeddedJWK = EmbeddedJWK; -const import_js_1 = __nccwpck_require__(45647); -const is_object_js_1 = __nccwpck_require__(92242); -const errors_js_1 = __nccwpck_require__(15974); -async function EmbeddedJWK(protectedHeader, token) { - const joseHeader = { - ...protectedHeader, - ...token?.header, - }; - if (!(0, is_object_js_1.default)(joseHeader.jwk)) { - throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); - } - const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); +var Buffer = (__nccwpck_require__(12803).Buffer); + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; } - return key; + + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; } +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; -/***/ }), -/***/ 45396: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} -"use strict"; +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.calculateJwkThumbprint = calculateJwkThumbprint; -exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; -const digest_js_1 = __nccwpck_require__(12931); -const base64url_js_1 = __nccwpck_require__(12635); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const is_object_js_1 = __nccwpck_require__(92242); -const check = (value, description) => { - if (typeof value !== 'string' || !value) { - throw new errors_js_1.JWKInvalid(`${description} missing or invalid`); - } -}; -async function calculateJwkThumbprint(jwk, digestAlgorithm) { - if (!(0, is_object_js_1.default)(jwk)) { - throw new TypeError('JWK must be an object'); - } - digestAlgorithm ??= 'sha256'; - if (digestAlgorithm !== 'sha256' && - digestAlgorithm !== 'sha384' && - digestAlgorithm !== 'sha512') { - throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); - } - let components; - switch (jwk.kty) { - case 'EC': - check(jwk.crv, '"crv" (Curve) Parameter'); - check(jwk.x, '"x" (X Coordinate) Parameter'); - check(jwk.y, '"y" (Y Coordinate) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; - break; - case 'OKP': - check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); - check(jwk.x, '"x" (Public Key) Parameter'); - components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; - break; - case 'RSA': - check(jwk.e, '"e" (Exponent) Parameter'); - check(jwk.n, '"n" (Modulus) Parameter'); - components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; - break; - case 'oct': - check(jwk.k, '"k" (Key Value) Parameter'); - components = { k: jwk.k, kty: jwk.kty }; - break; - default: - throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; } - const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components)); - return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data)); + return newBuf.toString('ucs2'); } -async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { - digestAlgorithm ??= 'sha256'; - const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); - return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; + +SBCSDecoder.prototype.end = function() { } /***/ }), -/***/ 25275: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 69487: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createLocalJWKSet = createLocalJWKSet; -const import_js_1 = __nccwpck_require__(45647); -const errors_js_1 = __nccwpck_require__(15974); -const is_object_js_1 = __nccwpck_require__(92242); -function getKtyFromAlg(alg) { - switch (typeof alg === 'string' && alg.slice(0, 2)) { - case 'RS': - case 'PS': - return 'RSA'; - case 'ES': - return 'EC'; - case 'Ed': - return 'OKP'; - default: - throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); - } -} -function isJWKSLike(jwks) { - return (jwks && - typeof jwks === 'object' && - Array.isArray(jwks.keys) && - jwks.keys.every(isJWKLike)); -} -function isJWKLike(key) { - return (0, is_object_js_1.default)(key); -} -function clone(obj) { - if (typeof structuredClone === 'function') { - return structuredClone(obj); - } - return JSON.parse(JSON.stringify(obj)); -} -class LocalJWKSet { - _jwks; - _cached = new WeakMap(); - constructor(jwks) { - if (!isJWKSLike(jwks)) { - throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); - } - this._jwks = clone(jwks); - } - async getKey(protectedHeader, token) { - const { alg, kid } = { ...protectedHeader, ...token?.header }; - const kty = getKtyFromAlg(alg); - const candidates = this._jwks.keys.filter((jwk) => { - let candidate = kty === jwk.kty; - if (candidate && typeof kid === 'string') { - candidate = kid === jwk.kid; - } - if (candidate && typeof jwk.alg === 'string') { - candidate = alg === jwk.alg; - } - if (candidate && typeof jwk.use === 'string') { - candidate = jwk.use === 'sig'; - } - if (candidate && Array.isArray(jwk.key_ops)) { - candidate = jwk.key_ops.includes('verify'); - } - if (candidate && alg === 'EdDSA') { - candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; - } - if (candidate) { - switch (alg) { - case 'ES256': - candidate = jwk.crv === 'P-256'; - break; - case 'ES256K': - candidate = jwk.crv === 'secp256k1'; - break; - case 'ES384': - candidate = jwk.crv === 'P-384'; - break; - case 'ES512': - candidate = jwk.crv === 'P-521'; - break; - } - } - return candidate; - }); - const { 0: jwk, length } = candidates; - if (length === 0) { - throw new errors_js_1.JWKSNoMatchingKey(); - } - if (length !== 1) { - const error = new errors_js_1.JWKSMultipleMatchingKeys(); - const { _cached } = this; - error[Symbol.asyncIterator] = async function* () { - for (const jwk of candidates) { - try { - yield await importWithAlgCache(_cached, jwk, alg); - } - catch { } - } - }; - throw error; - } - return importWithAlgCache(this._cached, jwk, alg); - } -} -async function importWithAlgCache(cache, jwk, alg) { - const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); - if (cached[alg] === undefined) { - const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg); - if (key instanceof Uint8Array || key.type !== 'public') { - throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys'); - } - cached[alg] = key; - } - return cached[alg]; -} -function createLocalJWKSet(jwks) { - const set = new LocalJWKSet(jwks); - const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(localJWKSet, { - jwks: { - value: () => clone(set._jwks), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return localJWKSet; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } } - /***/ }), -/***/ 69260: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 97083: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.experimental_jwksCache = exports.jwksCache = void 0; -exports.createRemoteJWKSet = createRemoteJWKSet; -const fetch_jwks_js_1 = __nccwpck_require__(20311); -const errors_js_1 = __nccwpck_require__(15974); -const local_js_1 = __nccwpck_require__(25275); -const is_object_js_1 = __nccwpck_require__(92242); -function isCloudflareWorkers() { - return (typeof WebSocketPair !== 'undefined' || - (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || - (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); -} -let USER_AGENT; -if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { - const NAME = 'jose'; - const VERSION = 'v5.9.6'; - USER_AGENT = `${NAME}/${VERSION}`; -} -exports.jwksCache = Symbol(); -function isFreshJwksCache(input, cacheMaxAge) { - if (typeof input !== 'object' || input === null) { - return false; - } - if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { - return false; - } - if (!('jwks' in input) || - !(0, is_object_js_1.default)(input.jwks) || - !Array.isArray(input.jwks.keys) || - !Array.prototype.every.call(input.jwks.keys, is_object_js_1.default)) { - return false; - } - return true; -} -class RemoteJWKSet { - _url; - _timeoutDuration; - _cooldownDuration; - _cacheMaxAge; - _jwksTimestamp; - _pendingFetch; - _options; - _local; - _cache; - constructor(url, options) { - if (!(url instanceof URL)) { - throw new TypeError('url must be an instance of URL'); - } - this._url = new URL(url.href); - this._options = { agent: options?.agent, headers: options?.headers }; - this._timeoutDuration = - typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000; - this._cooldownDuration = - typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000; - this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000; - if (options?.[exports.jwksCache] !== undefined) { - this._cache = options?.[exports.jwksCache]; - if (isFreshJwksCache(options?.[exports.jwksCache], this._cacheMaxAge)) { - this._jwksTimestamp = this._cache.uat; - this._local = (0, local_js_1.createLocalJWKSet)(this._cache.jwks); - } - } - } - coolingDown() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cooldownDuration - : false; - } - fresh() { - return typeof this._jwksTimestamp === 'number' - ? Date.now() < this._jwksTimestamp + this._cacheMaxAge - : false; - } - async getKey(protectedHeader, token) { - if (!this._local || !this.fresh()) { - await this.reload(); - } - try { - return await this._local(protectedHeader, token); - } - catch (err) { - if (err instanceof errors_js_1.JWKSNoMatchingKey) { - if (this.coolingDown() === false) { - await this.reload(); - return this._local(protectedHeader, token); - } - } - throw err; - } - } - async reload() { - if (this._pendingFetch && isCloudflareWorkers()) { - this._pendingFetch = undefined; - } - const headers = new Headers(this._options.headers); - if (USER_AGENT && !headers.has('User-Agent')) { - headers.set('User-Agent', USER_AGENT); - this._options.headers = Object.fromEntries(headers.entries()); - } - this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options) - .then((json) => { - this._local = (0, local_js_1.createLocalJWKSet)(json); - if (this._cache) { - this._cache.uat = Date.now(); - this._cache.jwks = json; - } - this._jwksTimestamp = Date.now(); - this._pendingFetch = undefined; - }) - .catch((err) => { - this._pendingFetch = undefined; - throw err; - }); - await this._pendingFetch; - } -} -function createRemoteJWKSet(url, options) { - const set = new RemoteJWKSet(url, options); - const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); - Object.defineProperties(remoteJWKSet, { - coolingDown: { - get: () => set.coolingDown(), - enumerable: true, - configurable: false, - }, - fresh: { - get: () => set.fresh(), - enumerable: true, - configurable: false, - }, - reload: { - value: () => set.reload(), - enumerable: true, - configurable: false, - writable: false, - }, - reloading: { - get: () => !!set._pendingFetch, - enumerable: true, - configurable: false, - }, - jwks: { - value: () => set._local?.jwks(), - enumerable: true, - configurable: false, - writable: false, - }, - }); - return remoteJWKSet; -} -exports.experimental_jwksCache = exports.jwksCache; +// Manually added data to be used by sbcs codec in addition to generated one. -/***/ }), +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, -/***/ 21760: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, -"use strict"; + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CompactSign = void 0; -const sign_js_1 = __nccwpck_require__(86170); -class CompactSign { - _flattened; - constructor(payload) { - this._flattened = new sign_js_1.FlattenedSign(payload); - } - setProtectedHeader(protectedHeader) { - this._flattened.setProtectedHeader(protectedHeader); - return this; - } - async sign(key, options) { - const jws = await this._flattened.sign(key, options); - if (jws.payload === undefined) { - throw new TypeError('use the flattened module for creating JWS with b64: false'); - } - return `${jws.protected}.${jws.payload}.${jws.signature}`; - } -} -exports.CompactSign = CompactSign; + "cp720": { + "type": "_sbcs", + "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0" + }, + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", -/***/ }), + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", -/***/ 94212: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", -"use strict"; + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.compactVerify = compactVerify; -const verify_js_1 = __nccwpck_require__(56358); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -async function compactVerify(jws, key, options) { - if (jws instanceof Uint8Array) { - jws = buffer_utils_js_1.decoder.decode(jws); - } - if (typeof jws !== 'string') { - throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array'); - } - const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); - if (length !== 3) { - throw new errors_js_1.JWSInvalid('Invalid Compact JWS'); - } - const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options); - const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; -} + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + "cp819": "iso88591", + "ibm819": "iso88591", -/***/ }), + "cyrillic": "iso88595", -/***/ 86170: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", -"use strict"; + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FlattenedSign = void 0; -const base64url_js_1 = __nccwpck_require__(12635); -const sign_js_1 = __nccwpck_require__(26966); -const is_disjoint_js_1 = __nccwpck_require__(21853); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const check_key_type_js_1 = __nccwpck_require__(29555); -const validate_crit_js_1 = __nccwpck_require__(15595); -class FlattenedSign { - _payload; - _protectedHeader; - _unprotectedHeader; - constructor(payload) { - if (!(payload instanceof Uint8Array)) { - throw new TypeError('payload must be an instance of Uint8Array'); - } - this._payload = payload; - } - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this._unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this._unprotectedHeader = unprotectedHeader; - return this; - } - async sign(key, options) { - if (!this._protectedHeader && !this._unprotectedHeader) { - throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); - } - if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) { - throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...this._protectedHeader, - ...this._unprotectedHeader, - }; - const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = this._protectedHeader.b64; - if (typeof b64 !== 'boolean') { - throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'sign'); - let payload = this._payload; - if (b64) { - payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload)); - } - let protectedHeader; - if (this._protectedHeader) { - protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); - } - else { - protectedHeader = buffer_utils_js_1.encoder.encode(''); - } - const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload); - const signature = await (0, sign_js_1.default)(alg, key, data); - const jws = { - signature: (0, base64url_js_1.encode)(signature), - payload: '', - }; - if (b64) { - jws.payload = buffer_utils_js_1.decoder.decode(payload); - } - if (this._unprotectedHeader) { - jws.header = this._unprotectedHeader; - } - if (this._protectedHeader) { - jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader); - } - return jws; - } -} -exports.FlattenedSign = FlattenedSign; + "hebrew": "iso88598", + "hebrew8": "iso88598", + "turkish": "iso88599", + "turkish8": "iso88599", -/***/ }), + "thai": "iso885911", + "thai8": "iso885911", -/***/ 56358: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", -"use strict"; + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.flattenedVerify = flattenedVerify; -const base64url_js_1 = __nccwpck_require__(12635); -const verify_js_1 = __nccwpck_require__(11242); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const is_disjoint_js_1 = __nccwpck_require__(21853); -const is_object_js_1 = __nccwpck_require__(92242); -const check_key_type_js_1 = __nccwpck_require__(29555); -const validate_crit_js_1 = __nccwpck_require__(15595); -const validate_algorithms_js_1 = __nccwpck_require__(19917); -const is_jwk_js_1 = __nccwpck_require__(91229); -const import_js_1 = __nccwpck_require__(45647); -async function flattenedVerify(jws, key, options) { - if (!(0, is_object_js_1.default)(jws)) { - throw new errors_js_1.JWSInvalid('Flattened JWS must be an object'); - } - if (jws.protected === undefined && jws.header === undefined) { - throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); - } - if (jws.protected !== undefined && typeof jws.protected !== 'string') { - throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type'); - } - if (jws.payload === undefined) { - throw new errors_js_1.JWSInvalid('JWS Payload missing'); - } - if (typeof jws.signature !== 'string') { - throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type'); - } - if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) { - throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type'); - } - let parsedProt = {}; - if (jws.protected) { - try { - const protectedHeader = (0, base64url_js_1.decode)(jws.protected); - parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); - } - catch { - throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid'); - } - } - if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) { - throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); - } - const joseHeader = { - ...parsedProt, - ...jws.header, - }; - const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader); - let b64 = true; - if (extensions.has('b64')) { - b64 = parsedProt.b64; - if (typeof b64 !== 'boolean') { - throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); - } - } - const { alg } = joseHeader; - if (typeof alg !== 'string' || !alg) { - throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); - } - const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms); - if (algorithms && !algorithms.has(alg)) { - throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); - } - if (b64) { - if (typeof jws.payload !== 'string') { - throw new errors_js_1.JWSInvalid('JWS Payload must be a string'); - } - } - else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { - throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); - } - let resolvedKey = false; - if (typeof key === 'function') { - key = await key(parsedProt, jws); - resolvedKey = true; - (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify'); - if ((0, is_jwk_js_1.isJWK)(key)) { - key = await (0, import_js_1.importJWK)(key, alg); - } - } - else { - (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify'); - } - const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload); - let signature; - try { - signature = (0, base64url_js_1.decode)(jws.signature); - } - catch { - throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature'); - } - const verified = await (0, verify_js_1.default)(alg, key, signature, data); - if (!verified) { - throw new errors_js_1.JWSSignatureVerificationFailed(); - } - let payload; - if (b64) { - try { - payload = (0, base64url_js_1.decode)(jws.payload); - } - catch { - throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload'); - } - } - else if (typeof jws.payload === 'string') { - payload = buffer_utils_js_1.encoder.encode(jws.payload); - } - else { - payload = jws.payload; - } - const result = { payload }; - if (jws.protected !== undefined) { - result.protectedHeader = parsedProt; - } - if (jws.header !== undefined) { - result.unprotectedHeader = jws.header; - } - if (resolvedKey) { - return { ...result, key }; - } - return result; -} + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", -/***/ }), + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", -/***/ 50443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", -"use strict"; + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GeneralSign = void 0; -const sign_js_1 = __nccwpck_require__(86170); -const errors_js_1 = __nccwpck_require__(15974); -class IndividualSignature { - parent; - protectedHeader; - unprotectedHeader; - options; - key; - constructor(sig, key, options) { - this.parent = sig; - this.key = key; - this.options = options; - } - setProtectedHeader(protectedHeader) { - if (this.protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this.protectedHeader = protectedHeader; - return this; - } - setUnprotectedHeader(unprotectedHeader) { - if (this.unprotectedHeader) { - throw new TypeError('setUnprotectedHeader can only be called once'); - } - this.unprotectedHeader = unprotectedHeader; - return this; - } - addSignature(...args) { - return this.parent.addSignature(...args); - } - sign(...args) { - return this.parent.sign(...args); - } - done() { - return this.parent; - } -} -class GeneralSign { - _payload; - _signatures = []; - constructor(payload) { - this._payload = payload; - } - addSignature(key, options) { - const signature = new IndividualSignature(this, key, options); - this._signatures.push(signature); - return signature; - } - async sign() { - if (!this._signatures.length) { - throw new errors_js_1.JWSInvalid('at least one signature must be added'); - } - const jws = { - signatures: [], - payload: '', - }; - for (let i = 0; i < this._signatures.length; i++) { - const signature = this._signatures[i]; - const flattened = new sign_js_1.FlattenedSign(this._payload); - flattened.setProtectedHeader(signature.protectedHeader); - flattened.setUnprotectedHeader(signature.unprotectedHeader); - const { payload, ...rest } = await flattened.sign(signature.key, signature.options); - if (i === 0) { - jws.payload = payload; - } - else if (jws.payload !== payload) { - throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); - } - jws.signatures.push(rest); - } - return jws; - } -} -exports.GeneralSign = GeneralSign; + "strk10482002": "rk1048", + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", -/***/ }), + "gb198880": "iso646cn", + "cn": "iso646cn", -/***/ 88323: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", -"use strict"; + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generalVerify = generalVerify; -const verify_js_1 = __nccwpck_require__(56358); -const errors_js_1 = __nccwpck_require__(15974); -const is_object_js_1 = __nccwpck_require__(92242); -async function generalVerify(jws, key, options) { - if (!(0, is_object_js_1.default)(jws)) { - throw new errors_js_1.JWSInvalid('General JWS must be an object'); - } - if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) { - throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type'); - } - for (const signature of jws.signatures) { - try { - return await (0, verify_js_1.flattenedVerify)({ - header: signature.header, - payload: jws.payload, - protected: signature.protected, - signature: signature.signature, - }, key, options); - } - catch { - } - } - throw new errors_js_1.JWSSignatureVerificationFailed(); -} /***/ }), -/***/ 95339: +/***/ 8771: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.jwtDecrypt = jwtDecrypt; -const decrypt_js_1 = __nccwpck_require__(14298); -const jwt_claims_set_js_1 = __nccwpck_require__(13354); -const errors_js_1 = __nccwpck_require__(15974); -async function jwtDecrypt(jwt, key, options) { - const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options); - const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options); - const { protectedHeader } = decrypted; - if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { - throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch'); - } - if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { - throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch'); - } - if (protectedHeader.aud !== undefined && - JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { - throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch'); - } - const result = { payload, protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: decrypted.key }; - } - return result; -} - - -/***/ }), +var Buffer = (__nccwpck_require__(12803).Buffer); -/***/ 38375: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js -"use strict"; +// == UTF16-BE codec. ========================================================== -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.EncryptJWT = void 0; -const encrypt_js_1 = __nccwpck_require__(4434); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const produce_js_1 = __nccwpck_require__(37318); -class EncryptJWT extends produce_js_1.ProduceJWT { - _cek; - _iv; - _keyManagementParameters; - _protectedHeader; - _replicateIssuerAsHeader; - _replicateSubjectAsHeader; - _replicateAudienceAsHeader; - setProtectedHeader(protectedHeader) { - if (this._protectedHeader) { - throw new TypeError('setProtectedHeader can only be called once'); - } - this._protectedHeader = protectedHeader; - return this; - } - setKeyManagementParameters(parameters) { - if (this._keyManagementParameters) { - throw new TypeError('setKeyManagementParameters can only be called once'); - } - this._keyManagementParameters = parameters; - return this; - } - setContentEncryptionKey(cek) { - if (this._cek) { - throw new TypeError('setContentEncryptionKey can only be called once'); - } - this._cek = cek; - return this; - } - setInitializationVector(iv) { - if (this._iv) { - throw new TypeError('setInitializationVector can only be called once'); - } - this._iv = iv; - return this; - } - replicateIssuerAsHeader() { - this._replicateIssuerAsHeader = true; - return this; - } - replicateSubjectAsHeader() { - this._replicateSubjectAsHeader = true; - return this; - } - replicateAudienceAsHeader() { - this._replicateAudienceAsHeader = true; - return this; - } - async encrypt(key, options) { - const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); - if (this._replicateIssuerAsHeader) { - this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; - } - if (this._replicateSubjectAsHeader) { - this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; - } - if (this._replicateAudienceAsHeader) { - this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; - } - enc.setProtectedHeader(this._protectedHeader); - if (this._iv) { - enc.setInitializationVector(this._iv); - } - if (this._cek) { - enc.setContentEncryptionKey(this._cek); - } - if (this._keyManagementParameters) { - enc.setKeyManagementParameters(this._keyManagementParameters); - } - return enc.encrypt(key, options); - } +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { } -exports.EncryptJWT = EncryptJWT; +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; -/***/ }), -/***/ 37318: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// -- Encoding -"use strict"; +function Utf16BEEncoder() { +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProduceJWT = void 0; -const epoch_js_1 = __nccwpck_require__(40485); -const is_object_js_1 = __nccwpck_require__(92242); -const secs_js_1 = __nccwpck_require__(40556); -function validateInput(label, input) { - if (!Number.isFinite(input)) { - throw new TypeError(`Invalid ${label} input`); +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; } - return input; + return buf; } -class ProduceJWT { - _payload; - constructor(payload = {}) { - if (!(0, is_object_js_1.default)(payload)) { - throw new TypeError('JWT Claims Set MUST be an object'); - } - this._payload = payload; - } - setIssuer(issuer) { - this._payload = { ...this._payload, iss: issuer }; - return this; - } - setSubject(subject) { - this._payload = { ...this._payload, sub: subject }; - return this; - } - setAudience(audience) { - this._payload = { ...this._payload, aud: audience }; - return this; - } - setJti(jwtId) { - this._payload = { ...this._payload, jti: jwtId }; - return this; - } - setNotBefore(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, nbf: validateInput('setNotBefore', (0, epoch_js_1.default)(input)) }; - } - else { - this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; - } - return this; - } - setExpirationTime(input) { - if (typeof input === 'number') { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, exp: validateInput('setExpirationTime', (0, epoch_js_1.default)(input)) }; - } - else { - this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; - } - return this; - } - setIssuedAt(input) { - if (typeof input === 'undefined') { - this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) }; - } - else if (input instanceof Date) { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(input)) }; - } - else if (typeof input === 'string') { - this._payload = { - ...this._payload, - iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input)), - }; - } - else { - this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) }; - } - return this; - } + +Utf16BEEncoder.prototype.end = function() { } -exports.ProduceJWT = ProduceJWT; -/***/ }), +// -- Decoding -/***/ 22713: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function Utf16BEDecoder() { + this.overflowByte = -1; +} -"use strict"; +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SignJWT = void 0; -const sign_js_1 = __nccwpck_require__(21760); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const produce_js_1 = __nccwpck_require__(37318); -class SignJWT extends produce_js_1.ProduceJWT { - _protectedHeader; - setProtectedHeader(protectedHeader) { - this._protectedHeader = protectedHeader; - return this; + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; } - async sign(key, options) { - const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); - sig.setProtectedHeader(this._protectedHeader); - if (Array.isArray(this._protectedHeader?.crit) && - this._protectedHeader.crit.includes('b64') && - this._protectedHeader.b64 === false) { - throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - return sig.sign(key, options); + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); } -exports.SignJWT = SignJWT; +Utf16BEDecoder.prototype.end = function() { + this.overflowByte = -1; +} -/***/ }), -/***/ 40560: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); -"use strict"; +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UnsecuredJWT = void 0; -const base64url = __nccwpck_require__(12635); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const errors_js_1 = __nccwpck_require__(15974); -const jwt_claims_set_js_1 = __nccwpck_require__(13354); -const produce_js_1 = __nccwpck_require__(37318); -class UnsecuredJWT extends produce_js_1.ProduceJWT { - encode() { - const header = base64url.encode(JSON.stringify({ alg: 'none' })); - const payload = base64url.encode(JSON.stringify(this._payload)); - return `${header}.${payload}.`; - } - static decode(jwt, options) { - if (typeof jwt !== 'string') { - throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string'); - } - const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); - if (length !== 3 || signature !== '') { - throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); - } - let header; - try { - header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader))); - if (header.alg !== 'none') - throw new Error(); - } - catch { - throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); - } - const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options); - return { payload, header }; - } +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; } -exports.UnsecuredJWT = UnsecuredJWT; +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; -/***/ }), -/***/ 35297: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// -- Encoding (pass-through) -"use strict"; +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.jwtVerify = jwtVerify; -const verify_js_1 = __nccwpck_require__(94212); -const jwt_claims_set_js_1 = __nccwpck_require__(13354); -const errors_js_1 = __nccwpck_require__(15974); -async function jwtVerify(jwt, key, options) { - const verified = await (0, verify_js_1.compactVerify)(jwt, key, options); - if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { - throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); - } - const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options); - const result = { payload, protectedHeader: verified.protectedHeader }; - if (typeof key === 'function') { - return { ...result, key: verified.key }; - } - return result; +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); } +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} -/***/ }), -/***/ 48108: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// -- Decoding -"use strict"; +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBufs = []; + this.initialBufsLen = 0; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.exportSPKI = exportSPKI; -exports.exportPKCS8 = exportPKCS8; -exports.exportJWK = exportJWK; -const asn1_js_1 = __nccwpck_require__(12774); -const asn1_js_2 = __nccwpck_require__(12774); -const key_to_jwk_js_1 = __nccwpck_require__(9041); -async function exportSPKI(key) { - return (0, asn1_js_1.toSPKI)(key); + this.options = options || {}; + this.iconv = codec.iconv; } -async function exportPKCS8(key) { - return (0, asn1_js_2.toPKCS8)(key); + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBufs.push(buf); + this.initialBufsLen += buf.length; + + if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + + return this.decoder.write(buf); } -async function exportJWK(key) { - return (0, key_to_jwk_js_1.default)(key); + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + var trail = this.decoder.end(); + if (trail) + resStr += trail; + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; + } + return this.decoder.end(); } +function detectEncoding(bufs, defaultEncoding) { + var b = []; + var charsProcessed = 0; + var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. -/***/ }), + outer_loop: + for (var i = 0; i < bufs.length; i++) { + var buf = bufs[i]; + for (var j = 0; j < buf.length; j++) { + b.push(buf[j]); + if (b.length === 2) { + if (charsProcessed === 0) { + // Check BOM first. + if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; + if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; + } -/***/ 87820: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; + if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; -"use strict"; + b.length = 0; + charsProcessed++; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generateKeyPair = generateKeyPair; -const generate_js_1 = __nccwpck_require__(10088); -async function generateKeyPair(alg, options) { - return (0, generate_js_1.generateKeyPair)(alg, options); + if (charsProcessed >= 100) { + break outer_loop; + } + } + } + } + + // Make decisions. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; + if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; + + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || 'utf-16le'; } + + /***/ }), -/***/ 37152: +/***/ 62021: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generateSecret = generateSecret; -const generate_js_1 = __nccwpck_require__(10088); -async function generateSecret(alg, options) { - return (0, generate_js_1.generateSecret)(alg, options); + +var Buffer = (__nccwpck_require__(12803).Buffer); + +// == UTF32-LE/BE codec. ========================================================== + +exports._utf32 = Utf32Codec; + +function Utf32Codec(codecOptions, iconv) { + this.iconv = iconv; + this.bomAware = true; + this.isLE = codecOptions.isLE; } +exports.utf32le = { type: '_utf32', isLE: true }; +exports.utf32be = { type: '_utf32', isLE: false }; -/***/ }), +// Aliases +exports.ucs4le = 'utf32le'; +exports.ucs4be = 'utf32be'; -/***/ 45647: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Utf32Codec.prototype.encoder = Utf32Encoder; +Utf32Codec.prototype.decoder = Utf32Decoder; -"use strict"; +// -- Encoding -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.importSPKI = importSPKI; -exports.importX509 = importX509; -exports.importPKCS8 = importPKCS8; -exports.importJWK = importJWK; -const base64url_js_1 = __nccwpck_require__(12635); -const asn1_js_1 = __nccwpck_require__(12774); -const jwk_to_key_js_1 = __nccwpck_require__(80939); -const errors_js_1 = __nccwpck_require__(15974); -const is_object_js_1 = __nccwpck_require__(92242); -async function importSPKI(spki, alg, options) { - if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { - throw new TypeError('"spki" must be SPKI formatted string'); - } - return (0, asn1_js_1.fromSPKI)(spki, alg, options); -} -async function importX509(x509, alg, options) { - if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { - throw new TypeError('"x509" must be X.509 formatted string'); - } - return (0, asn1_js_1.fromX509)(x509, alg, options); +function Utf32Encoder(options, codec) { + this.isLE = codec.isLE; + this.highSurrogate = 0; } -async function importPKCS8(pkcs8, alg, options) { - if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { - throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + +Utf32Encoder.prototype.write = function(str) { + var src = Buffer.from(str, 'ucs2'); + var dst = Buffer.alloc(src.length * 2); + var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; + var offset = 0; + + for (var i = 0; i < src.length; i += 2) { + var code = src.readUInt16LE(i); + var isHighSurrogate = (0xD800 <= code && code < 0xDC00); + var isLowSurrogate = (0xDC00 <= code && code < 0xE000); + + if (this.highSurrogate) { + if (isHighSurrogate || !isLowSurrogate) { + // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low + // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character + // (technically wrong, but expected by some applications, like Windows file names). + write32.call(dst, this.highSurrogate, offset); + offset += 4; + } + else { + // Create 32-bit value from high and low surrogates; + var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; + + write32.call(dst, codepoint, offset); + offset += 4; + this.highSurrogate = 0; + + continue; + } + } + + if (isHighSurrogate) + this.highSurrogate = code; + else { + // Even if the current character is a low surrogate, with no previous high surrogate, we'll + // encode it as a semi-invalid stand-alone character for the same reasons expressed above for + // unpaired high surrogates. + write32.call(dst, code, offset); + offset += 4; + this.highSurrogate = 0; + } } - return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options); + + if (offset < dst.length) + dst = dst.slice(0, offset); + + return dst; +}; + +Utf32Encoder.prototype.end = function() { + // Treat any leftover high surrogate as a semi-valid independent character. + if (!this.highSurrogate) + return; + + var buf = Buffer.alloc(4); + + if (this.isLE) + buf.writeUInt32LE(this.highSurrogate, 0); + else + buf.writeUInt32BE(this.highSurrogate, 0); + + this.highSurrogate = 0; + + return buf; +}; + +// -- Decoding + +function Utf32Decoder(options, codec) { + this.isLE = codec.isLE; + this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); + this.overflow = []; } -async function importJWK(jwk, alg) { - if (!(0, is_object_js_1.default)(jwk)) { - throw new TypeError('JWK must be an object'); - } - alg ||= jwk.alg; - switch (jwk.kty) { - case 'oct': - if (typeof jwk.k !== 'string' || !jwk.k) { - throw new TypeError('missing "k" (Key Value) Parameter value'); - } - return (0, base64url_js_1.decode)(jwk.k); - case 'RSA': - if (jwk.oth !== undefined) { - throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + +Utf32Decoder.prototype.write = function(src) { + if (src.length === 0) + return ''; + + var i = 0; + var codepoint = 0; + var dst = Buffer.alloc(src.length + 4); + var offset = 0; + var isLE = this.isLE; + var overflow = this.overflow; + var badChar = this.badChar; + + if (overflow.length > 0) { + for (; i < src.length && overflow.length < 4; i++) + overflow.push(src[i]); + + if (overflow.length === 4) { + // NOTE: codepoint is a signed int32 and can be negative. + // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). + if (isLE) { + codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); + } else { + codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); } - case 'EC': - case 'OKP': - return (0, jwk_to_key_js_1.default)({ ...jwk, alg }); - default: - throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); + overflow.length = 0; + + offset = _writeCodepoint(dst, offset, codepoint, badChar); + } + } + + // Main loop. Should be as optimized as possible. + for (; i < src.length - 3; i += 4) { + // NOTE: codepoint is a signed int32 and can be negative. + if (isLE) { + codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); + } else { + codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); + } + offset = _writeCodepoint(dst, offset, codepoint, badChar); } -} + // Keep overflowing bytes. + for (; i < src.length; i++) { + overflow.push(src[i]); + } -/***/ }), + return dst.slice(0, offset).toString('ucs2'); +}; -/***/ 95864: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function _writeCodepoint(dst, offset, codepoint, badChar) { + // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. + if (codepoint < 0 || codepoint > 0x10FFFF) { + // Not a valid Unicode codepoint + codepoint = badChar; + } -"use strict"; + // Ephemeral Planes: Write high surrogate. + if (codepoint >= 0x10000) { + codepoint -= 0x10000; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.wrap = wrap; -exports.unwrap = unwrap; -const encrypt_js_1 = __nccwpck_require__(36286); -const decrypt_js_1 = __nccwpck_require__(52806); -const base64url_js_1 = __nccwpck_require__(12635); -async function wrap(alg, key, cek, iv) { - const jweAlgorithm = alg.slice(0, 7); - const wrapped = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0)); - return { - encryptedKey: wrapped.ciphertext, - iv: (0, base64url_js_1.encode)(wrapped.iv), - tag: (0, base64url_js_1.encode)(wrapped.tag), - }; -} -async function unwrap(alg, key, encryptedKey, iv, tag) { - const jweAlgorithm = alg.slice(0, 7); - return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); -} + var high = 0xD800 | (codepoint >> 10); + dst[offset++] = high & 0xff; + dst[offset++] = high >> 8; + // Low surrogate is written below. + var codepoint = 0xDC00 | (codepoint & 0x3FF); + } -/***/ }), + // Write BMP char or low surrogate. + dst[offset++] = codepoint & 0xff; + dst[offset++] = codepoint >> 8; -/***/ 45734: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return offset; +}; -"use strict"; +Utf32Decoder.prototype.end = function() { + this.overflow.length = 0; +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decoder = exports.encoder = void 0; -exports.concat = concat; -exports.p2s = p2s; -exports.uint64be = uint64be; -exports.uint32be = uint32be; -exports.lengthAndInput = lengthAndInput; -exports.concatKdf = concatKdf; -const digest_js_1 = __nccwpck_require__(12931); -exports.encoder = new TextEncoder(); -exports.decoder = new TextDecoder(); -const MAX_INT32 = 2 ** 32; -function concat(...buffers) { - const size = buffers.reduce((acc, { length }) => acc + length, 0); - const buf = new Uint8Array(size); - let i = 0; - for (const buffer of buffers) { - buf.set(buffer, i); - i += buffer.length; - } - return buf; -} -function p2s(alg, p2sInput) { - return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput); -} -function writeUInt32BE(buf, value, offset) { - if (value < 0 || value >= MAX_INT32) { - throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); - } - buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); -} -function uint64be(value) { - const high = Math.floor(value / MAX_INT32); - const low = value % MAX_INT32; - const buf = new Uint8Array(8); - writeUInt32BE(buf, high, 0); - writeUInt32BE(buf, low, 4); - return buf; -} -function uint32be(value) { - const buf = new Uint8Array(4); - writeUInt32BE(buf, value); - return buf; -} -function lengthAndInput(input) { - return concat(uint32be(input.length), input); -} -async function concatKdf(secret, bits, value) { - const iterations = Math.ceil((bits >> 3) / 32); - const res = new Uint8Array(iterations * 32); - for (let iter = 0; iter < iterations; iter++) { - const buf = new Uint8Array(4 + secret.length + value.length); - buf.set(uint32be(iter + 1)); - buf.set(secret, 4); - buf.set(value, 4 + secret.length); - res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32); - } - return res.slice(0, bits >> 3); -} +// == UTF-32 Auto codec ============================================================= +// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. +// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 +// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); +// Encoder prepends BOM (which can be overridden with (addBOM: false}). -/***/ }), +exports.utf32 = Utf32AutoCodec; +exports.ucs4 = 'utf32'; -/***/ 87937: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function Utf32AutoCodec(options, iconv) { + this.iconv = iconv; +} -"use strict"; +Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; +Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bitLength = bitLength; -const errors_js_1 = __nccwpck_require__(15974); -const random_js_1 = __nccwpck_require__(23376); -function bitLength(alg) { - switch (alg) { - case 'A128GCM': - return 128; - case 'A192GCM': - return 192; - case 'A256GCM': - case 'A128CBC-HS256': - return 256; - case 'A192CBC-HS384': - return 384; - case 'A256CBC-HS512': - return 512; - default: - throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); - } -} -exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); +// -- Encoding +function Utf32AutoEncoder(options, codec) { + options = options || {}; -/***/ }), + if (options.addBOM === undefined) + options.addBOM = true; -/***/ 63351: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); +} -"use strict"; +Utf32AutoEncoder.prototype.write = function(str) { + return this.encoder.write(str); +}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const errors_js_1 = __nccwpck_require__(15974); -const iv_js_1 = __nccwpck_require__(56565); -const checkIvLength = (enc, iv) => { - if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) { - throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length'); - } +Utf32AutoEncoder.prototype.end = function() { + return this.encoder.end(); }; -exports["default"] = checkIvLength; +// -- Decoding -/***/ }), +function Utf32AutoDecoder(options, codec) { + this.decoder = null; + this.initialBufs = []; + this.initialBufsLen = 0; + this.options = options || {}; + this.iconv = codec.iconv; +} -/***/ 29555: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Utf32AutoDecoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBufs.push(buf); + this.initialBufsLen += buf.length; -"use strict"; + if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) + return ''; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkKeyTypeWithJwk = void 0; -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const jwk = __nccwpck_require__(91229); -const tag = (key) => key?.[Symbol.toStringTag]; -const jwkMatchesOp = (alg, key, usage) => { - if (key.use !== undefined && key.use !== 'sig') { - throw new TypeError('Invalid key for this operation, when present its use must be sig'); - } - if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) { - throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); - } - if (key.alg !== undefined && key.alg !== alg) { - throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); - } - return true; -}; -const symmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (key instanceof Uint8Array) - return; - if (allowJwk && jwk.isJWK(key)) { - if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); - } - if (!(0, is_key_like_js_1.default)(key)) { - throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null)); - } - if (key.type !== 'secret') { - throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); - } -}; -const asymmetricTypeCheck = (alg, key, usage, allowJwk) => { - if (allowJwk && jwk.isJWK(key)) { - switch (usage) { - case 'sign': - if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a private JWK`); - case 'verify': - if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) - return; - throw new TypeError(`JSON Web Key for this operation be a public JWK`); - } - } - if (!(0, is_key_like_js_1.default)(key)) { - throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, allowJwk ? 'JSON Web Key' : null)); - } - if (key.type === 'secret') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); - } - if (usage === 'sign' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); - } - if (usage === 'decrypt' && key.type === 'public') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); - } - if (key.algorithm && usage === 'verify' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); - } - if (key.algorithm && usage === 'encrypt' && key.type === 'private') { - throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); - } -}; -function checkKeyType(allowJwk, alg, key, usage) { - const symmetric = alg.startsWith('HS') || - alg === 'dir' || - alg.startsWith('PBES2') || - /^A\d{3}(?:GCM)?KW$/.test(alg); - if (symmetric) { - symmetricTypeCheck(alg, key, usage, allowJwk); - } - else { - asymmetricTypeCheck(alg, key, usage, allowJwk); + // We have enough bytes -> detect endianness. + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); + + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; } -} -exports["default"] = checkKeyType.bind(undefined, false); -exports.checkKeyTypeWithJwk = checkKeyType.bind(undefined, true); + return this.decoder.write(buf); +}; -/***/ }), +Utf32AutoDecoder.prototype.end = function() { + if (!this.decoder) { + var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); -/***/ 88040: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var resStr = ''; + for (var i = 0; i < this.initialBufs.length; i++) + resStr += this.decoder.write(this.initialBufs[i]); -"use strict"; + var trail = this.decoder.end(); + if (trail) + resStr += trail; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = checkP2s; -const errors_js_1 = __nccwpck_require__(15974); -function checkP2s(p2s) { - if (!(p2s instanceof Uint8Array) || p2s.length < 8) { - throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets'); + this.initialBufs.length = this.initialBufsLen = 0; + return resStr; } -} + return this.decoder.end(); +}; -/***/ }), +function detectEncoding(bufs, defaultEncoding) { + var b = []; + var charsProcessed = 0; + var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. + var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. -/***/ 26319: -/***/ ((__unused_webpack_module, exports) => { + outer_loop: + for (var i = 0; i < bufs.length; i++) { + var buf = bufs[i]; + for (var j = 0; j < buf.length; j++) { + b.push(buf[j]); + if (b.length === 4) { + if (charsProcessed === 0) { + // Check BOM first. + if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { + return 'utf-32le'; + } + if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { + return 'utf-32be'; + } + } -"use strict"; + if (b[0] !== 0 || b[1] > 0x10) invalidBE++; + if (b[3] !== 0 || b[2] > 0x10) invalidLE++; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkSigCryptoKey = checkSigCryptoKey; -exports.checkEncCryptoKey = checkEncCryptoKey; -function unusable(name, prop = 'algorithm.name') { - return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); -} -function isAlgorithm(algorithm, name) { - return algorithm.name === name; -} -function getHashLength(hash) { - return parseInt(hash.name.slice(4), 10); -} -function getNamedCurve(alg) { - switch (alg) { - case 'ES256': - return 'P-256'; - case 'ES384': - return 'P-384'; - case 'ES512': - return 'P-521'; - default: - throw new Error('unreachable'); - } -} -function checkUsage(key, usages) { - if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { - let msg = 'CryptoKey does not support this operation, its usages must include '; - if (usages.length > 2) { - const last = usages.pop(); - msg += `one of ${usages.join(', ')}, or ${last}.`; - } - else if (usages.length === 2) { - msg += `one of ${usages[0]} or ${usages[1]}.`; - } - else { - msg += `${usages[0]}.`; - } - throw new TypeError(msg); - } -} -function checkSigCryptoKey(key, alg, ...usages) { - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': { - if (!isAlgorithm(key.algorithm, 'HMAC')) - throw unusable('HMAC'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'RS256': - case 'RS384': - case 'RS512': { - if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) - throw unusable('RSASSA-PKCS1-v1_5'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'PS256': - case 'PS384': - case 'PS512': { - if (!isAlgorithm(key.algorithm, 'RSA-PSS')) - throw unusable('RSA-PSS'); - const expected = parseInt(alg.slice(2), 10); - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; - } - case 'EdDSA': { - if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { - throw unusable('Ed25519 or Ed448'); - } - break; - } - case 'ES256': - case 'ES384': - case 'ES512': { - if (!isAlgorithm(key.algorithm, 'ECDSA')) - throw unusable('ECDSA'); - const expected = getNamedCurve(alg); - const actual = key.algorithm.namedCurve; - if (actual !== expected) - throw unusable(expected, 'algorithm.namedCurve'); - break; - } - default: - throw new TypeError('CryptoKey does not support this operation'); - } - checkUsage(key, usages); -} -function checkEncCryptoKey(key, alg, ...usages) { - switch (alg) { - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': { - if (!isAlgorithm(key.algorithm, 'AES-GCM')) - throw unusable('AES-GCM'); - const expected = parseInt(alg.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, 'algorithm.length'); - break; - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - if (!isAlgorithm(key.algorithm, 'AES-KW')) - throw unusable('AES-KW'); - const expected = parseInt(alg.slice(1, 4), 10); - const actual = key.algorithm.length; - if (actual !== expected) - throw unusable(expected, 'algorithm.length'); - break; - } - case 'ECDH': { - switch (key.algorithm.name) { - case 'ECDH': - case 'X25519': - case 'X448': - break; - default: - throw unusable('ECDH, X25519, or X448'); + if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; + if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; + + b.length = 0; + charsProcessed++; + + if (charsProcessed >= 100) { + break outer_loop; + } } - break; - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': - if (!isAlgorithm(key.algorithm, 'PBKDF2')) - throw unusable('PBKDF2'); - break; - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) - throw unusable('RSA-OAEP'); - const expected = parseInt(alg.slice(9), 10) || 1; - const actual = getHashLength(key.algorithm.hash); - if (actual !== expected) - throw unusable(`SHA-${expected}`, 'algorithm.hash'); - break; } - default: - throw new TypeError('CryptoKey does not support this operation'); } - checkUsage(key, usages); + + // Make decisions. + if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; + if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; + + // Couldn't decide (likely all zeros or not enough data). + return defaultEncoding || 'utf-32le'; } /***/ }), -/***/ 56243: +/***/ 28231: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const aeskw_js_1 = __nccwpck_require__(76202); -const ECDH = __nccwpck_require__(43359); -const pbes2kw_js_1 = __nccwpck_require__(52741); -const rsaes_js_1 = __nccwpck_require__(61129); -const base64url_js_1 = __nccwpck_require__(12635); -const normalize_key_js_1 = __nccwpck_require__(51276); -const errors_js_1 = __nccwpck_require__(15974); -const cek_js_1 = __nccwpck_require__(87937); -const import_js_1 = __nccwpck_require__(45647); -const check_key_type_js_1 = __nccwpck_require__(29555); -const is_object_js_1 = __nccwpck_require__(92242); -const aesgcmkw_js_1 = __nccwpck_require__(95864); -async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { - (0, check_key_type_js_1.default)(alg, key, 'decrypt'); - key = (await normalize_key_js_1.default.normalizePrivateKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - if (encryptedKey !== undefined) - throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); - return key; - } - case 'ECDH-ES': - if (encryptedKey !== undefined) - throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!(0, is_object_js_1.default)(joseHeader.epk)) - throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); - if (!ECDH.ecdhAllowed(key)) - throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); - const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg); - let partyUInfo; - let partyVInfo; - if (joseHeader.apu !== undefined) { - if (typeof joseHeader.apu !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); - try { - partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the apu'); - } - } - if (joseHeader.apv !== undefined) { - if (typeof joseHeader.apv !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); - try { - partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the apv'); - } - } - const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); - if (alg === 'ECDH-ES') - return sharedSecret; - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey); - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey); - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - if (typeof joseHeader.p2c !== 'number') - throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); - const p2cLimit = options?.maxPBES2Count || 10_000; - if (joseHeader.p2c > p2cLimit) - throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); - if (typeof joseHeader.p2s !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); - let p2s; - try { - p2s = (0, base64url_js_1.decode)(joseHeader.p2s); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the p2s'); - } - return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s); - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey); - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - if (encryptedKey === undefined) - throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); - if (typeof joseHeader.iv !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); - if (typeof joseHeader.tag !== 'string') - throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); - let iv; - try { - iv = (0, base64url_js_1.decode)(joseHeader.iv); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); - } - let tag; - try { - tag = (0, base64url_js_1.decode)(joseHeader.tag); - } - catch { - throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); - } - return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag); - } - default: { - throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); - } - } +var Buffer = (__nccwpck_require__(12803).Buffer); + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; } -exports["default"] = decryptKeyManagement; +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} -/***/ }), +Utf7Encoder.prototype.end = function() { +} -/***/ 96539: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// -- Decoding -Object.defineProperty(exports, "__esModule", ({ value: true })); -const aeskw_js_1 = __nccwpck_require__(76202); -const ECDH = __nccwpck_require__(43359); -const pbes2kw_js_1 = __nccwpck_require__(52741); -const rsaes_js_1 = __nccwpck_require__(61129); -const base64url_js_1 = __nccwpck_require__(12635); -const normalize_key_js_1 = __nccwpck_require__(51276); -const cek_js_1 = __nccwpck_require__(87937); -const errors_js_1 = __nccwpck_require__(15974); -const export_js_1 = __nccwpck_require__(48108); -const check_key_type_js_1 = __nccwpck_require__(29555); -const aesgcmkw_js_1 = __nccwpck_require__(95864); -async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { - let encryptedKey; - let parameters; - let cek; - (0, check_key_type_js_1.default)(alg, key, 'encrypt'); - key = (await normalize_key_js_1.default.normalizePublicKey?.(key, alg)) || key; - switch (alg) { - case 'dir': { - cek = key; - break; - } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - if (!ECDH.ecdhAllowed(key)) { - throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; } - const { apu, apv } = providedParameters; - let { epk: ephemeralKey } = providedParameters; - ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey; - const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey); - const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); - parameters = { epk: { x, crv, kty } }; - if (kty === 'EC') - parameters.epk.y = y; - if (apu) - parameters.apu = (0, base64url_js_1.encode)(apu); - if (apv) - parameters.apv = (0, base64url_js_1.encode)(apv); - if (alg === 'ECDH-ES') { - cek = sharedSecret; - break; + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii"); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; } - cek = providedCek || (0, cek_js_1.default)(enc); - const kwAlg = alg.slice(-6); - encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek); - break; - } - case 'RSA1_5': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': { - cek = providedCek || (0, cek_js_1.default)(enc); - encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek); - break; - } - case 'PBES2-HS256+A128KW': - case 'PBES2-HS384+A192KW': - case 'PBES2-HS512+A256KW': { - cek = providedCek || (0, cek_js_1.default)(enc); - const { p2c, p2s } = providedParameters; - ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s)); - break; - } - case 'A128KW': - case 'A192KW': - case 'A256KW': { - cek = providedCek || (0, cek_js_1.default)(enc); - encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek); - break; - } - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': { - cek = providedCek || (0, cek_js_1.default)(enc); - const { iv } = providedParameters; - ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv)); - break; - } - default: { - throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } - return { cek, encryptedKey, parameters }; + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii"); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; } -exports["default"] = encryptKeyManagement; +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} -/***/ }), -/***/ 40485: -/***/ ((__unused_webpack_module, exports) => { +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = (date) => Math.floor(date.getTime() / 1000); +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; -/***/ }), -/***/ 16632: -/***/ ((__unused_webpack_module, exports) => { +// -- Encoding -"use strict"; +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.withAlg = withAlg; -function message(msg, actual, ...types) { - types = types.filter(Boolean); - if (types.length > 2) { - const last = types.pop(); - msg += `one of type ${types.join(', ')}, or ${last}.`; - } - else if (types.length === 2) { - msg += `one of type ${types[0]} or ${types[1]}.`; - } - else { - msg += `of type ${types[0]}.`; - } - if (actual == null) { - msg += ` Received ${actual}`; - } - else if (typeof actual === 'function' && actual.name) { - msg += ` Received function ${actual.name}`; +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } } - else if (typeof actual === 'object' && actual != null) { - if (actual.constructor?.name) { - msg += ` Received an instance of ${actual.constructor.name}`; + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; } - return msg; + + return buf.slice(0, bufIdx); } -exports["default"] = (actual, ...types) => { - return message('Key must be ', actual, ...types); -}; -function withAlg(alg, actual, ...types) { - return message(`Key for the ${alg} algorithm must be `, actual, ...types); + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; } +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; -/***/ }), +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; -/***/ 21853: -/***/ ((__unused_webpack_module, exports) => { + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). -"use strict"; + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const isDisjoint = (...headers) => { - const sources = headers.filter(Boolean); - if (sources.length === 0 || sources.length === 1) { - return true; - } - let acc; - for (const header of sources) { - const parameters = Object.keys(header); - if (!acc || acc.size === 0) { - acc = new Set(parameters); - continue; - } - for (const parameter of parameters) { - if (acc.has(parameter)) { - return false; + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; } - acc.add(parameter); - } - } - return true; -}; -exports["default"] = isDisjoint; + } + } + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/'); -/***/ }), + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); -/***/ 91229: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } -"use strict"; + this.inBase64 = inBase64; + this.base64Accum = base64Accum; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isJWK = isJWK; -exports.isPrivateJWK = isPrivateJWK; -exports.isPublicJWK = isPublicJWK; -exports.isSecretJWK = isSecretJWK; -const is_object_js_1 = __nccwpck_require__(92242); -function isJWK(key) { - return (0, is_object_js_1.default)(key) && typeof key.kty === 'string'; -} -function isPrivateJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'string'; -} -function isPublicJWK(key) { - return key.kty !== 'oct' && typeof key.d === 'undefined'; + return res; } -function isSecretJWK(key) { - return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string'; + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; } + + /***/ }), -/***/ 92242: +/***/ 74250: /***/ ((__unused_webpack_module, exports) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = isObject; -function isObjectLike(value) { - return typeof value === 'object' && value !== null; + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; } -function isObject(input) { - if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { - return false; - } - if (Object.getPrototypeOf(input) === null) { - return true; - } - let proto = input; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; } - return Object.getPrototypeOf(input) === proto; + + return this.encoder.write(str); } +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} -/***/ }), -/***/ 56565: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +//------------------------------------------------------------------------------ -"use strict"; +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bitLength = bitLength; -const errors_js_1 = __nccwpck_require__(15974); -const random_js_1 = __nccwpck_require__(23376); -function bitLength(alg) { - switch (alg) { - case 'A128GCM': - case 'A128GCMKW': - case 'A192GCM': - case 'A192GCMKW': - case 'A256GCM': - case 'A256GCMKW': - return 96; - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return 128; - default: - throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); } -exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); + /***/ }), -/***/ 13354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 31748: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const epoch_js_1 = __nccwpck_require__(40485); -const secs_js_1 = __nccwpck_require__(40556); -const is_object_js_1 = __nccwpck_require__(92242); -const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); -const checkAudiencePresence = (audPayload, audOption) => { - if (typeof audPayload === 'string') { - return audOption.includes(audPayload); - } - if (Array.isArray(audPayload)) { - return audOption.some(Set.prototype.has.bind(new Set(audPayload))); - } - return false; -}; -exports["default"] = (protectedHeader, encodedPayload, options = {}) => { - let payload; - try { - payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload)); - } - catch { - } - if (!(0, is_object_js_1.default)(payload)) { - throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object'); - } - const { typ } = options; - if (typ && - (typeof protectedHeader.typ !== 'string' || - normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed'); - } - const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; - const presenceCheck = [...requiredClaims]; - if (maxTokenAge !== undefined) - presenceCheck.push('iat'); - if (audience !== undefined) - presenceCheck.push('aud'); - if (subject !== undefined) - presenceCheck.push('sub'); - if (issuer !== undefined) - presenceCheck.push('iss'); - for (const claim of new Set(presenceCheck.reverse())) { - if (!(claim in payload)) { - throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing'); - } - } - if (issuer && - !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed'); - } - if (subject && payload.sub !== subject) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed'); - } - if (audience && - !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { - throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed'); - } - let tolerance; - switch (typeof options.clockTolerance) { - case 'string': - tolerance = (0, secs_js_1.default)(options.clockTolerance); - break; - case 'number': - tolerance = options.clockTolerance; - break; - case 'undefined': - tolerance = 0; - break; - default: - throw new TypeError('Invalid clockTolerance option type'); - } - const { currentDate } = options; - const now = (0, epoch_js_1.default)(currentDate || new Date()); - if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { - throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid'); - } - if (payload.nbf !== undefined) { - if (typeof payload.nbf !== 'number') { - throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid'); - } - if (payload.nbf > now + tolerance) { - throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed'); - } - } - if (payload.exp !== undefined) { - if (typeof payload.exp !== 'number') { - throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid'); - } - if (payload.exp <= now - tolerance) { - throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed'); - } - } - if (maxTokenAge) { - const age = now - payload.iat; - const max = typeof maxTokenAge === 'number' ? maxTokenAge : (0, secs_js_1.default)(maxTokenAge); - if (age - tolerance > max) { - throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed'); - } - if (age < 0 - tolerance) { - throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed'); - } - } - return payload; -}; - -/***/ }), +var Buffer = (__nccwpck_require__(12803).Buffer); -/***/ 46433: -/***/ ((__unused_webpack_module, exports) => { +var bomHandling = __nccwpck_require__(74250), + iconv = module.exports; -"use strict"; +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.unprotected = void 0; -exports.unprotected = Symbol(); +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. -/***/ }), + var encoder = iconv.getEncoder(encoding, options); -/***/ 40556: -/***/ ((__unused_webpack_module, exports) => { + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} -"use strict"; +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const minute = 60; -const hour = minute * 60; -const day = hour * 24; -const week = day * 7; -const year = day * 365.25; -const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; -exports["default"] = (str) => { - const matched = REGEX.exec(str); - if (!matched || (matched[4] && matched[1])) { - throw new TypeError('Invalid time period format'); - } - const value = parseFloat(matched[2]); - const unit = matched[3].toLowerCase(); - let numericDate; - switch (unit) { - case 'sec': - case 'secs': - case 'second': - case 'seconds': - case 's': - numericDate = Math.round(value); - break; - case 'minute': - case 'minutes': - case 'min': - case 'mins': - case 'm': - numericDate = Math.round(value * minute); - break; - case 'hour': - case 'hours': - case 'hr': - case 'hrs': - case 'h': - numericDate = Math.round(value * hour); - break; - case 'day': - case 'days': - case 'd': - numericDate = Math.round(value * day); - break; - case 'week': - case 'weeks': - case 'w': - numericDate = Math.round(value * week); - break; - default: - numericDate = Math.round(value * year); - break; + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } - if (matched[1] === '-' || matched[4] === 'ago') { - return -numericDate; + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; } - return numericDate; -}; +} +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; -/***/ }), +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = __nccwpck_require__(27585); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); -/***/ 19917: -/***/ ((__unused_webpack_module, exports) => { + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; -"use strict"; + var codecDef = iconv.encodings[enc]; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const validateAlgorithms = (option, algorithms) => { - if (algorithms !== undefined && - (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { - throw new TypeError(`"${option}" option must be an array of strings`); - } - if (!algorithms) { - return undefined; - } - return new Set(algorithms); -}; -exports["default"] = validateAlgorithms; + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; -/***/ }), + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; -/***/ 15595: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); -"use strict"; + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const errors_js_1 = __nccwpck_require__(15974); -function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { - if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { - throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); - } - if (!protectedHeader || protectedHeader.crit === undefined) { - return new Set(); - } - if (!Array.isArray(protectedHeader.crit) || - protectedHeader.crit.length === 0 || - protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { - throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); - } - let recognized; - if (recognizedOption !== undefined) { - recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); - } - else { - recognized = recognizedDefault; - } - for (const parameter of protectedHeader.crit) { - if (!recognized.has(parameter)) { - throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); - } - if (joseHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" is missing`); - } - if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { - throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } - return new Set(protectedHeader.crit); } -exports["default"] = validateCrit; +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} -/***/ }), - -/***/ 76202: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); -"use strict"; + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.unwrap = exports.wrap = void 0; -const node_buffer_1 = __nccwpck_require__(4573); -const node_crypto_1 = __nccwpck_require__(77598); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const ciphers_js_1 = __nccwpck_require__(99271); -const is_key_like_js_1 = __nccwpck_require__(7433); -function checkKeySize(key, alg) { - if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { - throw new TypeError(`Invalid key size for alg: ${alg}`); - } -} -function ensureKeyObject(key, alg, usage) { - if ((0, is_key_object_js_1.default)(key)) { - return key; - } - if (key instanceof Uint8Array) { - return (0, node_crypto_1.createSecretKey)(key); - } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage); - return node_crypto_1.KeyObject.from(key); - } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); + return encoder; } -const wrap = (alg, key, cek) => { - const size = parseInt(alg.slice(1, 4), 10); - const algorithm = `aes${size}-wrap`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - const keyObject = ensureKeyObject(key, alg, 'wrapKey'); - checkKeySize(keyObject, alg); - const cipher = (0, node_crypto_1.createCipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6)); - return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final()); -}; -exports.wrap = wrap; -const unwrap = (alg, key, encryptedKey) => { - const size = parseInt(alg.slice(1, 4), 10); - const algorithm = `aes${size}-wrap`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); - } - const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); - checkKeySize(keyObject, alg); - const cipher = (0, node_crypto_1.createDecipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6)); - return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final()); -}; -exports.unwrap = unwrap; +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} -/***/ }), +// Streaming API +// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add +// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default. +// If you would like to enable it explicitly, please add the following code to your app: +// > iconv.enableStreamingAPI(require('stream')); +iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) { + if (iconv.supportsStreams) + return; -/***/ 12774: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Dependency-inject stream module to create IconvLite stream classes. + var streams = __nccwpck_require__(42281)(stream_module); -"use strict"; + // Not public API yet, but expose the stream classes. + iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0; -const node_crypto_1 = __nccwpck_require__(77598); -const node_buffer_1 = __nccwpck_require__(4573); -const webcrypto_js_1 = __nccwpck_require__(59044); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const genericExport = (keyType, keyFormat, key) => { - let keyObject; - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); - } - keyObject = node_crypto_1.KeyObject.from(key); - } - else if ((0, is_key_object_js_1.default)(key)) { - keyObject = key; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); - } - if (keyObject.type !== keyType) { - throw new TypeError(`key is not a ${keyType} key`); + // Streaming API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } - return keyObject.export({ format: 'pem', type: keyFormat }); -}; -const toSPKI = (key) => { - return genericExport('public', 'spki', key); -}; -exports.toSPKI = toSPKI; -const toPKCS8 = (key) => { - return genericExport('private', 'pkcs8', key); -}; -exports.toPKCS8 = toPKCS8; -const fromPKCS8 = (pem) => (0, node_crypto_1.createPrivateKey)({ - key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), - type: 'pkcs8', - format: 'der', -}); -exports.fromPKCS8 = fromPKCS8; -const fromSPKI = (pem) => (0, node_crypto_1.createPublicKey)({ - key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), - type: 'spki', - format: 'der', -}); -exports.fromSPKI = fromSPKI; -const fromX509 = (pem) => (0, node_crypto_1.createPublicKey)({ - key: pem, - type: 'spki', - format: 'pem', -}); -exports.fromX509 = fromX509; + iconv.decodeStream = function decodeStream(encoding, options) { + return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } -/***/ }), + iconv.supportsStreams = true; +} -/***/ 12635: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments). +var stream_module; +try { + stream_module = __nccwpck_require__(2203); +} catch (e) {} -"use strict"; +if (stream_module && stream_module.Transform) { + iconv.enableStreamingAPI(stream_module); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0; -const node_buffer_1 = __nccwpck_require__(4573); -const buffer_utils_js_1 = __nccwpck_require__(45734); -function normalize(input) { - let encoded = input; - if (encoded instanceof Uint8Array) { - encoded = buffer_utils_js_1.decoder.decode(encoded); - } - return encoded; +} else { + // In rare cases where 'stream' module is not available by default, throw a helpful exception. + iconv.encodeStream = iconv.decodeStream = function() { + throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it."); + }; } -const encode = (input) => node_buffer_1.Buffer.from(input).toString('base64url'); -exports.encode = encode; -const decodeBase64 = (input) => new Uint8Array(node_buffer_1.Buffer.from(input, 'base64')); -exports.decodeBase64 = decodeBase64; -const encodeBase64 = (input) => node_buffer_1.Buffer.from(input).toString('base64'); -exports.encodeBase64 = encodeBase64; -const decode = (input) => new Uint8Array(node_buffer_1.Buffer.from(normalize(input), 'base64url')); -exports.decode = decode; + +if (false) {} /***/ }), -/***/ 36910: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 42281: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = cbcTag; -const node_crypto_1 = __nccwpck_require__(77598); -const buffer_utils_js_1 = __nccwpck_require__(45734); -function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { - const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3)); - const hmac = (0, node_crypto_1.createHmac)(`sha${macSize}`, macKey); - hmac.update(macData); - return hmac.digest().slice(0, keySize >> 3); -} - -/***/ }), +var Buffer = (__nccwpck_require__(12803).Buffer); -/***/ 67000: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), +// we opt to dependency-inject it instead of creating a hard dependency. +module.exports = function(stream_module) { + var Transform = stream_module.Transform; -"use strict"; + // == Encoder stream ======================================================= -Object.defineProperty(exports, "__esModule", ({ value: true })); -const errors_js_1 = __nccwpck_require__(15974); -const is_key_object_js_1 = __nccwpck_require__(68685); -const checkCekLength = (enc, cek) => { - let expected; - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - expected = parseInt(enc.slice(-3), 10); - break; - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - expected = parseInt(enc.slice(1, 4), 10); - break; - default: - throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); + function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); } - if (cek instanceof Uint8Array) { - const actual = cek.byteLength << 3; - if (actual !== expected) { - throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + + IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } + }); + + IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); } - return; } - if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') { - const actual = cek.symmetricKeySize << 3; - if (actual !== expected) { - throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + + IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); } - return; } - throw new TypeError('Invalid Content Encryption Key type'); -}; -exports["default"] = checkCekLength; + IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; + } -/***/ }), -/***/ 65142: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // == Decoder stream ======================================================= -"use strict"; + function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -exports["default"] = (key, alg) => { - let modulusLength; - try { - if (key instanceof node_crypto_1.KeyObject) { - modulusLength = key.asymmetricKeyDetails?.modulusLength; + IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } + }); + + IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); } - else { - modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3; + catch (e) { + done(e); } } - catch { } - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + + IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } + } + + IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; } + + return { + IconvLiteEncoderStream: IconvLiteEncoderStream, + IconvLiteDecoderStream: IconvLiteDecoderStream, + }; }; /***/ }), -/***/ 99271: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 72024: +/***/ ((module) => { -"use strict"; +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +(function(){ + var cache; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -let ciphers; -exports["default"] = (algorithm) => { - ciphers ||= new Set((0, node_crypto_1.getCiphers)()); - return ciphers.has(algorithm); -}; + // Call this function without `new` to use the cached object (good for + // single-threaded environments), or with `new` to create a new object. + // + // @param {string} key A UTF-16 or ASCII string + // @param {number} seed An optional positive integer + // @return {object} A MurmurHash3 object for incremental hashing + function MurmurHash3(key, seed) { + var m = this instanceof MurmurHash3 ? this : cache; + m.reset(seed) + if (typeof key === 'string' && key.length > 0) { + m.hash(key); + } + if (m !== this) { + return m; + } + }; -/***/ }), + // Incrementally add a string to this hash + // + // @param {string} key A UTF-16 or ASCII string + // @return {object} this + MurmurHash3.prototype.hash = function(key) { + var h1, k1, i, top, len; -/***/ 52806: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + len = key.length; + this.len += len; -"use strict"; + k1 = this.k1; + i = 0; + switch (this.rem) { + case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; + case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; + case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; + case 3: + k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; + k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -const check_iv_length_js_1 = __nccwpck_require__(63351); -const check_cek_length_js_1 = __nccwpck_require__(67000); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const errors_js_1 = __nccwpck_require__(15974); -const timing_safe_equal_js_1 = __nccwpck_require__(39106); -const cbc_tag_js_1 = __nccwpck_require__(36910); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const ciphers_js_1 = __nccwpck_require__(99271); -const is_key_like_js_1 = __nccwpck_require__(7433); -function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - if ((0, is_key_object_js_1.default)(cek)) { - cek = cek.export(); - } - const encKey = cek.subarray(keySize >> 3); - const macKey = cek.subarray(0, keySize >> 3); - const macSize = parseInt(enc.slice(-3), 10); - const algorithm = `aes-${keySize}-cbc`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); - let macCheckPassed; - try { - macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag); - } - catch { - } - if (!macCheckPassed) { - throw new errors_js_1.JWEDecryptionFailed(); - } - let plaintext; - try { - const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, encKey, iv); - plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final()); - } - catch { - } - if (!plaintext) { - throw new errors_js_1.JWEDecryptionFailed(); - } - return plaintext; -} -function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - const algorithm = `aes-${keySize}-gcm`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); - } - try { - const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 }); - decipher.setAuthTag(tag); - if (aad.byteLength) { - decipher.setAAD(aad, { plaintextLength: ciphertext.length }); + this.rem = (len + this.rem) & 3; // & 3 is same as % 4 + len -= this.rem; + if (len > 0) { + h1 = this.h1; + while (1) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; + + if (i >= len) { + break; + } + + k1 = ((key.charCodeAt(i++) & 0xffff)) ^ + ((key.charCodeAt(i++) & 0xffff) << 8) ^ + ((key.charCodeAt(i++) & 0xffff) << 16); + top = key.charCodeAt(i++); + k1 ^= ((top & 0xff) << 24) ^ + ((top & 0xff00) >> 8); + } + + k1 = 0; + switch (this.rem) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xffff); + } + + this.h1 = h1; } - const plaintext = decipher.update(ciphertext); - decipher.final(); - return plaintext; - } - catch { - throw new errors_js_1.JWEDecryptionFailed(); - } -} -const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(cek)) { - (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt'); - key = node_crypto_1.KeyObject.from(cek); - } - else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { - key = cek; - } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); - } - if (!iv) { - throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing'); - } - if (!tag) { - throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing'); - } - (0, check_cek_length_js_1.default)(enc, key); - (0, check_iv_length_js_1.default)(enc, iv); - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); - default: - throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); - } -}; -exports["default"] = decrypt; + + this.k1 = k1; + return this; + }; + + // Get the result of this hash + // + // @return {number} The 32-bit hash + MurmurHash3.prototype.result = function() { + var k1, h1; + + k1 = this.k1; + h1 = this.h1; + + if (k1 > 0) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= this.len; + + h1 ^= h1 >>> 16; + h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + }; + + // Reset the hash object for reuse + // + // @param {number} seed An optional positive integer + MurmurHash3.prototype.reset = function(seed) { + this.h1 = typeof seed === 'number' ? seed : 0; + this.rem = this.k1 = this.len = 0; + return this; + }; + + // A cached object to use. This can be safely used if you're in a single- + // threaded environment, otherwise you need to create new hashes to use. + cache = new MurmurHash3(); + + if (true) { + module.exports = MurmurHash3; + } else {} +}()); /***/ }), -/***/ 12931: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 68850: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -const digest = (algorithm, data) => (0, node_crypto_1.createHash)(algorithm).update(data).digest(); -exports["default"] = digest; - +exports.AddressError = void 0; +class AddressError extends Error { + constructor(message, parseMessage) { + super(message); + this.name = 'AddressError'; + if (parseMessage !== null) { + this.parseMessage = parseMessage; + } + } +} +exports.AddressError = AddressError; +//# sourceMappingURL=address-error.js.map /***/ }), -/***/ 74510: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 45864: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = dsaDigest; -const errors_js_1 = __nccwpck_require__(15974); -function dsaDigest(alg) { - switch (alg) { - case 'PS256': - case 'RS256': - case 'ES256': - case 'ES256K': - return 'sha256'; - case 'PS384': - case 'RS384': - case 'ES384': - return 'sha384'; - case 'PS512': - case 'RS512': - case 'ES512': - return 'sha512'; - case 'EdDSA': - return undefined; - default: - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); +exports.isCorrect = exports.isInSubnet = void 0; +function isInSubnet(address) { + if (this.subnetMask < address.subnetMask) { + return false; } + if (this.mask(address.subnetMask) === address.mask()) { + return true; + } + return false; +} +exports.isInSubnet = isInSubnet; +function isCorrect(defaultBits) { + return function () { + if (this.addressMinusSuffix !== this.correctForm()) { + return false; + } + if (this.subnetMask === defaultBits && !this.parsedSubnet) { + return true; + } + return this.parsedSubnet === String(this.subnetMask); + }; } +exports.isCorrect = isCorrect; +//# sourceMappingURL=common.js.map + +/***/ }), +/***/ 79253: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0; +const ipv4_1 = __nccwpck_require__(17946); +Object.defineProperty(exports, "Address4", ({ enumerable: true, get: function () { return ipv4_1.Address4; } })); +const ipv6_1 = __nccwpck_require__(38096); +Object.defineProperty(exports, "Address6", ({ enumerable: true, get: function () { return ipv6_1.Address6; } })); +const address_error_1 = __nccwpck_require__(68850); +Object.defineProperty(exports, "AddressError", ({ enumerable: true, get: function () { return address_error_1.AddressError; } })); +const helpers = __importStar(__nccwpck_require__(20339)); +exports.v6 = { helpers }; +//# sourceMappingURL=ip-address.js.map /***/ }), -/***/ 43359: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 17946: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +/* eslint-disable no-param-reassign */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ecdhAllowed = void 0; -exports.deriveKey = deriveKey; -exports.generateEpk = generateEpk; -const node_crypto_1 = __nccwpck_require__(77598); -const node_util_1 = __nccwpck_require__(57975); -const get_named_curve_js_1 = __nccwpck_require__(65661); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const errors_js_1 = __nccwpck_require__(15974); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const generateKeyPair = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair); -async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { - let publicKey; - if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) { - (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH'); - publicKey = node_crypto_1.KeyObject.from(publicKee); +exports.Address4 = void 0; +const common = __importStar(__nccwpck_require__(45864)); +const constants = __importStar(__nccwpck_require__(66437)); +const address_error_1 = __nccwpck_require__(68850); +const jsbn_1 = __nccwpck_require__(95947); +const sprintf_js_1 = __nccwpck_require__(19973); +/** + * Represents an IPv4 address + * @class Address4 + * @param {string} address - An IPv4 address string + */ +class Address4 { + constructor(address) { + this.groups = constants.GROUPS; + this.parsedAddress = []; + this.parsedSubnet = ''; + this.subnet = '/32'; + this.subnetMask = 32; + this.v4 = true; + /** + * Returns true if the address is correct, false otherwise + * @memberof Address4 + * @instance + * @returns {Boolean} + */ + this.isCorrect = common.isCorrect(constants.BITS); + /** + * Returns true if the given address is in the subnet of the current address + * @memberof Address4 + * @instance + * @returns {boolean} + */ + this.isInSubnet = common.isInSubnet; + this.address = address; + const subnet = constants.RE_SUBNET_STRING.exec(address); + if (subnet) { + this.parsedSubnet = subnet[0].replace('/', ''); + this.subnetMask = parseInt(this.parsedSubnet, 10); + this.subnet = `/${this.subnetMask}`; + if (this.subnetMask < 0 || this.subnetMask > constants.BITS) { + throw new address_error_1.AddressError('Invalid subnet mask.'); + } + address = address.replace(constants.RE_SUBNET_STRING, ''); + } + this.addressMinusSuffix = address; + this.parsedAddress = this.parse(address); } - else if ((0, is_key_object_js_1.default)(publicKee)) { - publicKey = publicKee; + static isValid(address) { + try { + // eslint-disable-next-line no-new + new Address4(address); + return true; + } + catch (e) { + return false; + } } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types)); + /* + * Parses a v4 address + */ + parse(address) { + const groups = address.split('.'); + if (!address.match(constants.RE_ADDRESS)) { + throw new address_error_1.AddressError('Invalid IPv4 address.'); + } + return groups; } - let privateKey; - if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) { - (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits'); - privateKey = node_crypto_1.KeyObject.from(privateKee); + /** + * Returns the correct form of an address + * @memberof Address4 + * @instance + * @returns {String} + */ + correctForm() { + return this.parsedAddress.map((part) => parseInt(part, 10)).join('.'); } - else if ((0, is_key_object_js_1.default)(privateKee)) { - privateKey = privateKee; + /** + * Converts a hex string to an IPv4 address object + * @memberof Address4 + * @static + * @param {string} hex - a hex string to convert + * @returns {Address4} + */ + static fromHex(hex) { + const padded = hex.replace(/:/g, '').padStart(8, '0'); + const groups = []; + let i; + for (i = 0; i < 8; i += 2) { + const h = padded.slice(i, i + 2); + groups.push(parseInt(h, 16)); + } + return new Address4(groups.join('.')); } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types)); + /** + * Converts an integer into a IPv4 address object + * @memberof Address4 + * @static + * @param {integer} integer - a number to convert + * @returns {Address4} + */ + static fromInteger(integer) { + return Address4.fromHex(integer.toString(16)); } - const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength)); - const sharedSecret = (0, node_crypto_1.diffieHellman)({ privateKey, publicKey }); - return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value); -} -async function generateEpk(kee) { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(kee)) { - key = node_crypto_1.KeyObject.from(kee); + /** + * Return an address from in-addr.arpa form + * @memberof Address4 + * @static + * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address + * @returns {Adress4} + * @example + * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.) + * address.correctForm(); // '192.0.2.42' + */ + static fromArpa(arpaFormAddress) { + // remove ending ".in-addr.arpa." or just "." + const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, ''); + const address = leader.split('.').reverse().join('.'); + return new Address4(address); } - else if ((0, is_key_object_js_1.default)(kee)) { - key = kee; + /** + * Converts an IPv4 address object to a hex string + * @memberof Address4 + * @instance + * @returns {String} + */ + toHex() { + return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':'); } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); + /** + * Converts an IPv4 address object to an array of bytes + * @memberof Address4 + * @instance + * @returns {Array} + */ + toArray() { + return this.parsedAddress.map((part) => parseInt(part, 10)); } - switch (key.asymmetricKeyType) { - case 'x25519': - return generateKeyPair('x25519'); - case 'x448': { - return generateKeyPair('x448'); - } - case 'ec': { - const namedCurve = (0, get_named_curve_js_1.default)(key); - return generateKeyPair('ec', { namedCurve }); + /** + * Converts an IPv4 address object to an IPv6 address group + * @memberof Address4 + * @instance + * @returns {String} + */ + toGroup6() { + const output = []; + let i; + for (i = 0; i < constants.GROUPS; i += 2) { + const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10)); + output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16))); } - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK'); + return output.join(':'); } -} -const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key)); -exports.ecdhAllowed = ecdhAllowed; - - -/***/ }), - -/***/ 36286: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -const check_iv_length_js_1 = __nccwpck_require__(63351); -const check_cek_length_js_1 = __nccwpck_require__(67000); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const cbc_tag_js_1 = __nccwpck_require__(36910); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const iv_js_1 = __nccwpck_require__(56565); -const errors_js_1 = __nccwpck_require__(15974); -const ciphers_js_1 = __nccwpck_require__(99271); -const is_key_like_js_1 = __nccwpck_require__(7433); -function cbcEncrypt(enc, plaintext, cek, iv, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - if ((0, is_key_object_js_1.default)(cek)) { - cek = cek.export(); + /** + * Returns the address as a BigInteger + * @memberof Address4 + * @instance + * @returns {BigInteger} + */ + bigInteger() { + return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16); } - const encKey = cek.subarray(keySize >> 3); - const macKey = cek.subarray(0, keySize >> 3); - const algorithm = `aes-${keySize}-cbc`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + /** + * Helper function getting start address. + * @memberof Address4 + * @instance + * @returns {BigInteger} + */ + _startAddress() { + return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2); } - const cipher = (0, node_crypto_1.createCipheriv)(algorithm, encKey, iv); - const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final()); - const macSize = parseInt(enc.slice(-3), 10); - const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); - return { ciphertext, tag, iv }; -} -function gcmEncrypt(enc, plaintext, cek, iv, aad) { - const keySize = parseInt(enc.slice(1, 4), 10); - const algorithm = `aes-${keySize}-gcm`; - if (!(0, ciphers_js_1.default)(algorithm)) { - throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + /** + * The first address in the range given by this address' subnet. + * Often referred to as the Network Address. + * @memberof Address4 + * @instance + * @returns {Address4} + */ + startAddress() { + return Address4.fromBigInteger(this._startAddress()); } - const cipher = (0, node_crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 }); - if (aad.byteLength) { - cipher.setAAD(aad, { plaintextLength: plaintext.length }); + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + * @memberof Address4 + * @instance + * @returns {Address4} + */ + startAddressExclusive() { + const adjust = new jsbn_1.BigInteger('1'); + return Address4.fromBigInteger(this._startAddress().add(adjust)); } - const ciphertext = cipher.update(plaintext); - cipher.final(); - const tag = cipher.getAuthTag(); - return { ciphertext, tag, iv }; -} -const encrypt = (enc, plaintext, cek, iv, aad) => { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(cek)) { - (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt'); - key = node_crypto_1.KeyObject.from(cek); + /** + * Helper function getting end address. + * @memberof Address4 + * @instance + * @returns {BigInteger} + */ + _endAddress() { + return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2); } - else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { - key = cek; + /** + * The last address in the range given by this address' subnet + * Often referred to as the Broadcast + * @memberof Address4 + * @instance + * @returns {Address4} + */ + endAddress() { + return Address4.fromBigInteger(this._endAddress()); } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); + /** + * The last host address in the range given by this address's subnet ie + * the last address prior to the Broadcast Address + * @memberof Address4 + * @instance + * @returns {Address4} + */ + endAddressExclusive() { + const adjust = new jsbn_1.BigInteger('1'); + return Address4.fromBigInteger(this._endAddress().subtract(adjust)); } - (0, check_cek_length_js_1.default)(enc, key); - if (iv) { - (0, check_iv_length_js_1.default)(enc, iv); + /** + * Converts a BigInteger to a v4 address object + * @memberof Address4 + * @static + * @param {BigInteger} bigInteger - a BigInteger to convert + * @returns {Address4} + */ + static fromBigInteger(bigInteger) { + return Address4.fromInteger(parseInt(bigInteger.toString(), 10)); + } + /** + * Returns the first n bits of the address, defaulting to the + * subnet mask + * @memberof Address4 + * @instance + * @returns {String} + */ + mask(mask) { + if (mask === undefined) { + mask = this.subnetMask; + } + return this.getBitsBase2(0, mask); + } + /** + * Returns the bits in the given range as a base-2 string + * @memberof Address4 + * @instance + * @returns {string} + */ + getBitsBase2(start, end) { + return this.binaryZeroPad().slice(start, end); + } + /** + * Return the reversed ip6.arpa form of the address + * @memberof Address4 + * @param {Object} options + * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix + * @instance + * @returns {String} + */ + reverseForm(options) { + if (!options) { + options = {}; + } + const reversed = this.correctForm().split('.').reverse().join('.'); + if (options.omitSuffix) { + return reversed; + } + return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed); + } + /** + * Returns true if the given address is a multicast address + * @memberof Address4 + * @instance + * @returns {boolean} + */ + isMulticast() { + return this.isInSubnet(new Address4('224.0.0.0/4')); } - else { - iv = (0, iv_js_1.default)(enc); + /** + * Returns a zero-padded base-2 string representation of the address + * @memberof Address4 + * @instance + * @returns {string} + */ + binaryZeroPad() { + return this.bigInteger().toString(2).padStart(constants.BITS, '0'); } - switch (enc) { - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - return cbcEncrypt(enc, plaintext, key, iv, aad); - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - return gcmEncrypt(enc, plaintext, key, iv, aad); - default: - throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + /** + * Groups an IPv4 address for inclusion at the end of an IPv6 address + * @returns {String} + */ + groupForV6() { + const segments = this.parsedAddress; + return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.'))); } -}; -exports["default"] = encrypt; - +} +exports.Address4 = Address4; +//# sourceMappingURL=ipv4.js.map /***/ }), -/***/ 20311: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 38096: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const http = __nccwpck_require__(37067); -const https = __nccwpck_require__(44708); -const node_events_1 = __nccwpck_require__(78474); -const errors_js_1 = __nccwpck_require__(15974); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const fetchJwks = async (url, timeout, options) => { - let get; - switch (url.protocol) { - case 'https:': - get = https.get; - break; - case 'http:': - get = http.get; - break; - default: - throw new TypeError('Unsupported URL protocol.'); +/* eslint-disable prefer-destructuring */ +/* eslint-disable no-param-reassign */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - const { agent, headers } = options; - const req = get(url.href, { - agent, - timeout, - headers, - }); - const [response] = (await Promise.race([(0, node_events_1.once)(req, 'response'), (0, node_events_1.once)(req, 'timeout')])); - if (!response) { - req.destroy(); - throw new errors_js_1.JWKSTimeout(); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Address6 = void 0; +const common = __importStar(__nccwpck_require__(45864)); +const constants4 = __importStar(__nccwpck_require__(66437)); +const constants6 = __importStar(__nccwpck_require__(75280)); +const helpers = __importStar(__nccwpck_require__(20339)); +const ipv4_1 = __nccwpck_require__(17946); +const regular_expressions_1 = __nccwpck_require__(72016); +const address_error_1 = __nccwpck_require__(68850); +const jsbn_1 = __nccwpck_require__(95947); +const sprintf_js_1 = __nccwpck_require__(19973); +function assert(condition) { + if (!condition) { + throw new Error('Assertion failed.'); } - if (response.statusCode !== 200) { - throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); +} +function addCommas(number) { + const r = /(\d+)(\d{3})/; + while (r.test(number)) { + number = number.replace(r, '$1,$2'); } - const parts = []; - for await (const part of response) { - parts.push(part); + return number; +} +function spanLeadingZeroes4(n) { + n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2'); + n = n.replace(/^(0{1,})(0)$/, '$1$2'); + return n; +} +/* + * A helper function to compact an array + */ +function compact(address, slice) { + const s1 = []; + const s2 = []; + let i; + for (i = 0; i < address.length; i++) { + if (i < slice[0]) { + s1.push(address[i]); + } + else if (i > slice[1]) { + s2.push(address[i]); + } } - try { - return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts))); + return s1.concat(['compact']).concat(s2); +} +function paddedHex(octet) { + return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16)); +} +function unsignByte(b) { + // eslint-disable-next-line no-bitwise + return b & 0xff; +} +/** + * Represents an IPv6 address + * @class Address6 + * @param {string} address - An IPv6 address string + * @param {number} [groups=8] - How many octets to parse + * @example + * var address = new Address6('2001::/32'); + */ +class Address6 { + constructor(address, optionalGroups) { + this.addressMinusSuffix = ''; + this.parsedSubnet = ''; + this.subnet = '/128'; + this.subnetMask = 128; + this.v4 = false; + this.zone = ''; + // #region Attributes + /** + * Returns true if the given address is in the subnet of the current address + * @memberof Address6 + * @instance + * @returns {boolean} + */ + this.isInSubnet = common.isInSubnet; + /** + * Returns true if the address is correct, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + this.isCorrect = common.isCorrect(constants6.BITS); + if (optionalGroups === undefined) { + this.groups = constants6.GROUPS; + } + else { + this.groups = optionalGroups; + } + this.address = address; + const subnet = constants6.RE_SUBNET_STRING.exec(address); + if (subnet) { + this.parsedSubnet = subnet[0].replace('/', ''); + this.subnetMask = parseInt(this.parsedSubnet, 10); + this.subnet = `/${this.subnetMask}`; + if (Number.isNaN(this.subnetMask) || + this.subnetMask < 0 || + this.subnetMask > constants6.BITS) { + throw new address_error_1.AddressError('Invalid subnet mask.'); + } + address = address.replace(constants6.RE_SUBNET_STRING, ''); + } + else if (/\//.test(address)) { + throw new address_error_1.AddressError('Invalid subnet mask.'); + } + const zone = constants6.RE_ZONE_STRING.exec(address); + if (zone) { + this.zone = zone[0]; + address = address.replace(constants6.RE_ZONE_STRING, ''); + } + this.addressMinusSuffix = address; + this.parsedAddress = this.parse(this.addressMinusSuffix); } - catch { - throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); + static isValid(address) { + try { + // eslint-disable-next-line no-new + new Address6(address); + return true; + } + catch (e) { + return false; + } } -}; -exports["default"] = fetchJwks; - - -/***/ }), - -/***/ 10088: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generateSecret = generateSecret; -exports.generateKeyPair = generateKeyPair; -const node_crypto_1 = __nccwpck_require__(77598); -const node_util_1 = __nccwpck_require__(57975); -const random_js_1 = __nccwpck_require__(23376); -const errors_js_1 = __nccwpck_require__(15974); -const generate = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair); -async function generateSecret(alg, options) { - let length; - switch (alg) { - case 'HS256': - case 'HS384': - case 'HS512': - case 'A128CBC-HS256': - case 'A192CBC-HS384': - case 'A256CBC-HS512': - length = parseInt(alg.slice(-3), 10); - break; - case 'A128KW': - case 'A192KW': - case 'A256KW': - case 'A128GCMKW': - case 'A192GCMKW': - case 'A256GCMKW': - case 'A128GCM': - case 'A192GCM': - case 'A256GCM': - length = parseInt(alg.slice(1, 4), 10); - break; - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + /** + * Convert a BigInteger to a v6 address object + * @memberof Address6 + * @static + * @param {BigInteger} bigInteger - a BigInteger to convert + * @returns {Address6} + * @example + * var bigInteger = new BigInteger('1000000000000'); + * var address = Address6.fromBigInteger(bigInteger); + * address.correctForm(); // '::e8:d4a5:1000' + */ + static fromBigInteger(bigInteger) { + const hex = bigInteger.toString(16).padStart(32, '0'); + const groups = []; + let i; + for (i = 0; i < constants6.GROUPS; i++) { + groups.push(hex.slice(i * 4, (i + 1) * 4)); + } + return new Address6(groups.join(':')); } - return (0, node_crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3))); -} -async function generateKeyPair(alg, options) { - switch (alg) { - case 'RS256': - case 'RS384': - case 'RS512': - case 'PS256': - case 'PS384': - case 'PS512': - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - case 'RSA1_5': { - const modulusLength = options?.modulusLength ?? 2048; - if (typeof modulusLength !== 'number' || modulusLength < 2048) { - throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); + /** + * Convert a URL (with optional port number) to an address object + * @memberof Address6 + * @static + * @param {string} url - a URL with optional port number + * @example + * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/'); + * addressAndPort.address.correctForm(); // 'ffff::' + * addressAndPort.port; // 8080 + */ + static fromURL(url) { + let host; + let port = null; + let result; + // If we have brackets parse them and find a port + if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) { + result = constants6.RE_URL_WITH_PORT.exec(url); + if (result === null) { + return { + error: 'failed to parse address with port', + address: null, + port: null, + }; } - const keypair = await generate('rsa', { - modulusLength, - publicExponent: 0x10001, - }); - return keypair; + host = result[1]; + port = result[2]; + // If there's a URL extract the address } - case 'ES256': - return generate('ec', { namedCurve: 'P-256' }); - case 'ES256K': - return generate('ec', { namedCurve: 'secp256k1' }); - case 'ES384': - return generate('ec', { namedCurve: 'P-384' }); - case 'ES512': - return generate('ec', { namedCurve: 'P-521' }); - case 'EdDSA': { - switch (options?.crv) { - case undefined: - case 'Ed25519': - return generate('ed25519'); - case 'Ed448': - return generate('ed448'); - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); + else if (url.indexOf('/') !== -1) { + // Remove the protocol prefix + url = url.replace(/^[a-z0-9]+:\/\//, ''); + // Parse the address + result = constants6.RE_URL.exec(url); + if (result === null) { + return { + error: 'failed to parse address from URL', + address: null, + port: null, + }; + } + host = result[1]; + // Otherwise just assign the URL to the host and let the library parse it + } + else { + host = url; + } + // If there's a port convert it to an integer + if (port) { + port = parseInt(port, 10); + // squelch out of range ports + if (port < 0 || port > 65536) { + port = null; } } - case 'ECDH-ES': - case 'ECDH-ES+A128KW': - case 'ECDH-ES+A192KW': - case 'ECDH-ES+A256KW': { - const crv = options?.crv ?? 'P-256'; - switch (crv) { - case undefined: - case 'P-256': - case 'P-384': - case 'P-521': - return generate('ec', { namedCurve: crv }); - case 'X25519': - return generate('x25519'); - case 'X448': - return generate('x448'); - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); + else { + // Standardize `undefined` to `null` + port = null; + } + return { + address: new Address6(host), + port, + }; + } + /** + * Create an IPv6-mapped address given an IPv4 address + * @memberof Address6 + * @static + * @param {string} address - An IPv4 address string + * @returns {Address6} + * @example + * var address = Address6.fromAddress4('192.168.0.1'); + * address.correctForm(); // '::ffff:c0a8:1' + * address.to4in6(); // '::ffff:192.168.0.1' + */ + static fromAddress4(address) { + const address4 = new ipv4_1.Address4(address); + const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask); + return new Address6(`::ffff:${address4.correctForm()}/${mask6}`); + } + /** + * Return an address from ip6.arpa form + * @memberof Address6 + * @static + * @param {string} arpaFormAddress - an 'ip6.arpa' form address + * @returns {Adress6} + * @example + * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.) + * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe' + */ + static fromArpa(arpaFormAddress) { + // remove ending ".ip6.arpa." or just "." + let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, ''); + const semicolonAmount = 7; + // correct ip6.arpa form with ending removed will be 63 characters + if (address.length !== 63) { + throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); + } + const parts = address.split('.').reverse(); + for (let i = semicolonAmount; i > 0; i--) { + const insertIndex = i * 4; + parts.splice(insertIndex, 0, ':'); + } + address = parts.join(''); + return new Address6(address); + } + /** + * Return the Microsoft UNC transcription of the address + * @memberof Address6 + * @instance + * @returns {String} the Microsoft UNC transcription of the address + */ + microsoftTranscription() { + return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-')); + } + /** + * Return the first n bits of the address, defaulting to the subnet mask + * @memberof Address6 + * @instance + * @param {number} [mask=subnet] - the number of bits to mask + * @returns {String} the first n bits of the address as a string + */ + mask(mask = this.subnetMask) { + return this.getBitsBase2(0, mask); + } + /** + * Return the number of possible subnets of a given size in the address + * @memberof Address6 + * @instance + * @param {number} [size=128] - the subnet size + * @returns {String} + */ + // TODO: probably useful to have a numeric version of this too + possibleSubnets(subnetSize = 128) { + const availableBits = constants6.BITS - this.subnetMask; + const subnetBits = Math.abs(subnetSize - constants6.BITS); + const subnetPowers = availableBits - subnetBits; + if (subnetPowers < 0) { + return '0'; + } + return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10)); + } + /** + * Helper function getting start address. + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + _startAddress() { + return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2); + } + /** + * The first address in the range given by this address' subnet + * Often referred to as the Network Address. + * @memberof Address6 + * @instance + * @returns {Address6} + */ + startAddress() { + return Address6.fromBigInteger(this._startAddress()); + } + /** + * The first host address in the range given by this address's subnet ie + * the first address after the Network Address + * @memberof Address6 + * @instance + * @returns {Address6} + */ + startAddressExclusive() { + const adjust = new jsbn_1.BigInteger('1'); + return Address6.fromBigInteger(this._startAddress().add(adjust)); + } + /** + * Helper function getting end address. + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + _endAddress() { + return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2); + } + /** + * The last address in the range given by this address' subnet + * Often referred to as the Broadcast + * @memberof Address6 + * @instance + * @returns {Address6} + */ + endAddress() { + return Address6.fromBigInteger(this._endAddress()); + } + /** + * The last host address in the range given by this address's subnet ie + * the last address prior to the Broadcast Address + * @memberof Address6 + * @instance + * @returns {Address6} + */ + endAddressExclusive() { + const adjust = new jsbn_1.BigInteger('1'); + return Address6.fromBigInteger(this._endAddress().subtract(adjust)); + } + /** + * Return the scope of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + getScope() { + let scope = constants6.SCOPES[this.getBits(12, 16).intValue()]; + if (this.getType() === 'Global unicast' && scope !== 'Link local') { + scope = 'Global'; + } + return scope || 'Unknown'; + } + /** + * Return the type of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + getType() { + for (const subnet of Object.keys(constants6.TYPES)) { + if (this.isInSubnet(new Address6(subnet))) { + return constants6.TYPES[subnet]; } } - default: - throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); - } -} - - -/***/ }), - -/***/ 65661: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.weakMap = void 0; -const node_crypto_1 = __nccwpck_require__(77598); -const errors_js_1 = __nccwpck_require__(15974); -const webcrypto_js_1 = __nccwpck_require__(59044); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const is_jwk_js_1 = __nccwpck_require__(91229); -exports.weakMap = new WeakMap(); -const namedCurveToJOSE = (namedCurve) => { - switch (namedCurve) { - case 'prime256v1': - return 'P-256'; - case 'secp384r1': - return 'P-384'; - case 'secp521r1': - return 'P-521'; - case 'secp256k1': - return 'secp256k1'; - default: - throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); - } -}; -const getNamedCurve = (kee, raw) => { - let key; - if ((0, webcrypto_js_1.isCryptoKey)(kee)) { - key = node_crypto_1.KeyObject.from(kee); + return 'Global unicast'; } - else if ((0, is_key_object_js_1.default)(kee)) { - key = kee; + /** + * Return the bits in the given range as a BigInteger + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + getBits(start, end) { + return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2); } - else if ((0, is_jwk_js_1.isJWK)(kee)) { - return kee.crv; + /** + * Return the bits in the given range as a base-2 string + * @memberof Address6 + * @instance + * @returns {String} + */ + getBitsBase2(start, end) { + return this.binaryZeroPad().slice(start, end); } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); + /** + * Return the bits in the given range as a base-16 string + * @memberof Address6 + * @instance + * @returns {String} + */ + getBitsBase16(start, end) { + const length = end - start; + if (length % 4 !== 0) { + throw new Error('Length of bits to retrieve must be divisible by four'); + } + return this.getBits(start, end) + .toString(16) + .padStart(length / 4, '0'); } - if (key.type === 'secret') { - throw new TypeError('only "private" or "public" type keys can be used for this operation'); + /** + * Return the bits that are set past the subnet mask length + * @memberof Address6 + * @instance + * @returns {String} + */ + getBitsPastSubnet() { + return this.getBitsBase2(this.subnetMask, constants6.BITS); } - switch (key.asymmetricKeyType) { - case 'ed25519': - case 'ed448': - return `Ed${key.asymmetricKeyType.slice(2)}`; - case 'x25519': - case 'x448': - return `X${key.asymmetricKeyType.slice(1)}`; - case 'ec': { - const namedCurve = key.asymmetricKeyDetails.namedCurve; - if (raw) { - return namedCurve; + /** + * Return the reversed ip6.arpa form of the address + * @memberof Address6 + * @param {Object} options + * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix + * @instance + * @returns {String} + */ + reverseForm(options) { + if (!options) { + options = {}; + } + const characters = Math.floor(this.subnetMask / 4); + const reversed = this.canonicalForm() + .replace(/:/g, '') + .split('') + .slice(0, characters) + .reverse() + .join('.'); + if (characters > 0) { + if (options.omitSuffix) { + return reversed; } - return namedCurveToJOSE(namedCurve); + return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed); } - default: - throw new TypeError('Invalid asymmetric key type for this operation'); + if (options.omitSuffix) { + return ''; + } + return 'ip6.arpa.'; } -}; -exports["default"] = getNamedCurve; - - -/***/ }), - -/***/ 80723: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = getSignVerifyKey; -const node_crypto_1 = __nccwpck_require__(77598); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const jwk = __nccwpck_require__(91229); -function getSignVerifyKey(alg, key, usage) { - if (key instanceof Uint8Array) { - if (!alg.startsWith('HS')) { - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); + /** + * Return the correct form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + correctForm() { + let i; + let groups = []; + let zeroCounter = 0; + const zeroes = []; + for (i = 0; i < this.parsedAddress.length; i++) { + const value = parseInt(this.parsedAddress[i], 16); + if (value === 0) { + zeroCounter++; + } + if (value !== 0 && zeroCounter > 0) { + if (zeroCounter > 1) { + zeroes.push([i - zeroCounter, i - 1]); + } + zeroCounter = 0; + } } - return (0, node_crypto_1.createSecretKey)(key); + // Do we end with a string of zeroes? + if (zeroCounter > 1) { + zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]); + } + const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1); + if (zeroes.length > 0) { + const index = zeroLengths.indexOf(Math.max(...zeroLengths)); + groups = compact(this.parsedAddress, zeroes[index]); + } + else { + groups = this.parsedAddress; + } + for (i = 0; i < groups.length; i++) { + if (groups[i] !== 'compact') { + groups[i] = parseInt(groups[i], 16).toString(16); + } + } + let correct = groups.join(':'); + correct = correct.replace(/^compact$/, '::'); + correct = correct.replace(/^compact|compact$/, ':'); + correct = correct.replace(/compact/, ''); + return correct; } - if (key instanceof node_crypto_1.KeyObject) { - return key; + /** + * Return a zero-padded base-2 string representation of the address + * @memberof Address6 + * @instance + * @returns {String} + * @example + * var address = new Address6('2001:4860:4001:803::1011'); + * address.binaryZeroPad(); + * // '0010000000000001010010000110000001000000000000010000100000000011 + * // 0000000000000000000000000000000000000000000000000001000000010001' + */ + binaryZeroPad() { + return this.bigInteger().toString(2).padStart(constants6.BITS, '0'); } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage); - return node_crypto_1.KeyObject.from(key); + // TODO: Improve the semantics of this helper function + parse4in6(address) { + const groups = address.split(':'); + const lastGroup = groups.slice(-1)[0]; + const address4 = lastGroup.match(constants4.RE_ADDRESS); + if (address4) { + this.parsedAddress4 = address4[0]; + this.address4 = new ipv4_1.Address4(this.parsedAddress4); + for (let i = 0; i < this.address4.groups; i++) { + if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) { + throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.'))); + } + } + this.v4 = true; + groups[groups.length - 1] = this.address4.toGroup6(); + address = groups.join(':'); + } + return address; } - if (jwk.isJWK(key)) { - if (alg.startsWith('HS')) { - return (0, node_crypto_1.createSecretKey)(Buffer.from(key.k, 'base64url')); + // TODO: Make private? + parse(address) { + address = this.parse4in6(address); + const badCharacters = address.match(constants6.RE_BAD_CHARACTERS); + if (badCharacters) { + throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '$1')); } - return key; + const badAddress = address.match(constants6.RE_BAD_ADDRESS); + if (badAddress) { + throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '$1')); + } + let groups = []; + const halves = address.split('::'); + if (halves.length === 2) { + let first = halves[0].split(':'); + let last = halves[1].split(':'); + if (first.length === 1 && first[0] === '') { + first = []; + } + if (last.length === 1 && last[0] === '') { + last = []; + } + const remaining = this.groups - (first.length + last.length); + if (!remaining) { + throw new address_error_1.AddressError('Error parsing groups'); + } + this.elidedGroups = remaining; + this.elisionBegin = first.length; + this.elisionEnd = first.length + this.elidedGroups; + groups = groups.concat(first); + for (let i = 0; i < remaining; i++) { + groups.push('0'); + } + groups = groups.concat(last); + } + else if (halves.length === 1) { + groups = address.split(':'); + this.elidedGroups = 0; + } + else { + throw new address_error_1.AddressError('Too many :: groups found'); + } + groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16))); + if (groups.length !== this.groups) { + throw new address_error_1.AddressError('Incorrect number of groups found'); + } + return groups; } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array', 'JSON Web Key')); -} - - -/***/ }), - -/***/ 57399: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = hmacDigest; -const errors_js_1 = __nccwpck_require__(15974); -function hmacDigest(alg) { - switch (alg) { - case 'HS256': - return 'sha256'; - case 'HS384': - return 'sha384'; - case 'HS512': - return 'sha512'; - default: - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + /** + * Return the canonical form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + canonicalForm() { + return this.parsedAddress.map(paddedHex).join(':'); } -} - - -/***/ }), - -/***/ 7433: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.types = void 0; -const webcrypto_js_1 = __nccwpck_require__(59044); -const is_key_object_js_1 = __nccwpck_require__(68685); -exports["default"] = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key); -const types = ['KeyObject']; -exports.types = types; -if (globalThis.CryptoKey || webcrypto_js_1.default?.CryptoKey) { - types.push('CryptoKey'); -} - - -/***/ }), - -/***/ 68685: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util = __nccwpck_require__(57975); -exports["default"] = (obj) => util.types.isKeyObject(obj); - - -/***/ }), - -/***/ 80939: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -const parse = (key) => { - if (key.d) { - return (0, node_crypto_1.createPrivateKey)({ format: 'jwk', key }); + /** + * Return the decimal form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + decimal() { + return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':'); } - return (0, node_crypto_1.createPublicKey)({ format: 'jwk', key }); -}; -exports["default"] = parse; - - -/***/ }), - -/***/ 9041: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -const base64url_js_1 = __nccwpck_require__(12635); -const errors_js_1 = __nccwpck_require__(15974); -const webcrypto_js_1 = __nccwpck_require__(59044); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const keyToJWK = (key) => { - let keyObject; - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - if (!key.extractable) { - throw new TypeError('CryptoKey is not extractable'); + /** + * Return the address as a BigInteger + * @memberof Address6 + * @instance + * @returns {BigInteger} + */ + bigInteger() { + return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16); + } + /** + * Return the last two groups of this address as an IPv4 address string + * @memberof Address6 + * @instance + * @returns {Address4} + * @example + * var address = new Address6('2001:4860:4001::1825:bf11'); + * address.to4().correctForm(); // '24.37.191.17' + */ + to4() { + const binary = this.binaryZeroPad().split(''); + return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16)); + } + /** + * Return the v4-in-v6 form of the address + * @memberof Address6 + * @instance + * @returns {String} + */ + to4in6() { + const address4 = this.to4(); + const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6); + const correct = address6.correctForm(); + let infix = ''; + if (!/:$/.test(correct)) { + infix = ':'; } - keyObject = node_crypto_1.KeyObject.from(key); + return correct + infix + address4.address; } - else if ((0, is_key_object_js_1.default)(key)) { - keyObject = key; + /** + * Return an object containing the Teredo properties of the address + * @memberof Address6 + * @instance + * @returns {Object} + */ + inspectTeredo() { + /* + - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32). + - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that + is used. + - Bits 64 to 79 can be used to define some flags. Currently only the + higher order bit is used; it is set to 1 if the Teredo client is + located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista + and Windows Server 2008 implementations, more bits are used. In those + implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA", + where "C" remains the "Cone" flag. The "R" bit is reserved for future + use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit + is Individual/Group flag (set to 0). The A bits are set to a 12-bit + randomly generated number chosen by the Teredo client to introduce + additional protection for the Teredo node against IPv6-based scanning + attacks. + - Bits 80 to 95 contains the obfuscated UDP port number. This is the + port number that is mapped by the NAT to the Teredo client with all + bits inverted. + - Bits 96 to 127 contains the obfuscated IPv4 address. This is the + public IPv4 address of the NAT with all bits inverted. + */ + const prefix = this.getBitsBase16(0, 32); + const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString(); + const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64)); + const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16)); + const flags = this.getBits(64, 80); + const flagsBase2 = this.getBitsBase2(64, 80); + const coneNat = flags.testBit(15); + const reserved = flags.testBit(14); + const groupIndividual = flags.testBit(8); + const universalLocal = flags.testBit(9); + const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10); + return { + prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)), + server4: server4.address, + client4: client4.address, + flags: flagsBase2, + coneNat, + microsoft: { + reserved, + universalLocal, + groupIndividual, + nonce, + }, + udpPort, + }; } - else if (key instanceof Uint8Array) { + /** + * Return an object containing the 6to4 properties of the address + * @memberof Address6 + * @instance + * @returns {Object} + */ + inspect6to4() { + /* + - Bits 0 to 15 are set to the 6to4 prefix (2002::/16). + - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used. + */ + const prefix = this.getBitsBase16(0, 16); + const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48)); return { - kty: 'oct', - k: (0, base64url_js_1.encode)(key), + prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)), + gateway: gateway.address, }; } - else { - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); + /** + * Return a v6 6to4 address from a v6 v4inv6 address + * @memberof Address6 + * @instance + * @returns {Address6} + */ + to6to4() { + if (!this.is4()) { + return null; + } + const addr6to4 = [ + '2002', + this.getBitsBase16(96, 112), + this.getBitsBase16(112, 128), + '', + '/16', + ].join(':'); + return new Address6(addr6to4); } - if (keyObject.type !== 'secret' && - !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { - throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); + /** + * Return a byte array + * @memberof Address6 + * @instance + * @returns {Array} + */ + toByteArray() { + const byteArray = this.bigInteger().toByteArray(); + // work around issue where `toByteArray` returns a leading 0 element + if (byteArray.length === 17 && byteArray[0] === 0) { + return byteArray.slice(1); + } + return byteArray; } - return keyObject.export({ format: 'jwk' }); -}; -exports["default"] = keyToJWK; - - -/***/ }), - -/***/ 70363: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = keyForCrypto; -const node_crypto_1 = __nccwpck_require__(77598); -const get_named_curve_js_1 = __nccwpck_require__(65661); -const errors_js_1 = __nccwpck_require__(15974); -const check_key_length_js_1 = __nccwpck_require__(65142); -const ecCurveAlgMap = new Map([ - ['ES256', 'P-256'], - ['ES256K', 'secp256k1'], - ['ES384', 'P-384'], - ['ES512', 'P-521'], -]); -function keyForCrypto(alg, key) { - let asymmetricKeyType; - let asymmetricKeyDetails; - let isJWK; - if (key instanceof node_crypto_1.KeyObject) { - asymmetricKeyType = key.asymmetricKeyType; - asymmetricKeyDetails = key.asymmetricKeyDetails; + /** + * Return an unsigned byte array + * @memberof Address6 + * @instance + * @returns {Array} + */ + toUnsignedByteArray() { + return this.toByteArray().map(unsignByte); } - else { - isJWK = true; - switch (key.kty) { - case 'RSA': - asymmetricKeyType = 'rsa'; - break; - case 'EC': - asymmetricKeyType = 'ec'; - break; - case 'OKP': { - if (key.crv === 'Ed25519') { - asymmetricKeyType = 'ed25519'; - break; - } - if (key.crv === 'Ed448') { - asymmetricKeyType = 'ed448'; - break; - } - throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448'); - } - default: - throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC'); + /** + * Convert a byte array to an Address6 object + * @memberof Address6 + * @static + * @returns {Address6} + */ + static fromByteArray(bytes) { + return this.fromUnsignedByteArray(bytes.map(unsignByte)); + } + /** + * Convert an unsigned byte array to an Address6 object + * @memberof Address6 + * @static + * @returns {Address6} + */ + static fromUnsignedByteArray(bytes) { + const BYTE_MAX = new jsbn_1.BigInteger('256', 10); + let result = new jsbn_1.BigInteger('0', 10); + let multiplier = new jsbn_1.BigInteger('1', 10); + for (let i = bytes.length - 1; i >= 0; i--) { + result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10))); + multiplier = multiplier.multiply(BYTE_MAX); } + return Address6.fromBigInteger(result); } - let options; - switch (alg) { - case 'EdDSA': - if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); - } - break; - case 'RS256': - case 'RS384': - case 'RS512': - if (asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); - } - (0, check_key_length_js_1.default)(key, alg); - break; - case 'PS256': - case 'PS384': - case 'PS512': - if (asymmetricKeyType === 'rsa-pss') { - const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails; - const length = parseInt(alg.slice(-3), 10); - if (hashAlgorithm !== undefined && - (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { - throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); - } - if (saltLength !== undefined && saltLength > length >> 3) { - throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); - } - } - else if (asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); - } - (0, check_key_length_js_1.default)(key, alg); - options = { - padding: node_crypto_1.constants.RSA_PKCS1_PSS_PADDING, - saltLength: node_crypto_1.constants.RSA_PSS_SALTLEN_DIGEST, - }; - break; - case 'ES256': - case 'ES256K': - case 'ES384': - case 'ES512': { - if (asymmetricKeyType !== 'ec') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); - } - const actual = (0, get_named_curve_js_1.default)(key); - const expected = ecCurveAlgMap.get(alg); - if (actual !== expected) { - throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); - } - options = { dsaEncoding: 'ieee-p1363' }; - break; + /** + * Returns true if the address is in the canonical form, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isCanonical() { + return this.addressMinusSuffix === this.canonicalForm(); + } + /** + * Returns true if the address is a link local address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isLinkLocal() { + // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10' + if (this.getBitsBase2(0, 64) === + '1111111010000000000000000000000000000000000000000000000000000000') { + return true; } - default: - throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + return false; } - if (isJWK) { - return { format: 'jwk', key, ...options }; + /** + * Returns true if the address is a multicast address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isMulticast() { + return this.getType() === 'Multicast'; } - return options ? { ...options, key } : key; -} - - -/***/ }), - -/***/ 51276: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = {}; - - -/***/ }), - -/***/ 52741: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decrypt = exports.encrypt = void 0; -const node_util_1 = __nccwpck_require__(57975); -const node_crypto_1 = __nccwpck_require__(77598); -const random_js_1 = __nccwpck_require__(23376); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const base64url_js_1 = __nccwpck_require__(12635); -const aeskw_js_1 = __nccwpck_require__(76202); -const check_p2s_js_1 = __nccwpck_require__(88040); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const pbkdf2 = (0, node_util_1.promisify)(node_crypto_1.pbkdf2); -function getPassword(key, alg) { - if ((0, is_key_object_js_1.default)(key)) { - return key.export(); + /** + * Returns true if the address is a v4-in-v6 address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + is4() { + return this.v4; } - if (key instanceof Uint8Array) { - return key; + /** + * Returns true if the address is a Teredo address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isTeredo() { + return this.isInSubnet(new Address6('2001::/32')); } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey'); - return node_crypto_1.KeyObject.from(key).export(); + /** + * Returns true if the address is a 6to4 address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + is6to4() { + return this.isInSubnet(new Address6('2002::/16')); } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); -} -const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => { - (0, check_p2s_js_1.default)(p2s); - const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10) >> 3; - const password = getPassword(key, alg); - const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); - const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek); - return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) }; -}; -exports.encrypt = encrypt; -const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { - (0, check_p2s_js_1.default)(p2s); - const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); - const keylen = parseInt(alg.slice(13, 16), 10) >> 3; - const password = getPassword(key, alg); - const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); - return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey); -}; -exports.decrypt = decrypt; - - -/***/ }), - -/***/ 23376: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = void 0; -var node_crypto_1 = __nccwpck_require__(77598); -Object.defineProperty(exports, "default", ({ enumerable: true, get: function () { return node_crypto_1.randomFillSync; } })); - - -/***/ }), - -/***/ 61129: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decrypt = exports.encrypt = void 0; -const node_crypto_1 = __nccwpck_require__(77598); -const node_util_1 = __nccwpck_require__(57975); -const check_key_length_js_1 = __nccwpck_require__(65142); -const webcrypto_js_1 = __nccwpck_require__(59044); -const crypto_key_js_1 = __nccwpck_require__(26319); -const is_key_object_js_1 = __nccwpck_require__(68685); -const invalid_key_input_js_1 = __nccwpck_require__(16632); -const is_key_like_js_1 = __nccwpck_require__(7433); -const checkKey = (key, alg) => { - if (key.asymmetricKeyType !== 'rsa') { - throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + /** + * Returns true if the address is a loopback address, false otherwise + * @memberof Address6 + * @instance + * @returns {boolean} + */ + isLoopback() { + return this.getType() === 'Loopback'; } - (0, check_key_length_js_1.default)(key, alg); -}; -const RSA1_5 = (0, node_util_1.deprecate)(() => node_crypto_1.constants.RSA_PKCS1_PADDING, 'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'); -const resolvePadding = (alg) => { - switch (alg) { - case 'RSA-OAEP': - case 'RSA-OAEP-256': - case 'RSA-OAEP-384': - case 'RSA-OAEP-512': - return node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING; - case 'RSA1_5': - return RSA1_5(); - default: - return undefined; + // #endregion + // #region HTML + /** + * @returns {String} the address in link form with a default port of 80 + */ + href(optionalPort) { + if (optionalPort === undefined) { + optionalPort = ''; + } + else { + optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort); + } + return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort); } -}; -const resolveOaepHash = (alg) => { - switch (alg) { - case 'RSA-OAEP': - return 'sha1'; - case 'RSA-OAEP-256': - return 'sha256'; - case 'RSA-OAEP-384': - return 'sha384'; - case 'RSA-OAEP-512': - return 'sha512'; - default: - return undefined; + /** + * @returns {String} a link suitable for conveying the address via a URL hash + */ + link(options) { + if (!options) { + options = {}; + } + if (options.className === undefined) { + options.className = ''; + } + if (options.prefix === undefined) { + options.prefix = '/#address='; + } + if (options.v4 === undefined) { + options.v4 = false; + } + let formFunction = this.correctForm; + if (options.v4) { + formFunction = this.to4in6; + } + if (options.className) { + return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className); + } + return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this)); } -}; -function ensureKeyObject(key, alg, ...usages) { - if ((0, is_key_object_js_1.default)(key)) { - return key; + /** + * Groups an address + * @returns {String} + */ + group() { + if (this.elidedGroups === 0) { + // The simple case + return helpers.simpleGroup(this.address).join(':'); + } + assert(typeof this.elidedGroups === 'number'); + assert(typeof this.elisionBegin === 'number'); + // The elided case + const output = []; + const [left, right] = this.address.split('::'); + if (left.length) { + output.push(...helpers.simpleGroup(left)); + } + else { + output.push(''); + } + const classes = ['hover-group']; + for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) { + classes.push((0, sprintf_js_1.sprintf)('group-%d', i)); + } + output.push((0, sprintf_js_1.sprintf)('', classes.join(' '))); + if (right.length) { + output.push(...helpers.simpleGroup(right, this.elisionEnd)); + } + else { + output.push(''); + } + if (this.is4()) { + assert(this.address4 instanceof ipv4_1.Address4); + output.pop(); + output.push(this.address4.groupForV6()); + } + return output.join(':'); + } + // #endregion + // #region Regular expressions + /** + * Generate a regular expression string that can be used to find or validate + * all variations of this address + * @memberof Address6 + * @instance + * @param {boolean} substringSearch + * @returns {string} + */ + regularExpressionString(substringSearch = false) { + let output = []; + // TODO: revisit why this is necessary + const address6 = new Address6(this.correctForm()); + if (address6.elidedGroups === 0) { + // The simple case + output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress)); + } + else if (address6.elidedGroups === constants6.GROUPS) { + // A completely elided address + output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS)); + } + else { + // A partially elided address + const halves = address6.address.split('::'); + if (halves[0].length) { + output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':'))); + } + assert(typeof address6.elidedGroups === 'number'); + output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0)); + if (halves[1].length) { + output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':'))); + } + output = [output.join(':')]; + } + if (!substringSearch) { + output = [ + '(?=^|', + regular_expressions_1.ADDRESS_BOUNDARY, + '|[^\\w\\:])(', + ...output, + ')(?=[^\\w\\:]|', + regular_expressions_1.ADDRESS_BOUNDARY, + '|$)', + ]; + } + return output.join(''); } - if ((0, webcrypto_js_1.isCryptoKey)(key)) { - (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages); - return node_crypto_1.KeyObject.from(key); + /** + * Generate a regular expression that can be used to find or validate all + * variations of this address. + * @memberof Address6 + * @instance + * @param {boolean} substringSearch + * @returns {RegExp} + */ + regularExpression(substringSearch = false) { + return new RegExp(this.regularExpressionString(substringSearch), 'i'); } - throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); } -const encrypt = (alg, key, cek) => { - const padding = resolvePadding(alg); - const oaepHash = resolveOaepHash(alg); - const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); - checkKey(keyObject, alg); - return (0, node_crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek); -}; -exports.encrypt = encrypt; -const decrypt = (alg, key, encryptedKey) => { - const padding = resolvePadding(alg); - const oaepHash = resolveOaepHash(alg); - const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); - checkKey(keyObject, alg); - return (0, node_crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey); -}; -exports.decrypt = decrypt; - +exports.Address6 = Address6; +//# sourceMappingURL=ipv6.js.map /***/ }), -/***/ 95527: +/***/ 66437: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = 'node:crypto'; - +exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0; +exports.BITS = 32; +exports.GROUPS = 4; +exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g; +exports.RE_SUBNET_STRING = /\/\d{1,2}$/; +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 26966: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 75280: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const crypto = __nccwpck_require__(77598); -const node_util_1 = __nccwpck_require__(57975); -const dsa_digest_js_1 = __nccwpck_require__(74510); -const hmac_digest_js_1 = __nccwpck_require__(57399); -const node_key_js_1 = __nccwpck_require__(70363); -const get_sign_verify_key_js_1 = __nccwpck_require__(80723); -const oneShotSign = (0, node_util_1.promisify)(crypto.sign); -const sign = async (alg, key, data) => { - const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign'); - if (alg.startsWith('HS')) { - const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), k); - hmac.update(data); - return hmac.digest(); - } - return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, k)); +exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0; +exports.BITS = 128; +exports.GROUPS = 8; +/** + * Represents IPv6 address scopes + * @memberof Address6 + * @static + */ +exports.SCOPES = { + 0: 'Reserved', + 1: 'Interface local', + 2: 'Link local', + 4: 'Admin local', + 5: 'Site local', + 8: 'Organization local', + 14: 'Global', + 15: 'Reserved', }; -exports["default"] = sign; - +/** + * Represents IPv6 address types + * @memberof Address6 + * @static + */ +exports.TYPES = { + 'ff01::1/128': 'Multicast (All nodes on this interface)', + 'ff01::2/128': 'Multicast (All routers on this interface)', + 'ff02::1/128': 'Multicast (All nodes on this link)', + 'ff02::2/128': 'Multicast (All routers on this link)', + 'ff05::2/128': 'Multicast (All routers in this site)', + 'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)', + 'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)', + 'ff02::9/128': 'Multicast (RIP routers)', + 'ff02::a/128': 'Multicast (EIGRP routers)', + 'ff02::d/128': 'Multicast (PIM routers)', + 'ff02::16/128': 'Multicast (MLDv2 reports)', + 'ff01::fb/128': 'Multicast (mDNSv6)', + 'ff02::fb/128': 'Multicast (mDNSv6)', + 'ff05::fb/128': 'Multicast (mDNSv6)', + 'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)', + 'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)', + 'ff02::1:3/128': 'Multicast (All DHCP servers on this link)', + 'ff05::1:3/128': 'Multicast (All DHCP servers in this site)', + '::/128': 'Unspecified', + '::1/128': 'Loopback', + 'ff00::/8': 'Multicast', + 'fe80::/10': 'Link-local unicast', +}; +/** + * A regular expression that matches bad characters in an IPv6 address + * @memberof Address6 + * @static + */ +exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi; +/** + * A regular expression that matches an incorrect IPv6 address + * @memberof Address6 + * @static + */ +exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi; +/** + * A regular expression that matches an IPv6 subnet + * @memberof Address6 + * @static + */ +exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/; +/** + * A regular expression that matches an IPv6 zone + * @memberof Address6 + * @static + */ +exports.RE_ZONE_STRING = /%.*$/; +exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/); +exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/); +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 39106: +/***/ 20339: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const node_crypto_1 = __nccwpck_require__(77598); -const timingSafeEqual = node_crypto_1.timingSafeEqual; -exports["default"] = timingSafeEqual; - +exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0; +const sprintf_js_1 = __nccwpck_require__(19973); +/** + * @returns {String} the string with all zeroes contained in a + */ +function spanAllZeroes(s) { + return s.replace(/(0+)/g, '$1'); +} +exports.spanAllZeroes = spanAllZeroes; +/** + * @returns {String} the string with each character contained in a + */ +function spanAll(s, offset = 0) { + const letters = s.split(''); + return letters + .map((n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead? + ) + .join(''); +} +exports.spanAll = spanAll; +function spanLeadingZeroesSimple(group) { + return group.replace(/^(0+)/, '$1'); +} +/** + * @returns {String} the string with leading zeroes contained in a + */ +function spanLeadingZeroes(address) { + const groups = address.split(':'); + return groups.map((g) => spanLeadingZeroesSimple(g)).join(':'); +} +exports.spanLeadingZeroes = spanLeadingZeroes; +/** + * Groups an address + * @returns {String} a grouped address + */ +function simpleGroup(addressString, offset = 0) { + const groups = addressString.split(':'); + return groups.map((g, i) => { + if (/group-v4/.test(g)) { + return g; + } + return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g)); + }); +} +exports.simpleGroup = simpleGroup; +//# sourceMappingURL=helpers.js.map /***/ }), -/***/ 11242: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 72016: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const crypto = __nccwpck_require__(77598); -const node_util_1 = __nccwpck_require__(57975); -const dsa_digest_js_1 = __nccwpck_require__(74510); -const node_key_js_1 = __nccwpck_require__(70363); -const sign_js_1 = __nccwpck_require__(26966); -const get_sign_verify_key_js_1 = __nccwpck_require__(80723); -const oneShotVerify = (0, node_util_1.promisify)(crypto.verify); -const verify = async (alg, key, signature, data) => { - const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify'); - if (alg.startsWith('HS')) { - const expected = await (0, sign_js_1.default)(alg, k, data); - const actual = signature; - try { - return crypto.timingSafeEqual(actual, expected); +exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0; +const v6 = __importStar(__nccwpck_require__(75280)); +const sprintf_js_1 = __nccwpck_require__(19973); +function groupPossibilities(possibilities) { + return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|')); +} +exports.groupPossibilities = groupPossibilities; +function padGroup(group) { + if (group.length < 4) { + return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group); + } + return group; +} +exports.padGroup = padGroup; +exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]'; +function simpleRegularExpression(groups) { + const zeroIndexes = []; + groups.forEach((group, i) => { + const groupInteger = parseInt(group, 16); + if (groupInteger === 0) { + zeroIndexes.push(i); } - catch { - return false; + }); + // You can technically elide a single 0, this creates the regular expressions + // to match that eventuality + const possibilities = zeroIndexes.map((zeroIndex) => groups + .map((group, i) => { + if (i === zeroIndex) { + const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : ''; + return groupPossibilities([padGroup(group), elision]); } + return padGroup(group); + }) + .join(':')); + // The simplest case + possibilities.push(groups.map(padGroup).join(':')); + return groupPossibilities(possibilities); +} +exports.simpleRegularExpression = simpleRegularExpression; +function possibleElisions(elidedGroups, moreLeft, moreRight) { + const left = moreLeft ? '' : ':'; + const right = moreRight ? '' : ':'; + const possibilities = []; + // 1. elision of everything (::) + if (!moreLeft && !moreRight) { + possibilities.push('::'); } - const algorithm = (0, dsa_digest_js_1.default)(alg); - const keyInput = (0, node_key_js_1.default)(alg, k); - try { - return await oneShotVerify(algorithm, data, keyInput, signature); + // 2. complete elision of the middle + if (moreLeft && moreRight) { + possibilities.push(''); } - catch { - return false; + if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) { + // 3. complete elision of one side + possibilities.push(':'); } -}; -exports["default"] = verify; + // 4. elision from the left side + possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1)); + // 5. elision from the right side + possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right)); + // 6. no elision + possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1)); + // 7. elision (including sloppy elision) from the middle + for (let groups = 1; groups < elidedGroups - 1; groups++) { + for (let position = 1; position < elidedGroups - groups; position++) { + possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1)); + } + } + return groupPossibilities(possibilities); +} +exports.possibleElisions = possibleElisions; +//# sourceMappingURL=regular-expressions.js.map + +/***/ }), + +/***/ 21608: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.experimental_jwksCache = exports.jwksCache = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0; +var decrypt_js_1 = __nccwpck_require__(14298); +Object.defineProperty(exports, "compactDecrypt", ({ enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } })); +var decrypt_js_2 = __nccwpck_require__(59344); +Object.defineProperty(exports, "flattenedDecrypt", ({ enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } })); +var decrypt_js_3 = __nccwpck_require__(49783); +Object.defineProperty(exports, "generalDecrypt", ({ enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } })); +var encrypt_js_1 = __nccwpck_require__(71907); +Object.defineProperty(exports, "GeneralEncrypt", ({ enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } })); +var verify_js_1 = __nccwpck_require__(94212); +Object.defineProperty(exports, "compactVerify", ({ enumerable: true, get: function () { return verify_js_1.compactVerify; } })); +var verify_js_2 = __nccwpck_require__(56358); +Object.defineProperty(exports, "flattenedVerify", ({ enumerable: true, get: function () { return verify_js_2.flattenedVerify; } })); +var verify_js_3 = __nccwpck_require__(88323); +Object.defineProperty(exports, "generalVerify", ({ enumerable: true, get: function () { return verify_js_3.generalVerify; } })); +var verify_js_4 = __nccwpck_require__(35297); +Object.defineProperty(exports, "jwtVerify", ({ enumerable: true, get: function () { return verify_js_4.jwtVerify; } })); +var decrypt_js_4 = __nccwpck_require__(95339); +Object.defineProperty(exports, "jwtDecrypt", ({ enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } })); +var encrypt_js_2 = __nccwpck_require__(4434); +Object.defineProperty(exports, "CompactEncrypt", ({ enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } })); +var encrypt_js_3 = __nccwpck_require__(62372); +Object.defineProperty(exports, "FlattenedEncrypt", ({ enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } })); +var sign_js_1 = __nccwpck_require__(21760); +Object.defineProperty(exports, "CompactSign", ({ enumerable: true, get: function () { return sign_js_1.CompactSign; } })); +var sign_js_2 = __nccwpck_require__(86170); +Object.defineProperty(exports, "FlattenedSign", ({ enumerable: true, get: function () { return sign_js_2.FlattenedSign; } })); +var sign_js_3 = __nccwpck_require__(50443); +Object.defineProperty(exports, "GeneralSign", ({ enumerable: true, get: function () { return sign_js_3.GeneralSign; } })); +var sign_js_4 = __nccwpck_require__(22713); +Object.defineProperty(exports, "SignJWT", ({ enumerable: true, get: function () { return sign_js_4.SignJWT; } })); +var encrypt_js_4 = __nccwpck_require__(38375); +Object.defineProperty(exports, "EncryptJWT", ({ enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } })); +var thumbprint_js_1 = __nccwpck_require__(45396); +Object.defineProperty(exports, "calculateJwkThumbprint", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } })); +Object.defineProperty(exports, "calculateJwkThumbprintUri", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } })); +var embedded_js_1 = __nccwpck_require__(88541); +Object.defineProperty(exports, "EmbeddedJWK", ({ enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } })); +var local_js_1 = __nccwpck_require__(25275); +Object.defineProperty(exports, "createLocalJWKSet", ({ enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } })); +var remote_js_1 = __nccwpck_require__(69260); +Object.defineProperty(exports, "createRemoteJWKSet", ({ enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } })); +Object.defineProperty(exports, "jwksCache", ({ enumerable: true, get: function () { return remote_js_1.jwksCache; } })); +Object.defineProperty(exports, "experimental_jwksCache", ({ enumerable: true, get: function () { return remote_js_1.experimental_jwksCache; } })); +var unsecured_js_1 = __nccwpck_require__(40560); +Object.defineProperty(exports, "UnsecuredJWT", ({ enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } })); +var export_js_1 = __nccwpck_require__(48108); +Object.defineProperty(exports, "exportPKCS8", ({ enumerable: true, get: function () { return export_js_1.exportPKCS8; } })); +Object.defineProperty(exports, "exportSPKI", ({ enumerable: true, get: function () { return export_js_1.exportSPKI; } })); +Object.defineProperty(exports, "exportJWK", ({ enumerable: true, get: function () { return export_js_1.exportJWK; } })); +var import_js_1 = __nccwpck_require__(45647); +Object.defineProperty(exports, "importSPKI", ({ enumerable: true, get: function () { return import_js_1.importSPKI; } })); +Object.defineProperty(exports, "importPKCS8", ({ enumerable: true, get: function () { return import_js_1.importPKCS8; } })); +Object.defineProperty(exports, "importX509", ({ enumerable: true, get: function () { return import_js_1.importX509; } })); +Object.defineProperty(exports, "importJWK", ({ enumerable: true, get: function () { return import_js_1.importJWK; } })); +var decode_protected_header_js_1 = __nccwpck_require__(14704); +Object.defineProperty(exports, "decodeProtectedHeader", ({ enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } })); +var decode_jwt_js_1 = __nccwpck_require__(60002); +Object.defineProperty(exports, "decodeJwt", ({ enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } })); +exports.errors = __nccwpck_require__(15974); +var generate_key_pair_js_1 = __nccwpck_require__(87820); +Object.defineProperty(exports, "generateKeyPair", ({ enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } })); +var generate_secret_js_1 = __nccwpck_require__(37152); +Object.defineProperty(exports, "generateSecret", ({ enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } })); +exports.base64url = __nccwpck_require__(78305); +var runtime_js_1 = __nccwpck_require__(25021); +Object.defineProperty(exports, "cryptoRuntime", ({ enumerable: true, get: function () { return runtime_js_1.default; } })); /***/ }), -/***/ 59044: +/***/ 14298: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isCryptoKey = void 0; -const crypto = __nccwpck_require__(77598); -const util = __nccwpck_require__(57975); -const webcrypto = crypto.webcrypto; -exports["default"] = webcrypto; -const isCryptoKey = (key) => util.types.isCryptoKey(key); -exports.isCryptoKey = isCryptoKey; +exports.compactDecrypt = compactDecrypt; +const decrypt_js_1 = __nccwpck_require__(59344); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +async function compactDecrypt(jwe, key, options) { + if (jwe instanceof Uint8Array) { + jwe = buffer_utils_js_1.decoder.decode(jwe); + } + if (typeof jwe !== 'string') { + throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array'); + } + const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); + if (length !== 5) { + throw new errors_js_1.JWEInvalid('Invalid Compact JWE'); + } + const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({ + ciphertext, + iv: iv || undefined, + protected: protectedHeader, + tag: tag || undefined, + encrypted_key: encryptedKey || undefined, + }, key, options); + const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; + } + return result; +} /***/ }), -/***/ 78305: +/***/ 4434: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decode = exports.encode = void 0; -const base64url = __nccwpck_require__(12635); -exports.encode = base64url.encode; -exports.decode = base64url.decode; +exports.CompactEncrypt = void 0; +const encrypt_js_1 = __nccwpck_require__(62372); +class CompactEncrypt { + _flattened; + constructor(plaintext) { + this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext); + } + setContentEncryptionKey(cek) { + this._flattened.setContentEncryptionKey(cek); + return this; + } + setInitializationVector(iv) { + this._flattened.setInitializationVector(iv); + return this; + } + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; + } + setKeyManagementParameters(parameters) { + this._flattened.setKeyManagementParameters(parameters); + return this; + } + async encrypt(key, options) { + const jwe = await this._flattened.encrypt(key, options); + return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); + } +} +exports.CompactEncrypt = CompactEncrypt; /***/ }), -/***/ 60002: +/***/ 59344: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decodeJwt = decodeJwt; -const base64url_js_1 = __nccwpck_require__(78305); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const is_object_js_1 = __nccwpck_require__(92242); +exports.flattenedDecrypt = flattenedDecrypt; +const base64url_js_1 = __nccwpck_require__(12635); +const decrypt_js_1 = __nccwpck_require__(52806); const errors_js_1 = __nccwpck_require__(15974); -function decodeJwt(jwt) { - if (typeof jwt !== 'string') - throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); - const { 1: payload, length } = jwt.split('.'); - if (length === 5) - throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); - if (length !== 3) - throw new errors_js_1.JWTInvalid('Invalid JWT'); - if (!payload) - throw new errors_js_1.JWTInvalid('JWTs must contain a payload'); - let decoded; - try { - decoded = (0, base64url_js_1.decode)(payload); +const is_disjoint_js_1 = __nccwpck_require__(21853); +const is_object_js_1 = __nccwpck_require__(92242); +const decrypt_key_management_js_1 = __nccwpck_require__(56243); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const cek_js_1 = __nccwpck_require__(87937); +const validate_crit_js_1 = __nccwpck_require__(15595); +const validate_algorithms_js_1 = __nccwpck_require__(19917); +async function flattenedDecrypt(jwe, key, options) { + if (!(0, is_object_js_1.default)(jwe)) { + throw new errors_js_1.JWEInvalid('Flattened JWE must be an object'); + } + if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { + throw new errors_js_1.JWEInvalid('JOSE Header missing'); + } + if (jwe.iv !== undefined && typeof jwe.iv !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Initialization Vector incorrect type'); + } + if (typeof jwe.ciphertext !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type'); } - catch { - throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload'); + if (jwe.tag !== undefined && typeof jwe.tag !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Authentication Tag incorrect type'); } - let result; - try { - result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded)); + if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type'); } - catch { - throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON'); + if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { + throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type'); } - if (!(0, is_object_js_1.default)(result)) - throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set'); - return result; -} - - -/***/ }), - -/***/ 14704: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.decodeProtectedHeader = decodeProtectedHeader; -const base64url_js_1 = __nccwpck_require__(78305); -const buffer_utils_js_1 = __nccwpck_require__(45734); -const is_object_js_1 = __nccwpck_require__(92242); -function decodeProtectedHeader(token) { - let protectedB64u; - if (typeof token === 'string') { - const parts = token.split('.'); - if (parts.length === 3 || parts.length === 5) { - ; - [protectedB64u] = parts; + if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { + throw new errors_js_1.JWEInvalid('JWE AAD incorrect type'); + } + if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) { + throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type'); + } + if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) { + throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); + } + let parsedProt; + if (jwe.protected) { + try { + const protectedHeader = (0, base64url_js_1.decode)(jwe.protected); + parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); + } + catch { + throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid'); } } - else if (typeof token === 'object' && token) { - if ('protected' in token) { - protectedB64u = token.protected; + if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) { + throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jwe.header, + ...jwe.unprotected, + }; + (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader); + if (joseHeader.zip !== undefined) { + throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); + } + if (typeof enc !== 'string' || !enc) { + throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); + } + const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms); + const contentEncryptionAlgorithms = options && + (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); + if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) || + (!keyManagementAlgorithms && alg.startsWith('PBES2'))) { + throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { + throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed'); + } + let encryptedKey; + if (jwe.encrypted_key !== undefined) { + try { + encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key); } - else { - throw new TypeError('Token does not contain a Protected Header'); + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key'); } } + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jwe); + resolvedKey = true; + } + let cek; try { - if (typeof protectedB64u !== 'string' || !protectedB64u) { - throw new Error(); + cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options); + } + catch (err) { + if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) { + throw err; } - const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u))); - if (!(0, is_object_js_1.default)(result)) { - throw new Error(); + cek = (0, cek_js_1.default)(enc); + } + let iv; + let tag; + if (jwe.iv !== undefined) { + try { + iv = (0, base64url_js_1.decode)(jwe.iv); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); } - return result; } - catch { - throw new TypeError('Invalid Token or Protected Header formatting'); + if (jwe.tag !== undefined) { + try { + tag = (0, base64url_js_1.decode)(jwe.tag); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); + } } -} - - -/***/ }), - -/***/ 15974: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0; -class JOSEError extends Error { - static code = 'ERR_JOSE_GENERIC'; - code = 'ERR_JOSE_GENERIC'; - constructor(message, options) { - super(message, options); - this.name = this.constructor.name; - Error.captureStackTrace?.(this, this.constructor); + const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? ''); + let additionalData; + if (jwe.aad !== undefined) { + additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad)); } -} -exports.JOSEError = JOSEError; -class JWTClaimValidationFailed extends JOSEError { - static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; - claim; - reason; - payload; - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message, { cause: { claim, reason, payload } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; + else { + additionalData = protectedHeader; } -} -exports.JWTClaimValidationFailed = JWTClaimValidationFailed; -class JWTExpired extends JOSEError { - static code = 'ERR_JWT_EXPIRED'; - code = 'ERR_JWT_EXPIRED'; - claim; - reason; - payload; - constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { - super(message, { cause: { claim, reason, payload } }); - this.claim = claim; - this.reason = reason; - this.payload = payload; + let ciphertext; + try { + ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext); } -} -exports.JWTExpired = JWTExpired; -class JOSEAlgNotAllowed extends JOSEError { - static code = 'ERR_JOSE_ALG_NOT_ALLOWED'; - code = 'ERR_JOSE_ALG_NOT_ALLOWED'; -} -exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed; -class JOSENotSupported extends JOSEError { - static code = 'ERR_JOSE_NOT_SUPPORTED'; - code = 'ERR_JOSE_NOT_SUPPORTED'; -} -exports.JOSENotSupported = JOSENotSupported; -class JWEDecryptionFailed extends JOSEError { - static code = 'ERR_JWE_DECRYPTION_FAILED'; - code = 'ERR_JWE_DECRYPTION_FAILED'; - constructor(message = 'decryption operation failed', options) { - super(message, options); + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext'); } -} -exports.JWEDecryptionFailed = JWEDecryptionFailed; -class JWEInvalid extends JOSEError { - static code = 'ERR_JWE_INVALID'; - code = 'ERR_JWE_INVALID'; -} -exports.JWEInvalid = JWEInvalid; -class JWSInvalid extends JOSEError { - static code = 'ERR_JWS_INVALID'; - code = 'ERR_JWS_INVALID'; -} -exports.JWSInvalid = JWSInvalid; -class JWTInvalid extends JOSEError { - static code = 'ERR_JWT_INVALID'; - code = 'ERR_JWT_INVALID'; -} -exports.JWTInvalid = JWTInvalid; -class JWKInvalid extends JOSEError { - static code = 'ERR_JWK_INVALID'; - code = 'ERR_JWK_INVALID'; -} -exports.JWKInvalid = JWKInvalid; -class JWKSInvalid extends JOSEError { - static code = 'ERR_JWKS_INVALID'; - code = 'ERR_JWKS_INVALID'; -} -exports.JWKSInvalid = JWKSInvalid; -class JWKSNoMatchingKey extends JOSEError { - static code = 'ERR_JWKS_NO_MATCHING_KEY'; - code = 'ERR_JWKS_NO_MATCHING_KEY'; - constructor(message = 'no applicable key found in the JSON Web Key Set', options) { - super(message, options); + const plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData); + const result = { plaintext }; + if (jwe.protected !== undefined) { + result.protectedHeader = parsedProt; } -} -exports.JWKSNoMatchingKey = JWKSNoMatchingKey; -class JWKSMultipleMatchingKeys extends JOSEError { - [Symbol.asyncIterator]; - static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; - constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) { - super(message, options); + if (jwe.aad !== undefined) { + try { + result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad'); + } } -} -exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys; -class JWKSTimeout extends JOSEError { - static code = 'ERR_JWKS_TIMEOUT'; - code = 'ERR_JWKS_TIMEOUT'; - constructor(message = 'request timed out', options) { - super(message, options); + if (jwe.unprotected !== undefined) { + result.sharedUnprotectedHeader = jwe.unprotected; } -} -exports.JWKSTimeout = JWKSTimeout; -class JWSSignatureVerificationFailed extends JOSEError { - static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; - constructor(message = 'signature verification failed', options) { - super(message, options); + if (jwe.header !== undefined) { + result.unprotectedHeader = jwe.header; + } + if (resolvedKey) { + return { ...result, key }; } + return result; } -exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed; /***/ }), -/***/ 25021: +/***/ 62372: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const runtime_js_1 = __nccwpck_require__(95527); -exports["default"] = runtime_js_1.default; - - -/***/ }), - -/***/ 95947: -/***/ (function(module, exports) { - -(function(){ - - // Copyright (c) 2005 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Basic JavaScript BN library - subset useful for RSA encryption. - - // Bits per digit - var dbits; - - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = ((canary&0xffffff)==0xefcafe); - - // (public) Constructor - function BigInteger(a,b,c) { - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); +exports.FlattenedEncrypt = void 0; +const base64url_js_1 = __nccwpck_require__(12635); +const private_symbols_js_1 = __nccwpck_require__(46433); +const encrypt_js_1 = __nccwpck_require__(36286); +const encrypt_key_management_js_1 = __nccwpck_require__(96539); +const errors_js_1 = __nccwpck_require__(15974); +const is_disjoint_js_1 = __nccwpck_require__(21853); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const validate_crit_js_1 = __nccwpck_require__(15595); +class FlattenedEncrypt { + _plaintext; + _protectedHeader; + _sharedUnprotectedHeader; + _unprotectedHeader; + _aad; + _cek; + _iv; + _keyManagementParameters; + constructor(plaintext) { + if (!(plaintext instanceof Uint8Array)) { + throw new TypeError('plaintext must be an instance of Uint8Array'); + } + this._plaintext = plaintext; } - - // return new, unset BigInteger - function nbi() { return new BigInteger(null); } - - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. - - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this[i++]+w[j]+c; - c = Math.floor(v/0x4000000); - w[j++] = v&0x3ffffff; - } - return c; + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) - function am2(i,x,w,j,c,n) { - var xl = x&0x7fff, xh = x>>15; - while(--n >= 0) { - var l = this[i]&0x7fff; - var h = this[i++]>>15; - var m = xh*l+h*xl; - l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); - c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); - w[j++] = l&0x3fffffff; - } - return c; + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; } - // Alternately, set max digit bits to 28 since some - // browsers slow down when dealing with 32-bit numbers. - function am3(i,x,w,j,c,n) { - var xl = x&0x3fff, xh = x>>14; - while(--n >= 0) { - var l = this[i]&0x3fff; - var h = this[i++]>>14; - var m = xh*l+h*xl; - l = xl*l+((m&0x3fff)<<14)+w[j]+c; - c = (l>>28)+(m>>14)+xh*h; - w[j++] = l&0xfffffff; - } - return c; + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._sharedUnprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); + } + this._sharedUnprotectedHeader = sharedUnprotectedHeader; + return this; } - var inBrowser = typeof navigator !== "undefined"; - if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { - BigInteger.prototype.am = am2; - dbits = 30; + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this._unprotectedHeader = unprotectedHeader; + return this; } - else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { - BigInteger.prototype.am = am1; - dbits = 26; + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; } - else { // Mozilla/Netscape seems to prefer am3 - BigInteger.prototype.am = am3; - dbits = 28; + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + async encrypt(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { + throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); + } + if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { + throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...this._sharedUnprotectedHeader, + }; + (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + const { alg, enc } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (typeof enc !== 'string' || !enc) { + throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + let encryptedKey; + if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) { + throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`); + } + let cek; + { + let parameters; + ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters)); + if (parameters) { + if (options && private_symbols_js_1.unprotected in options) { + if (!this._unprotectedHeader) { + this.setUnprotectedHeader(parameters); + } + else { + this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; + } + } + else if (!this._protectedHeader) { + this.setProtectedHeader(parameters); + } + else { + this._protectedHeader = { ...this._protectedHeader, ...parameters }; + } + } + } + let additionalData; + let protectedHeader; + let aadMember; + if (this._protectedHeader) { + protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); + } + else { + protectedHeader = buffer_utils_js_1.encoder.encode(''); + } + if (this._aad) { + aadMember = (0, base64url_js_1.encode)(this._aad); + additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember)); + } + else { + additionalData = protectedHeader; + } + const { ciphertext, tag, iv } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData); + const jwe = { + ciphertext: (0, base64url_js_1.encode)(ciphertext), + }; + if (iv) { + jwe.iv = (0, base64url_js_1.encode)(iv); + } + if (tag) { + jwe.tag = (0, base64url_js_1.encode)(tag); + } + if (encryptedKey) { + jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); + } + if (aadMember) { + jwe.aad = aadMember; + } + if (this._protectedHeader) { + jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader); + } + if (this._sharedUnprotectedHeader) { + jwe.unprotected = this._sharedUnprotectedHeader; + } + if (this._unprotectedHeader) { + jwe.header = this._unprotectedHeader; + } + return jwe; } +} +exports.FlattenedEncrypt = FlattenedEncrypt; - BigInteger.prototype.DB = dbits; - BigInteger.prototype.DM = ((1< { - function int2char(n) { return BI_RM.charAt(n); } - function intAt(s,i) { - var c = BI_RC[s.charCodeAt(i)]; - return (c==null)?-1:c; - } +"use strict"; - // (protected) copy this to r - function bnpCopyTo(r) { - for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; - r.t = this.t; - r.s = this.s; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generalDecrypt = generalDecrypt; +const decrypt_js_1 = __nccwpck_require__(59344); +const errors_js_1 = __nccwpck_require__(15974); +const is_object_js_1 = __nccwpck_require__(92242); +async function generalDecrypt(jwe, key, options) { + if (!(0, is_object_js_1.default)(jwe)) { + throw new errors_js_1.JWEInvalid('General JWE must be an object'); } - - // (protected) set from integer value x, -DV <= x < DV - function bnpFromInt(x) { - this.t = 1; - this.s = (x<0)?-1:0; - if(x > 0) this[0] = x; - else if(x < -1) this[0] = x+this.DV; - else this.t = 0; + if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) { + throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type'); } - - // return bigint initialized to value - function nbv(i) { var r = nbi(); r.fromInt(i); return r; } - - // (protected) set from string and radix - function bnpFromString(s,b) { - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 256) k = 8; // byte array - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else { this.fromRadix(s,b); return; } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while(--i >= 0) { - var x = (k==8)?s[i]&0xff:intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-") mi = true; - continue; + if (!jwe.recipients.length) { + throw new errors_js_1.JWEInvalid('JWE Recipients has no members'); + } + for (const recipient of jwe.recipients) { + try { + return await (0, decrypt_js_1.flattenedDecrypt)({ + aad: jwe.aad, + ciphertext: jwe.ciphertext, + encrypted_key: recipient.encrypted_key, + header: recipient.header, + iv: jwe.iv, + protected: jwe.protected, + tag: jwe.tag, + unprotected: jwe.unprotected, + }, key, options); } - mi = false; - if(sh == 0) - this[this.t++] = x; - else if(sh+k > this.DB) { - this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + catch { } - else - this[this.t-1] |= x<= this.DB) sh -= this.DB; - } - if(k == 8 && (s[0]&0x80) != 0) { - this.s = -1; - if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; - } - // (public) return string representation in given radix - function bnToString(b) { - if(this.s < 0) return "-"+this.negate().toString(b); - var k; - if(b == 16) k = 4; - else if(b == 8) k = 3; - else if(b == 2) k = 1; - else if(b == 32) k = 5; - else if(b == 4) k = 2; - else return this.toRadix(b); - var km = (1< 0) { - if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } - while(i >= 0) { - if(p < k) { - d = (this[i]&((1<>(p+=this.DB-k); - } - else { - d = (this[i]>>(p-=k))&km; - if(p <= 0) { p += this.DB; --i; } - } - if(d > 0) m = true; - if(m) r += int2char(d); - } - } - return m?r:"0"; - } +/***/ }), - // (public) -this - function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } +/***/ 71907: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // (public) |this| - function bnAbs() { return (this.s<0)?this.negate():this; } +"use strict"; - // (public) return + if this > a, - if this < a, 0 if equal - function bnCompareTo(a) { - var r = this.s-a.s; - if(r != 0) return r; - var i = this.t; - r = i-a.t; - if(r != 0) return (this.s<0)?-r:r; - while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; - return 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GeneralEncrypt = void 0; +const encrypt_js_1 = __nccwpck_require__(62372); +const private_symbols_js_1 = __nccwpck_require__(46433); +const errors_js_1 = __nccwpck_require__(15974); +const cek_js_1 = __nccwpck_require__(87937); +const is_disjoint_js_1 = __nccwpck_require__(21853); +const encrypt_key_management_js_1 = __nccwpck_require__(96539); +const base64url_js_1 = __nccwpck_require__(12635); +const validate_crit_js_1 = __nccwpck_require__(15595); +class IndividualRecipient { + parent; + unprotectedHeader; + key; + options; + constructor(enc, key, options) { + this.parent = enc; + this.key = key; + this.options = options; } - - // returns bit length of the integer x - function nbits(x) { - var r = 1, t; - if((t=x>>>16) != 0) { x = t; r += 16; } - if((t=x>>8) != 0) { x = t; r += 8; } - if((t=x>>4) != 0) { x = t; r += 4; } - if((t=x>>2) != 0) { x = t; r += 2; } - if((t=x>>1) != 0) { x = t; r += 1; } - return r; + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; } - - // (public) return the number of bits in "this" - function bnBitLength() { - if(this.t <= 0) return 0; - return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); + addRecipient(...args) { + return this.parent.addRecipient(...args); } - - // (protected) r = this << n*DB - function bnpDLShiftTo(n,r) { - var i; - for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; - for(i = n-1; i >= 0; --i) r[i] = 0; - r.t = this.t+n; - r.s = this.s; + encrypt(...args) { + return this.parent.encrypt(...args); } - - // (protected) r = this >> n*DB - function bnpDRShiftTo(n,r) { - for(var i = n; i < this.t; ++i) r[i-n] = this[i]; - r.t = Math.max(this.t-n,0); - r.s = this.s; + done() { + return this.parent; } - - // (protected) r = this << n - function bnpLShiftTo(n,r) { - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<= 0; --i) { - r[i+ds+1] = (this[i]>>cbs)|c; - c = (this[i]&bm)<= 0; --i) r[i] = 0; - r[ds] = c; - r.t = this.t+ds+1; - r.s = this.s; - r.clamp(); +} +class GeneralEncrypt { + _plaintext; + _recipients = []; + _protectedHeader; + _unprotectedHeader; + _aad; + constructor(plaintext) { + this._plaintext = plaintext; } - - // (protected) r = this >> n - function bnpRShiftTo(n,r) { - r.s = this.s; - var ds = Math.floor(n/this.DB); - if(ds >= this.t) { r.t = 0; return; } - var bs = n%this.DB; - var cbs = this.DB-bs; - var bm = (1<>bs; - for(var i = ds+1; i < this.t; ++i) { - r[i-ds-1] |= (this[i]&bm)<>bs; - } - if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB; - } - if(a.t < this.t) { - c -= a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c -= a[i]; - r[i++] = c&this.DM; - c >>= this.DB; + this._protectedHeader = protectedHeader; + return this; + } + setSharedUnprotectedHeader(sharedUnprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setSharedUnprotectedHeader can only be called once'); } - c -= a.s; - } - r.s = (c<0)?-1:0; - if(c < -1) r[i++] = this.DV+c; - else if(c > 0) r[i++] = c; - r.t = i; - r.clamp(); + this._unprotectedHeader = sharedUnprotectedHeader; + return this; } - - // (protected) r = this * a, r != this,a (HAC 14.12) - // "this" should be the larger one if appropriate. - function bnpMultiplyTo(a,r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i+y.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); - r.s = 0; - r.clamp(); - if(this.s != a.s) BigInteger.ZERO.subTo(r,r); + setAdditionalAuthenticatedData(aad) { + this._aad = aad; + return this; } - - // (protected) r = this^2, r != this (HAC 14.16) - function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2*x.t; - while(--i >= 0) r[i] = 0; - for(i = 0; i < x.t-1; ++i) { - var c = x.am(i,x[i],r,2*i,0,1); - if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { - r[i+x.t] -= x.DV; - r[i+x.t+1] = 1; + async encrypt() { + if (!this._recipients.length) { + throw new errors_js_1.JWEInvalid('at least one recipient must be added'); } - } - if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); - r.s = 0; - r.clamp(); - } - - // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) - // r != q, this != m. q or r may be null. - function bnpDivRemTo(m,q,r) { - var pm = m.abs(); - if(pm.t <= 0) return; - var pt = this.abs(); - if(pt.t < pm.t) { - if(q != null) q.fromInt(0); - if(r != null) this.copyTo(r); - return; - } - if(r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus - if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } - else { pm.copyTo(y); pt.copyTo(r); } - var ys = y.t; - var y0 = y[ys-1]; - if(y0 == 0) return; - var yt = y0*(1<1)?y[ys-2]>>this.F2:0); - var d1 = this.FV/yt, d2 = (1<= 0) { - r[r.t++] = 1; - r.subTo(t,r); - } - BigInteger.ONE.dlShiftTo(ys,t); - t.subTo(y,y); // "negative" y so we can replace sub with am later - while(y.t < ys) y[y.t++] = 0; - while(--j >= 0) { - // Estimate quotient digit - var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); - if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out - y.dlShiftTo(j,t); - r.subTo(t,r); - while(r[i] < --qd) r.subTo(t,r); + if (this._recipients.length === 1) { + const [recipient] = this._recipients; + const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .encrypt(recipient.key, { ...recipient.options }); + const jwe = { + ciphertext: flattened.ciphertext, + iv: flattened.iv, + recipients: [{}], + tag: flattened.tag, + }; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + if (flattened.encrypted_key) + jwe.recipients[0].encrypted_key = flattened.encrypted_key; + if (flattened.header) + jwe.recipients[0].header = flattened.header; + return jwe; } - } - if(q != null) { - r.drShiftTo(ys,q); - if(ts != ms) BigInteger.ZERO.subTo(q,q); - } - r.t = ys; - r.clamp(); - if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder - if(ts < 0) BigInteger.ZERO.subTo(r,r); - } - - // (public) this mod a - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a,null,r); - if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); - return r; - } - - // Modular reduction using "classic" algorithm - function Classic(m) { this.m = m; } - function cConvert(x) { - if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; + let enc; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { + throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); + } + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); + } + if (alg === 'dir' || alg === 'ECDH-ES') { + throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); + } + if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { + throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); + } + if (!enc) { + enc = joseHeader.enc; + } + else if (enc !== joseHeader.enc) { + throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); + } + (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); + if (joseHeader.zip !== undefined) { + throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.'); + } + } + const cek = (0, cek_js_1.default)(enc); + const jwe = { + ciphertext: '', + iv: '', + recipients: [], + tag: '', + }; + for (let i = 0; i < this._recipients.length; i++) { + const recipient = this._recipients[i]; + const target = {}; + jwe.recipients.push(target); + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + ...recipient.unprotectedHeader, + }; + const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; + if (i === 0) { + const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) + .setAdditionalAuthenticatedData(this._aad) + .setContentEncryptionKey(cek) + .setProtectedHeader(this._protectedHeader) + .setSharedUnprotectedHeader(this._unprotectedHeader) + .setUnprotectedHeader(recipient.unprotectedHeader) + .setKeyManagementParameters({ p2c }) + .encrypt(recipient.key, { + ...recipient.options, + [private_symbols_js_1.unprotected]: true, + }); + jwe.ciphertext = flattened.ciphertext; + jwe.iv = flattened.iv; + jwe.tag = flattened.tag; + if (flattened.aad) + jwe.aad = flattened.aad; + if (flattened.protected) + jwe.protected = flattened.protected; + if (flattened.unprotected) + jwe.unprotected = flattened.unprotected; + target.encrypted_key = flattened.encrypted_key; + if (flattened.header) + target.header = flattened.header; + continue; + } + const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg || + this._protectedHeader?.alg || + this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c }); + target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); + if (recipient.unprotectedHeader || parameters) + target.header = { ...recipient.unprotectedHeader, ...parameters }; + } + return jwe; } - function cRevert(x) { return x; } - function cReduce(x) { x.divRemTo(this.m,null,x); } - function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } - function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } +} +exports.GeneralEncrypt = GeneralEncrypt; - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - // (protected) return "-1/this % 2^DB"; useful for Mont. reduction - // justification: - // xy == 1 (mod m) - // xy = 1+km - // xy(2-xy) = (1+km)(1-km) - // x[y(2-xy)] = 1-k^2m^2 - // x[y(2-xy)] == 1 (mod m^2) - // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 - // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. - // JS multiply "overflows" differently from C/C++, so care is needed here. - function bnpInvDigit() { - if(this.t < 1) return 0; - var x = this[0]; - if((x&1) == 0) return 0; - var y = x&3; // y == 1/x mod 2^2 - y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 - y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 - y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly; - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y>0)?this.DV-y:-y; - } +/***/ }), - // Montgomery reduction - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp&0x7fff; - this.mph = this.mp>>15; - this.um = (1<<(m.DB-15))-1; - this.mt2 = 2*m.t; - } +/***/ 88541: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // xR mod m - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t,r); - r.divRemTo(this.m,null,r); - if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); - return r; - } +"use strict"; - // x/R mod m - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.EmbeddedJWK = EmbeddedJWK; +const import_js_1 = __nccwpck_require__(45647); +const is_object_js_1 = __nccwpck_require__(92242); +const errors_js_1 = __nccwpck_require__(15974); +async function EmbeddedJWK(protectedHeader, token) { + const joseHeader = { + ...protectedHeader, + ...token?.header, + }; + if (!(0, is_object_js_1.default)(joseHeader.jwk)) { + throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); } - - // x = x/R mod m (HAC 14.32) - function montReduce(x) { - while(x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0; - for(var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i]&0x7fff; - var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; - // use am to combine the multiply-shift-add into one call - j = i+this.m.t; - x[j] += this.m.am(0,u0,x,i,0,this.m.t); - // propagate carry - while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } - } - x.clamp(); - x.drShiftTo(this.m.t,x); - if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); + const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); } + return key; +} - // r = "x^2/R mod m"; x != r - function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - // r = "xy/R mod m"; x,y != r - function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +/***/ }), - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; +/***/ 45396: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // (protected) true iff this is even - function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } +"use strict"; - // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) - function bnpExp(e,z) { - if(e > 0xffffffff || e < 1) return BigInteger.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; - g.copyTo(r); - while(--i >= 0) { - z.sqrTo(r,r2); - if((e&(1< 0) z.mulTo(r2,g,r); - else { var t = r; r = r2; r2 = t; } - } - return z.revert(r); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.calculateJwkThumbprint = calculateJwkThumbprint; +exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; +const digest_js_1 = __nccwpck_require__(12931); +const base64url_js_1 = __nccwpck_require__(12635); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const is_object_js_1 = __nccwpck_require__(92242); +const check = (value, description) => { + if (typeof value !== 'string' || !value) { + throw new errors_js_1.JWKInvalid(`${description} missing or invalid`); } - - // (public) this^e % m, 0 <= e < 2^32 - function bnModPowInt(e,m) { - var z; - if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); - return this.exp(e,z); +}; +async function calculateJwkThumbprint(jwk, digestAlgorithm) { + if (!(0, is_object_js_1.default)(jwk)) { + throw new TypeError('JWK must be an object'); } - - // protected - BigInteger.prototype.copyTo = bnpCopyTo; - BigInteger.prototype.fromInt = bnpFromInt; - BigInteger.prototype.fromString = bnpFromString; - BigInteger.prototype.clamp = bnpClamp; - BigInteger.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger.prototype.drShiftTo = bnpDRShiftTo; - BigInteger.prototype.lShiftTo = bnpLShiftTo; - BigInteger.prototype.rShiftTo = bnpRShiftTo; - BigInteger.prototype.subTo = bnpSubTo; - BigInteger.prototype.multiplyTo = bnpMultiplyTo; - BigInteger.prototype.squareTo = bnpSquareTo; - BigInteger.prototype.divRemTo = bnpDivRemTo; - BigInteger.prototype.invDigit = bnpInvDigit; - BigInteger.prototype.isEven = bnpIsEven; - BigInteger.prototype.exp = bnpExp; - - // public - BigInteger.prototype.toString = bnToString; - BigInteger.prototype.negate = bnNegate; - BigInteger.prototype.abs = bnAbs; - BigInteger.prototype.compareTo = bnCompareTo; - BigInteger.prototype.bitLength = bnBitLength; - BigInteger.prototype.mod = bnMod; - BigInteger.prototype.modPowInt = bnModPowInt; - - // "constants" - BigInteger.ZERO = nbv(0); - BigInteger.ONE = nbv(1); - - // Copyright (c) 2005-2009 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. - - // Extended JavaScript BN functions, required for RSA private ops. - - // Version 1.1: new BigInteger("0", 10) returns "proper" zero - // Version 1.2: square() API, isProbablePrime fix - - // (public) - function bnClone() { var r = nbi(); this.copyTo(r); return r; } - - // (public) return value as integer - function bnIntValue() { - if(this.s < 0) { - if(this.t == 1) return this[0]-this.DV; - else if(this.t == 0) return -1; - } - else if(this.t == 1) return this[0]; - else if(this.t == 0) return 0; - // assumes 16 < DB < 32 - return ((this[1]&((1<<(32-this.DB))-1))<>24; } - // (public) return value as short (assumes DB>=16) - function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } +/***/ }), - // (protected) return x s.t. r^x < DV - function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } +/***/ 25275: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // (public) 0 if this == 0, 1 if this > 0 - function bnSigNum() { - if(this.s < 0) return -1; - else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; - else return 1; - } +"use strict"; - // (protected) convert to radix string - function bnpToRadix(b) { - if(b == null) b = 10; - if(this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b,cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d,y,z); - while(y.signum() > 0) { - r = (a+z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d,y,z); - } - return z.intValue().toString(b) + r; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createLocalJWKSet = createLocalJWKSet; +const import_js_1 = __nccwpck_require__(45647); +const errors_js_1 = __nccwpck_require__(15974); +const is_object_js_1 = __nccwpck_require__(92242); +function getKtyFromAlg(alg) { + switch (typeof alg === 'string' && alg.slice(0, 2)) { + case 'RS': + case 'PS': + return 'RSA'; + case 'ES': + return 'EC'; + case 'Ed': + return 'OKP'; + default: + throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); } - - // (protected) convert from radix string - function bnpFromRadix(s,b) { - this.fromInt(0); - if(b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b,cs), mi = false, j = 0, w = 0; - for(var i = 0; i < s.length; ++i) { - var x = intAt(s,i); - if(x < 0) { - if(s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b*w+x; - if(++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w,0); - j = 0; - w = 0; - } - } - if(j > 0) { - this.dMultiply(Math.pow(b,j)); - this.dAddOffset(w,0); - } - if(mi) BigInteger.ZERO.subTo(this,this); +} +function isJWKSLike(jwks) { + return (jwks && + typeof jwks === 'object' && + Array.isArray(jwks.keys) && + jwks.keys.every(isJWKLike)); +} +function isJWKLike(key) { + return (0, is_object_js_1.default)(key); +} +function clone(obj) { + if (typeof structuredClone === 'function') { + return structuredClone(obj); } - - // (protected) alternate constructor - function bnpFromNumber(a,b,c) { - if("number" == typeof b) { - // new BigInteger(int,int,RNG) - if(a < 2) this.fromInt(1); - else { - this.fromNumber(a,c); - if(!this.testBit(a-1)) // force MSB set - this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); - if(this.isEven()) this.dAddOffset(1,0); // force odd - while(!this.isProbablePrime(b)) { - this.dAddOffset(2,0); - if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); - } + return JSON.parse(JSON.stringify(obj)); +} +class LocalJWKSet { + _jwks; + _cached = new WeakMap(); + constructor(jwks) { + if (!isJWKSLike(jwks)) { + throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); } - } - else { - // new BigInteger(int,RNG) - var x = new Array(), t = a&7; - x.length = (a>>3)+1; - b.nextBytes(x); - if(t > 0) x[0] &= ((1< 0) { - if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) - r[k++] = d|(this.s<<(this.DB-p)); - while(i >= 0) { - if(p < 8) { - d = (this[i]&((1<>(p+=this.DB-8); - } - else { - d = (this[i]>>(p-=8))&0xff; - if(p <= 0) { p += this.DB; --i; } - } - if((d&0x80) != 0) d |= -256; - if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; - if(k > 0 || d != this.s) r[k++] = d; + async getKey(protectedHeader, token) { + const { alg, kid } = { ...protectedHeader, ...token?.header }; + const kty = getKtyFromAlg(alg); + const candidates = this._jwks.keys.filter((jwk) => { + let candidate = kty === jwk.kty; + if (candidate && typeof kid === 'string') { + candidate = kid === jwk.kid; + } + if (candidate && typeof jwk.alg === 'string') { + candidate = alg === jwk.alg; + } + if (candidate && typeof jwk.use === 'string') { + candidate = jwk.use === 'sig'; + } + if (candidate && Array.isArray(jwk.key_ops)) { + candidate = jwk.key_ops.includes('verify'); + } + if (candidate && alg === 'EdDSA') { + candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; + } + if (candidate) { + switch (alg) { + case 'ES256': + candidate = jwk.crv === 'P-256'; + break; + case 'ES256K': + candidate = jwk.crv === 'secp256k1'; + break; + case 'ES384': + candidate = jwk.crv === 'P-384'; + break; + case 'ES512': + candidate = jwk.crv === 'P-521'; + break; + } + } + return candidate; + }); + const { 0: jwk, length } = candidates; + if (length === 0) { + throw new errors_js_1.JWKSNoMatchingKey(); } - } - return r; + if (length !== 1) { + const error = new errors_js_1.JWKSMultipleMatchingKeys(); + const { _cached } = this; + error[Symbol.asyncIterator] = async function* () { + for (const jwk of candidates) { + try { + yield await importWithAlgCache(_cached, jwk, alg); + } + catch { } + } + }; + throw error; + } + return importWithAlgCache(this._cached, jwk, alg); } - - function bnEquals(a) { return(this.compareTo(a)==0); } - function bnMin(a) { return(this.compareTo(a)<0)?this:a; } - function bnMax(a) { return(this.compareTo(a)>0)?this:a; } - - // (protected) r = this op a (bitwise) - function bnpBitwiseTo(a,op,r) { - var i, f, m = Math.min(a.t,this.t); - for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); - if(a.t < this.t) { - f = a.s&this.DM; - for(i = m; i < this.t; ++i) r[i] = op(this[i],f); - r.t = this.t; - } - else { - f = this.s&this.DM; - for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); - r.t = a.t; - } - r.s = op(this.s,a.s); - r.clamp(); +} +async function importWithAlgCache(cache, jwk, alg) { + const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk); + if (cached[alg] === undefined) { + const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg); + if (key instanceof Uint8Array || key.type !== 'public') { + throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys'); + } + cached[alg] = key; } + return cached[alg]; +} +function createLocalJWKSet(jwks) { + const set = new LocalJWKSet(jwks); + const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); + Object.defineProperties(localJWKSet, { + jwks: { + value: () => clone(set._jwks), + enumerable: true, + configurable: false, + writable: false, + }, + }); + return localJWKSet; +} - // (public) this & a - function op_and(x,y) { return x&y; } - function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } - - // (public) this | a - function op_or(x,y) { return x|y; } - function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } - - // (public) this ^ a - function op_xor(x,y) { return x^y; } - function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - - // (public) this & ~a - function op_andnot(x,y) { return x&~y; } - function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } - - // (public) ~this - function bnNot() { - var r = nbi(); - for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - // (public) this << n - function bnShiftLeft(n) { - var r = nbi(); - if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); - return r; - } +/***/ }), - // (public) this >> n - function bnShiftRight(n) { - var r = nbi(); - if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); - return r; - } +/***/ 69260: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // return index of lowest 1-bit in x, x < 2^31 - function lbit(x) { - if(x == 0) return -1; - var r = 0; - if((x&0xffff) == 0) { x >>= 16; r += 16; } - if((x&0xff) == 0) { x >>= 8; r += 8; } - if((x&0xf) == 0) { x >>= 4; r += 4; } - if((x&3) == 0) { x >>= 2; r += 2; } - if((x&1) == 0) ++r; - return r; - } +"use strict"; - // (public) returns index of lowest 1-bit (or -1 if none) - function bnGetLowestSetBit() { - for(var i = 0; i < this.t; ++i) - if(this[i] != 0) return i*this.DB+lbit(this[i]); - if(this.s < 0) return this.t*this.DB; - return -1; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.experimental_jwksCache = exports.jwksCache = void 0; +exports.createRemoteJWKSet = createRemoteJWKSet; +const fetch_jwks_js_1 = __nccwpck_require__(20311); +const errors_js_1 = __nccwpck_require__(15974); +const local_js_1 = __nccwpck_require__(25275); +const is_object_js_1 = __nccwpck_require__(92242); +function isCloudflareWorkers() { + return (typeof WebSocketPair !== 'undefined' || + (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || + (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); +} +let USER_AGENT; +if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) { + const NAME = 'jose'; + const VERSION = 'v5.9.6'; + USER_AGENT = `${NAME}/${VERSION}`; +} +exports.jwksCache = Symbol(); +function isFreshJwksCache(input, cacheMaxAge) { + if (typeof input !== 'object' || input === null) { + return false; } - - // return number of 1 bits in x - function cbit(x) { - var r = 0; - while(x != 0) { x &= x-1; ++r; } - return r; + if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) { + return false; } - - // (public) return number of set bits - function bnBitCount() { - var r = 0, x = this.s&this.DM; - for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); - return r; + if (!('jwks' in input) || + !(0, is_object_js_1.default)(input.jwks) || + !Array.isArray(input.jwks.keys) || + !Array.prototype.every.call(input.jwks.keys, is_object_js_1.default)) { + return false; } - - // (public) true iff nth bit is set - function bnTestBit(n) { - var j = Math.floor(n/this.DB); - if(j >= this.t) return(this.s!=0); - return((this[j]&(1<<(n%this.DB)))!=0); + return true; +} +class RemoteJWKSet { + _url; + _timeoutDuration; + _cooldownDuration; + _cacheMaxAge; + _jwksTimestamp; + _pendingFetch; + _options; + _local; + _cache; + constructor(url, options) { + if (!(url instanceof URL)) { + throw new TypeError('url must be an instance of URL'); + } + this._url = new URL(url.href); + this._options = { agent: options?.agent, headers: options?.headers }; + this._timeoutDuration = + typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000; + this._cooldownDuration = + typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000; + this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000; + if (options?.[exports.jwksCache] !== undefined) { + this._cache = options?.[exports.jwksCache]; + if (isFreshJwksCache(options?.[exports.jwksCache], this._cacheMaxAge)) { + this._jwksTimestamp = this._cache.uat; + this._local = (0, local_js_1.createLocalJWKSet)(this._cache.jwks); + } + } } - - // (protected) this op (1<>= this.DB; - } - if(a.t < this.t) { - c += a.s; - while(i < this.t) { - c += this[i]; - r[i++] = c&this.DM; - c >>= this.DB; + fresh() { + return typeof this._jwksTimestamp === 'number' + ? Date.now() < this._jwksTimestamp + this._cacheMaxAge + : false; + } + async getKey(protectedHeader, token) { + if (!this._local || !this.fresh()) { + await this.reload(); } - c += this.s; - } - else { - c += this.s; - while(i < a.t) { - c += a[i]; - r[i++] = c&this.DM; - c >>= this.DB; + try { + return await this._local(protectedHeader, token); + } + catch (err) { + if (err instanceof errors_js_1.JWKSNoMatchingKey) { + if (this.coolingDown() === false) { + await this.reload(); + return this._local(protectedHeader, token); + } + } + throw err; } - c += a.s; - } - r.s = (c<0)?-1:0; - if(c > 0) r[i++] = c; - else if(c < -1) r[i++] = this.DV+c; - r.t = i; - r.clamp(); } + async reload() { + if (this._pendingFetch && isCloudflareWorkers()) { + this._pendingFetch = undefined; + } + const headers = new Headers(this._options.headers); + if (USER_AGENT && !headers.has('User-Agent')) { + headers.set('User-Agent', USER_AGENT); + this._options.headers = Object.fromEntries(headers.entries()); + } + this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options) + .then((json) => { + this._local = (0, local_js_1.createLocalJWKSet)(json); + if (this._cache) { + this._cache.uat = Date.now(); + this._cache.jwks = json; + } + this._jwksTimestamp = Date.now(); + this._pendingFetch = undefined; + }) + .catch((err) => { + this._pendingFetch = undefined; + throw err; + }); + await this._pendingFetch; + } +} +function createRemoteJWKSet(url, options) { + const set = new RemoteJWKSet(url, options); + const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token); + Object.defineProperties(remoteJWKSet, { + coolingDown: { + get: () => set.coolingDown(), + enumerable: true, + configurable: false, + }, + fresh: { + get: () => set.fresh(), + enumerable: true, + configurable: false, + }, + reload: { + value: () => set.reload(), + enumerable: true, + configurable: false, + writable: false, + }, + reloading: { + get: () => !!set._pendingFetch, + enumerable: true, + configurable: false, + }, + jwks: { + value: () => set._local?.jwks(), + enumerable: true, + configurable: false, + writable: false, + }, + }); + return remoteJWKSet; +} +exports.experimental_jwksCache = exports.jwksCache; - // (public) this + a - function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } - - // (public) this - a - function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } - - // (public) this * a - function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } - // (public) this^2 - function bnSquare() { var r = nbi(); this.squareTo(r); return r; } +/***/ }), - // (public) this / a - function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } +/***/ 21760: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // (public) this % a - function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } +"use strict"; - // (public) [this/a,this%a] - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a,q,r); - return new Array(q,r); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CompactSign = void 0; +const sign_js_1 = __nccwpck_require__(86170); +class CompactSign { + _flattened; + constructor(payload) { + this._flattened = new sign_js_1.FlattenedSign(payload); } - - // (protected) this *= n, this >= 0, 1 < n < DV - function bnpDMultiply(n) { - this[this.t] = this.am(0,n-1,this,0,0,this.t); - ++this.t; - this.clamp(); + setProtectedHeader(protectedHeader) { + this._flattened.setProtectedHeader(protectedHeader); + return this; } - - // (protected) this += n << w words, this >= 0 - function bnpDAddOffset(n,w) { - if(n == 0) return; - while(this.t <= w) this[this.t++] = 0; - this[w] += n; - while(this[w] >= this.DV) { - this[w] -= this.DV; - if(++w >= this.t) this[this.t++] = 0; - ++this[w]; - } + async sign(key, options) { + const jws = await this._flattened.sign(key, options); + if (jws.payload === undefined) { + throw new TypeError('use the flattened module for creating JWS with b64: false'); + } + return `${jws.protected}.${jws.payload}.${jws.signature}`; } +} +exports.CompactSign = CompactSign; - // A "null" reducer - function NullExp() {} - function nNop(x) { return x; } - function nMulTo(x,y,r) { x.multiplyTo(y,r); } - function nSqrTo(x,r) { x.squareTo(r); } - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; +/***/ }), - // (public) this^e - function bnPow(e) { return this.exp(e,new NullExp()); } +/***/ 94212: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // (protected) r = lower n words of "this * a", a.t <= n - // "this" should be the larger one if appropriate. - function bnpMultiplyLowerTo(a,n,r) { - var i = Math.min(this.t+a.t,n); - r.s = 0; // assumes a,this >= 0 - r.t = i; - while(i > 0) r[--i] = 0; - var j; - for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); - for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); - r.clamp(); - } +"use strict"; - // (protected) r = "this * a" without lower n words, n > 0 - // "this" should be the larger one if appropriate. - function bnpMultiplyUpperTo(a,n,r) { - --n; - var i = r.t = this.t+a.t-n; - r.s = 0; // assumes a,this >= 0 - while(--i >= 0) r[i] = 0; - for(i = Math.max(n-this.t,0); i < a.t; ++i) - r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); - r.clamp(); - r.drShiftTo(1,r); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.compactVerify = compactVerify; +const verify_js_1 = __nccwpck_require__(56358); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +async function compactVerify(jws, key, options) { + if (jws instanceof Uint8Array) { + jws = buffer_utils_js_1.decoder.decode(jws); } - - // Barrett modular reduction - function Barrett(m) { - // setup Barrett - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger.ONE.dlShiftTo(2*m.t,this.r2); - this.mu = this.r2.divide(m); - this.m = m; + if (typeof jws !== 'string') { + throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array'); } - - function barrettConvert(x) { - if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); - else if(x.compareTo(this.m) < 0) return x; - else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } + const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); + if (length !== 3) { + throw new errors_js_1.JWSInvalid('Invalid Compact JWS'); } - - function barrettRevert(x) { return x; } - - // x = x mod m (HAC 14.42) - function barrettReduce(x) { - x.drShiftTo(this.m.t-1,this.r2); - if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } - this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); - this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); - while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); - x.subTo(this.r2,x); - while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); + const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options); + const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; } + return result; +} - // r = x^2 mod m; x != r - function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - // r = x*y mod m; x,y != r - function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +/***/ }), - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; +/***/ 86170: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // (public) this^e % m (HAC 14.85) - function bnModPow(e,m) { - var i = e.bitLength(), k, r = nbv(1), z; - if(i <= 0) return r; - else if(i < 18) k = 1; - else if(i < 48) k = 3; - else if(i < 144) k = 4; - else if(i < 768) k = 5; - else k = 6; - if(i < 8) - z = new Classic(m); - else if(m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); +"use strict"; - // precomputation - var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { - var g2 = nbi(); - z.sqrTo(g[1],g2); - while(n <= km) { - g[n] = nbi(); - z.mulTo(g2,g[n-2],g[n]); - n += 2; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FlattenedSign = void 0; +const base64url_js_1 = __nccwpck_require__(12635); +const sign_js_1 = __nccwpck_require__(26966); +const is_disjoint_js_1 = __nccwpck_require__(21853); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const check_key_type_js_1 = __nccwpck_require__(29555); +const validate_crit_js_1 = __nccwpck_require__(15595); +class FlattenedSign { + _payload; + _protectedHeader; + _unprotectedHeader; + constructor(payload) { + if (!(payload instanceof Uint8Array)) { + throw new TypeError('payload must be an instance of Uint8Array'); } - } - - var j = e.t-1, w, is1 = true, r2 = nbi(), t; - i = nbits(e[j])-1; - while(j >= 0) { - if(i >= k1) w = (e[j]>>(i-k1))&km; - else { - w = (e[j]&((1<<(i+1))-1))<<(k1-i); - if(j > 0) w |= e[j-1]>>(this.DB+i-k1); + this._payload = payload; + } + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); } - - n = k; - while((w&1) == 0) { w >>= 1; --n; } - if((i -= n) < 0) { i += this.DB; --j; } - if(is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r); - is1 = false; + this._protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this._unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); } - else { - while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } - if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } - z.mulTo(r2,g[w],r); + this._unprotectedHeader = unprotectedHeader; + return this; + } + async sign(key, options) { + if (!this._protectedHeader && !this._unprotectedHeader) { + throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); } - - while(j >= 0 && (e[j]&(1< 0) { - x.rShiftTo(g,x); - y.rShiftTo(g,y); - } - while(x.signum() > 0) { - if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); - if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); - if(x.compareTo(y) >= 0) { - x.subTo(y,x); - x.rShiftTo(1,x); + const joseHeader = { + ...this._protectedHeader, + ...this._unprotectedHeader, + }; + const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = this._protectedHeader.b64; + if (typeof b64 !== 'boolean') { + throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); + } + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'sign'); + let payload = this._payload; + if (b64) { + payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload)); + } + let protectedHeader; + if (this._protectedHeader) { + protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); } else { - y.subTo(x,y); - y.rShiftTo(1,y); + protectedHeader = buffer_utils_js_1.encoder.encode(''); } - } - if(g > 0) y.lShiftTo(g,y); - return y; + const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload); + const signature = await (0, sign_js_1.default)(alg, key, data); + const jws = { + signature: (0, base64url_js_1.encode)(signature), + payload: '', + }; + if (b64) { + jws.payload = buffer_utils_js_1.decoder.decode(payload); + } + if (this._unprotectedHeader) { + jws.header = this._unprotectedHeader; + } + if (this._protectedHeader) { + jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader); + } + return jws; } +} +exports.FlattenedSign = FlattenedSign; - // (protected) this % n, n < 2^26 - function bnpModInt(n) { - if(n <= 0) return 0; - var d = this.DV%n, r = (this.s<0)?n-1:0; - if(this.t > 0) - if(d == 0) r = this[0]%n; - else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; - return r; - } - // (public) 1/this % m (HAC 14.61) - function bnModInverse(m) { - var ac = m.isEven(); - if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while(u.signum() != 0) { - while(u.isEven()) { - u.rShiftTo(1,u); - if(ac) { - if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } - a.rShiftTo(1,a); - } - else if(!b.isEven()) b.subTo(m,b); - b.rShiftTo(1,b); +/***/ }), + +/***/ 56358: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.flattenedVerify = flattenedVerify; +const base64url_js_1 = __nccwpck_require__(12635); +const verify_js_1 = __nccwpck_require__(11242); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const is_disjoint_js_1 = __nccwpck_require__(21853); +const is_object_js_1 = __nccwpck_require__(92242); +const check_key_type_js_1 = __nccwpck_require__(29555); +const validate_crit_js_1 = __nccwpck_require__(15595); +const validate_algorithms_js_1 = __nccwpck_require__(19917); +const is_jwk_js_1 = __nccwpck_require__(91229); +const import_js_1 = __nccwpck_require__(45647); +async function flattenedVerify(jws, key, options) { + if (!(0, is_object_js_1.default)(jws)) { + throw new errors_js_1.JWSInvalid('Flattened JWS must be an object'); + } + if (jws.protected === undefined && jws.header === undefined) { + throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); + } + if (jws.protected !== undefined && typeof jws.protected !== 'string') { + throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type'); + } + if (jws.payload === undefined) { + throw new errors_js_1.JWSInvalid('JWS Payload missing'); + } + if (typeof jws.signature !== 'string') { + throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type'); + } + if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) { + throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type'); + } + let parsedProt = {}; + if (jws.protected) { + try { + const protectedHeader = (0, base64url_js_1.decode)(jws.protected); + parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); } - while(v.isEven()) { - v.rShiftTo(1,v); - if(ac) { - if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } - c.rShiftTo(1,c); - } - else if(!d.isEven()) d.subTo(m,d); - d.rShiftTo(1,d); + catch { + throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid'); } - if(u.compareTo(v) >= 0) { - u.subTo(v,u); - if(ac) a.subTo(c,a); - b.subTo(d,b); + } + if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) { + throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); + } + const joseHeader = { + ...parsedProt, + ...jws.header, + }; + const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader); + let b64 = true; + if (extensions.has('b64')) { + b64 = parsedProt.b64; + if (typeof b64 !== 'boolean') { + throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } - else { - v.subTo(u,v); - if(ac) c.subTo(a,c); - d.subTo(b,d); + } + const { alg } = joseHeader; + if (typeof alg !== 'string' || !alg) { + throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); + } + const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms); + if (algorithms && !algorithms.has(alg)) { + throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); + } + if (b64) { + if (typeof jws.payload !== 'string') { + throw new errors_js_1.JWSInvalid('JWS Payload must be a string'); } - } - if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; - if(d.compareTo(m) >= 0) return d.subtract(m); - if(d.signum() < 0) d.addTo(m,d); else return d; - if(d.signum() < 0) return d.add(m); else return d; } - - var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; - var lplim = (1<<26)/lowprimes[lowprimes.length-1]; - - // (public) test primality with certainty >= 1-.5^t - function bnIsProbablePrime(t) { - var i, x = this.abs(); - if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { - for(i = 0; i < lowprimes.length; ++i) - if(x[0] == lowprimes[i]) return true; - return false; - } - if(x.isEven()) return false; - i = 1; - while(i < lowprimes.length) { - var m = lowprimes[i], j = i+1; - while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while(i < j) if(m%lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); + else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { + throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); } - - // (protected) true if probably prime (HAC 4.24, Miller-Rabin) - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE); - var k = n1.getLowestSetBit(); - if(k <= 0) return false; - var r = n1.shiftRight(k); - t = (t+1)>>1; - if(t > lowprimes.length) t = lowprimes.length; - var a = nbi(); - for(var i = 0; i < t; ++i) { - //Pick bases at random, instead of starting at 2 - a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); - var y = a.modPow(r,this); - if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while(j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2,this); - if(y.compareTo(BigInteger.ONE) == 0) return false; - } - if(y.compareTo(n1) != 0) return false; + let resolvedKey = false; + if (typeof key === 'function') { + key = await key(parsedProt, jws); + resolvedKey = true; + (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify'); + if ((0, is_jwk_js_1.isJWK)(key)) { + key = await (0, import_js_1.importJWK)(key, alg); } - } - return true; } + else { + (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify'); + } + const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload); + let signature; + try { + signature = (0, base64url_js_1.decode)(jws.signature); + } + catch { + throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature'); + } + const verified = await (0, verify_js_1.default)(alg, key, signature, data); + if (!verified) { + throw new errors_js_1.JWSSignatureVerificationFailed(); + } + let payload; + if (b64) { + try { + payload = (0, base64url_js_1.decode)(jws.payload); + } + catch { + throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload'); + } + } + else if (typeof jws.payload === 'string') { + payload = buffer_utils_js_1.encoder.encode(jws.payload); + } + else { + payload = jws.payload; + } + const result = { payload }; + if (jws.protected !== undefined) { + result.protectedHeader = parsedProt; + } + if (jws.header !== undefined) { + result.unprotectedHeader = jws.header; + } + if (resolvedKey) { + return { ...result, key }; + } + return result; +} - // protected - BigInteger.prototype.chunkSize = bnpChunkSize; - BigInteger.prototype.toRadix = bnpToRadix; - BigInteger.prototype.fromRadix = bnpFromRadix; - BigInteger.prototype.fromNumber = bnpFromNumber; - BigInteger.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger.prototype.changeBit = bnpChangeBit; - BigInteger.prototype.addTo = bnpAddTo; - BigInteger.prototype.dMultiply = bnpDMultiply; - BigInteger.prototype.dAddOffset = bnpDAddOffset; - BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger.prototype.modInt = bnpModInt; - BigInteger.prototype.millerRabin = bnpMillerRabin; - // public - BigInteger.prototype.clone = bnClone; - BigInteger.prototype.intValue = bnIntValue; - BigInteger.prototype.byteValue = bnByteValue; - BigInteger.prototype.shortValue = bnShortValue; - BigInteger.prototype.signum = bnSigNum; - BigInteger.prototype.toByteArray = bnToByteArray; - BigInteger.prototype.equals = bnEquals; - BigInteger.prototype.min = bnMin; - BigInteger.prototype.max = bnMax; - BigInteger.prototype.and = bnAnd; - BigInteger.prototype.or = bnOr; - BigInteger.prototype.xor = bnXor; - BigInteger.prototype.andNot = bnAndNot; - BigInteger.prototype.not = bnNot; - BigInteger.prototype.shiftLeft = bnShiftLeft; - BigInteger.prototype.shiftRight = bnShiftRight; - BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger.prototype.bitCount = bnBitCount; - BigInteger.prototype.testBit = bnTestBit; - BigInteger.prototype.setBit = bnSetBit; - BigInteger.prototype.clearBit = bnClearBit; - BigInteger.prototype.flipBit = bnFlipBit; - BigInteger.prototype.add = bnAdd; - BigInteger.prototype.subtract = bnSubtract; - BigInteger.prototype.multiply = bnMultiply; - BigInteger.prototype.divide = bnDivide; - BigInteger.prototype.remainder = bnRemainder; - BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger.prototype.modPow = bnModPow; - BigInteger.prototype.modInverse = bnModInverse; - BigInteger.prototype.pow = bnPow; - BigInteger.prototype.gcd = bnGCD; - BigInteger.prototype.isProbablePrime = bnIsProbablePrime; +/***/ }), - // JSBN-specific extension - BigInteger.prototype.square = bnSquare; +/***/ 50443: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Expose the Barrett function - BigInteger.prototype.Barrett = Barrett +"use strict"; - // BigInteger interfaces not implemented in jsbn: +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GeneralSign = void 0; +const sign_js_1 = __nccwpck_require__(86170); +const errors_js_1 = __nccwpck_require__(15974); +class IndividualSignature { + parent; + protectedHeader; + unprotectedHeader; + options; + key; + constructor(sig, key, options) { + this.parent = sig; + this.key = key; + this.options = options; + } + setProtectedHeader(protectedHeader) { + if (this.protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this.protectedHeader = protectedHeader; + return this; + } + setUnprotectedHeader(unprotectedHeader) { + if (this.unprotectedHeader) { + throw new TypeError('setUnprotectedHeader can only be called once'); + } + this.unprotectedHeader = unprotectedHeader; + return this; + } + addSignature(...args) { + return this.parent.addSignature(...args); + } + sign(...args) { + return this.parent.sign(...args); + } + done() { + return this.parent; + } +} +class GeneralSign { + _payload; + _signatures = []; + constructor(payload) { + this._payload = payload; + } + addSignature(key, options) { + const signature = new IndividualSignature(this, key, options); + this._signatures.push(signature); + return signature; + } + async sign() { + if (!this._signatures.length) { + throw new errors_js_1.JWSInvalid('at least one signature must be added'); + } + const jws = { + signatures: [], + payload: '', + }; + for (let i = 0; i < this._signatures.length; i++) { + const signature = this._signatures[i]; + const flattened = new sign_js_1.FlattenedSign(this._payload); + flattened.setProtectedHeader(signature.protectedHeader); + flattened.setUnprotectedHeader(signature.unprotectedHeader); + const { payload, ...rest } = await flattened.sign(signature.key, signature.options); + if (i === 0) { + jws.payload = payload; + } + else if (jws.payload !== payload) { + throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)'); + } + jws.signatures.push(rest); + } + return jws; + } +} +exports.GeneralSign = GeneralSign; - // BigInteger(int signum, byte[] magnitude) - // double doubleValue() - // float floatValue() - // int hashCode() - // long longValue() - // static BigInteger valueOf(long val) - // Random number generator - requires a PRNG backend, e.g. prng4.js +/***/ }), - // For best results, put code like - // - // in your main HTML document. +/***/ 88323: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var rng_state; - var rng_pool; - var rng_pptr; +"use strict"; - // Mix in a 32-bit integer into the pool - function rng_seed_int(x) { - rng_pool[rng_pptr++] ^= x & 255; - rng_pool[rng_pptr++] ^= (x >> 8) & 255; - rng_pool[rng_pptr++] ^= (x >> 16) & 255; - rng_pool[rng_pptr++] ^= (x >> 24) & 255; - if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generalVerify = generalVerify; +const verify_js_1 = __nccwpck_require__(56358); +const errors_js_1 = __nccwpck_require__(15974); +const is_object_js_1 = __nccwpck_require__(92242); +async function generalVerify(jws, key, options) { + if (!(0, is_object_js_1.default)(jws)) { + throw new errors_js_1.JWSInvalid('General JWS must be an object'); } - - // Mix in the current time (w/milliseconds) into the pool - function rng_seed_time() { - rng_seed_int(new Date().getTime()); + if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) { + throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type'); } - - // Initialize the pool with junk if needed. - if(rng_pool == null) { - rng_pool = new Array(); - rng_pptr = 0; - var t; - if(typeof window !== "undefined" && window.crypto) { - if (window.crypto.getRandomValues) { - // Use webcrypto if available - var ua = new Uint8Array(32); - window.crypto.getRandomValues(ua); - for(t = 0; t < 32; ++t) - rng_pool[rng_pptr++] = ua[t]; + for (const signature of jws.signatures) { + try { + return await (0, verify_js_1.flattenedVerify)({ + header: signature.header, + payload: jws.payload, + protected: signature.protected, + signature: signature.signature, + }, key, options); } - else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { - // Extract entropy (256 bits) from NS4 RNG if available - var z = window.crypto.random(32); - for(t = 0; t < z.length; ++t) - rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; + catch { } - } - while(rng_pptr < rng_psize) { // extract some randomness from Math.random() - t = Math.floor(65536 * Math.random()); - rng_pool[rng_pptr++] = t >>> 8; - rng_pool[rng_pptr++] = t & 255; - } - rng_pptr = 0; - rng_seed_time(); - //rng_seed_int(window.screenX); - //rng_seed_int(window.screenY); - } - - function rng_get_byte() { - if(rng_state == null) { - rng_seed_time(); - rng_state = prng_newstate(); - rng_state.init(rng_pool); - for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) - rng_pool[rng_pptr] = 0; - rng_pptr = 0; - //rng_pool = null; - } - // TODO: allow reseeding after first request - return rng_state.next(); } + throw new errors_js_1.JWSSignatureVerificationFailed(); +} - function rng_get_bytes(ba) { - var i; - for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); - } - function SecureRandom() {} +/***/ }), - SecureRandom.prototype.nextBytes = rng_get_bytes; +/***/ 95339: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // prng4.js - uses Arcfour as a PRNG +"use strict"; - function Arcfour() { - this.i = 0; - this.j = 0; - this.S = new Array(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.jwtDecrypt = jwtDecrypt; +const decrypt_js_1 = __nccwpck_require__(14298); +const jwt_claims_set_js_1 = __nccwpck_require__(13354); +const errors_js_1 = __nccwpck_require__(15974); +async function jwtDecrypt(jwt, key, options) { + const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options); + const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options); + const { protectedHeader } = decrypted; + if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { + throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch'); } - - // Initialize arcfour context from key, an array of ints, each from [0..255] - function ARC4init(key) { - var i, j, t; - for(i = 0; i < 256; ++i) - this.S[i] = i; - j = 0; - for(i = 0; i < 256; ++i) { - j = (j + this.S[i] + key[i % key.length]) & 255; - t = this.S[i]; - this.S[i] = this.S[j]; - this.S[j] = t; - } - this.i = 0; - this.j = 0; + if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { + throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch'); + } + if (protectedHeader.aud !== undefined && + JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { + throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch'); } - - function ARC4next() { - var t; - this.i = (this.i + 1) & 255; - this.j = (this.j + this.S[this.i]) & 255; - t = this.S[this.i]; - this.S[this.i] = this.S[this.j]; - this.S[this.j] = t; - return this.S[(t + this.S[this.i]) & 255]; + const result = { payload, protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: decrypted.key }; } + return result; +} - Arcfour.prototype.init = ARC4init; - Arcfour.prototype.next = ARC4next; - // Plug in your RNG constructor here - function prng_newstate() { - return new Arcfour(); - } +/***/ }), - // Pool size must be a multiple of 4 and greater than 32. - // An array of bytes the size of the pool will be passed to init() - var rng_psize = 256; +/***/ 38375: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (true) { - exports = module.exports = { - default: BigInteger, - BigInteger: BigInteger, - SecureRandom: SecureRandom, - }; - } else {} +"use strict"; -}).call(this); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.EncryptJWT = void 0; +const encrypt_js_1 = __nccwpck_require__(4434); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const produce_js_1 = __nccwpck_require__(37318); +class EncryptJWT extends produce_js_1.ProduceJWT { + _cek; + _iv; + _keyManagementParameters; + _protectedHeader; + _replicateIssuerAsHeader; + _replicateSubjectAsHeader; + _replicateAudienceAsHeader; + setProtectedHeader(protectedHeader) { + if (this._protectedHeader) { + throw new TypeError('setProtectedHeader can only be called once'); + } + this._protectedHeader = protectedHeader; + return this; + } + setKeyManagementParameters(parameters) { + if (this._keyManagementParameters) { + throw new TypeError('setKeyManagementParameters can only be called once'); + } + this._keyManagementParameters = parameters; + return this; + } + setContentEncryptionKey(cek) { + if (this._cek) { + throw new TypeError('setContentEncryptionKey can only be called once'); + } + this._cek = cek; + return this; + } + setInitializationVector(iv) { + if (this._iv) { + throw new TypeError('setInitializationVector can only be called once'); + } + this._iv = iv; + return this; + } + replicateIssuerAsHeader() { + this._replicateIssuerAsHeader = true; + return this; + } + replicateSubjectAsHeader() { + this._replicateSubjectAsHeader = true; + return this; + } + replicateAudienceAsHeader() { + this._replicateAudienceAsHeader = true; + return this; + } + async encrypt(key, options) { + const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); + if (this._replicateIssuerAsHeader) { + this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; + } + if (this._replicateSubjectAsHeader) { + this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; + } + if (this._replicateAudienceAsHeader) { + this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; + } + enc.setProtectedHeader(this._protectedHeader); + if (this._iv) { + enc.setInitializationVector(this._iv); + } + if (this._cek) { + enc.setContentEncryptionKey(this._cek); + } + if (this._keyManagementParameters) { + enc.setKeyManagementParameters(this._keyManagementParameters); + } + return enc.encrypt(key, options); + } +} +exports.EncryptJWT = EncryptJWT; /***/ }), -/***/ 85743: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { Request, Response } = __nccwpck_require__(88483) -const { Minipass } = __nccwpck_require__(78275) -const MinipassFlush = __nccwpck_require__(37633) -const cacache = __nccwpck_require__(85742) -const url = __nccwpck_require__(87016) - -const CachingMinipassPipeline = __nccwpck_require__(22314) -const CachePolicy = __nccwpck_require__(15281) -const cacheKey = __nccwpck_require__(45808) -const remote = __nccwpck_require__(20766) +/***/ 37318: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) +"use strict"; -// allow list for request headers that will be written to the cache index -// note: we will also store any request headers -// that are named in a response's vary header -const KEEP_REQUEST_HEADERS = [ - 'accept-charset', - 'accept-encoding', - 'accept-language', - 'accept', - 'cache-control', -] +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProduceJWT = void 0; +const epoch_js_1 = __nccwpck_require__(40485); +const is_object_js_1 = __nccwpck_require__(92242); +const secs_js_1 = __nccwpck_require__(40556); +function validateInput(label, input) { + if (!Number.isFinite(input)) { + throw new TypeError(`Invalid ${label} input`); + } + return input; +} +class ProduceJWT { + _payload; + constructor(payload = {}) { + if (!(0, is_object_js_1.default)(payload)) { + throw new TypeError('JWT Claims Set MUST be an object'); + } + this._payload = payload; + } + setIssuer(issuer) { + this._payload = { ...this._payload, iss: issuer }; + return this; + } + setSubject(subject) { + this._payload = { ...this._payload, sub: subject }; + return this; + } + setAudience(audience) { + this._payload = { ...this._payload, aud: audience }; + return this; + } + setJti(jwtId) { + this._payload = { ...this._payload, jti: jwtId }; + return this; + } + setNotBefore(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) }; + } + else if (input instanceof Date) { + this._payload = { ...this._payload, nbf: validateInput('setNotBefore', (0, epoch_js_1.default)(input)) }; + } + else { + this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; + } + return this; + } + setExpirationTime(input) { + if (typeof input === 'number') { + this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) }; + } + else if (input instanceof Date) { + this._payload = { ...this._payload, exp: validateInput('setExpirationTime', (0, epoch_js_1.default)(input)) }; + } + else { + this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; + } + return this; + } + setIssuedAt(input) { + if (typeof input === 'undefined') { + this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) }; + } + else if (input instanceof Date) { + this._payload = { ...this._payload, iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(input)) }; + } + else if (typeof input === 'string') { + this._payload = { + ...this._payload, + iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input)), + }; + } + else { + this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) }; + } + return this; + } +} +exports.ProduceJWT = ProduceJWT; -// allow list for response headers that will be written to the cache index -// note: we must not store the real response's age header, or when we load -// a cache policy based on the metadata it will think the cached response -// is always stale -const KEEP_RESPONSE_HEADERS = [ - 'cache-control', - 'content-encoding', - 'content-language', - 'content-type', - 'date', - 'etag', - 'expires', - 'last-modified', - 'link', - 'location', - 'pragma', - 'vary', -] -// return an object containing all metadata to be written to the index -const getMetadata = (request, response, options) => { - const metadata = { - time: Date.now(), - url: request.url, - reqHeaders: {}, - resHeaders: {}, +/***/ }), - // options on which we must match the request and vary the response - options: { - compress: options.compress != null ? options.compress : request.compress, - }, - } +/***/ 22713: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // only save the status if it's not a 200 or 304 - if (response.status !== 200 && response.status !== 304) { - metadata.status = response.status - } +"use strict"; - for (const name of KEEP_REQUEST_HEADERS) { - if (request.headers.has(name)) { - metadata.reqHeaders[name] = request.headers.get(name) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SignJWT = void 0; +const sign_js_1 = __nccwpck_require__(21760); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const produce_js_1 = __nccwpck_require__(37318); +class SignJWT extends produce_js_1.ProduceJWT { + _protectedHeader; + setProtectedHeader(protectedHeader) { + this._protectedHeader = protectedHeader; + return this; } - } - - // if the request's host header differs from the host in the url - // we need to keep it, otherwise it's just noise and we ignore it - const host = request.headers.get('host') - const parsedUrl = new url.URL(request.url) - if (host && parsedUrl.host !== host) { - metadata.reqHeaders.host = host - } - - // if the response has a vary header, make sure - // we store the relevant request headers too - if (response.headers.has('vary')) { - const vary = response.headers.get('vary') - // a vary of "*" means every header causes a different response. - // in that scenario, we do not include any additional headers - // as the freshness check will always fail anyway and we don't - // want to bloat the cache indexes - if (vary !== '*') { - // copy any other request headers that will vary the response - const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/) - for (const name of varyHeaders) { - if (request.headers.has(name)) { - metadata.reqHeaders[name] = request.headers.get(name) + async sign(key, options) { + const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); + sig.setProtectedHeader(this._protectedHeader); + if (Array.isArray(this._protectedHeader?.crit) && + this._protectedHeader.crit.includes('b64') && + this._protectedHeader.b64 === false) { + throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); } - } + return sig.sign(key, options); } - } +} +exports.SignJWT = SignJWT; - for (const name of KEEP_RESPONSE_HEADERS) { - if (response.headers.has(name)) { - metadata.resHeaders[name] = response.headers.get(name) - } - } - for (const name of options.cacheAdditionalHeaders) { - if (response.headers.has(name)) { - metadata.resHeaders[name] = response.headers.get(name) - } - } +/***/ }), - return metadata -} +/***/ 40560: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// symbols used to hide objects that may be lazily evaluated in a getter -const _request = Symbol('request') -const _response = Symbol('response') -const _policy = Symbol('policy') +"use strict"; -class CacheEntry { - constructor ({ entry, request, response, options }) { - if (entry) { - this.key = entry.key - this.entry = entry - // previous versions of this module didn't write an explicit timestamp in - // the metadata, so fall back to the entry's timestamp. we can't use the - // entry timestamp to determine staleness because cacache will update it - // when it verifies its data - this.entry.metadata.time = this.entry.metadata.time || this.entry.time - } else { - this.key = cacheKey(request) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UnsecuredJWT = void 0; +const base64url = __nccwpck_require__(12635); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const errors_js_1 = __nccwpck_require__(15974); +const jwt_claims_set_js_1 = __nccwpck_require__(13354); +const produce_js_1 = __nccwpck_require__(37318); +class UnsecuredJWT extends produce_js_1.ProduceJWT { + encode() { + const header = base64url.encode(JSON.stringify({ alg: 'none' })); + const payload = base64url.encode(JSON.stringify(this._payload)); + return `${header}.${payload}.`; + } + static decode(jwt, options) { + if (typeof jwt !== 'string') { + throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string'); + } + const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); + if (length !== 3 || signature !== '') { + throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); + } + let header; + try { + header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader))); + if (header.alg !== 'none') + throw new Error(); + } + catch { + throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); + } + const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options); + return { payload, header }; } +} +exports.UnsecuredJWT = UnsecuredJWT; - this.options = options - // these properties are behind getters that lazily evaluate - this[_request] = request - this[_response] = response - this[_policy] = null - } +/***/ }), - // returns a CacheEntry instance that satisfies the given request - // or undefined if no existing entry satisfies - static async find (request, options) { - try { - // compacts the index and returns an array of unique entries - var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => { - const entryA = new CacheEntry({ entry: A, options }) - const entryB = new CacheEntry({ entry: B, options }) - return entryA.policy.satisfies(entryB.request) - }, { - validateEntry: (entry) => { - // clean out entries with a buggy content-encoding value - if (entry.metadata && - entry.metadata.resHeaders && - entry.metadata.resHeaders['content-encoding'] === null) { - return false - } +/***/ 35297: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // if an integrity is null, it needs to have a status specified - if (entry.integrity === null) { - return !!(entry.metadata && entry.metadata.status) - } +"use strict"; - return true - }, - }) - } catch (err) { - // if the compact request fails, ignore the error and return - return +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.jwtVerify = jwtVerify; +const verify_js_1 = __nccwpck_require__(94212); +const jwt_claims_set_js_1 = __nccwpck_require__(13354); +const errors_js_1 = __nccwpck_require__(15974); +async function jwtVerify(jwt, key, options) { + const verified = await (0, verify_js_1.compactVerify)(jwt, key, options); + if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { + throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); } - - // a cache mode of 'reload' means to behave as though we have no cache - // on the way to the network. return undefined to allow cacheFetch to - // create a brand new request no matter what. - if (options.cache === 'reload') { - return + const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options); + const result = { payload, protectedHeader: verified.protectedHeader }; + if (typeof key === 'function') { + return { ...result, key: verified.key }; } + return result; +} - // find the specific entry that satisfies the request - let match - for (const entry of matches) { - const _entry = new CacheEntry({ - entry, - options, - }) - if (_entry.policy.satisfies(request)) { - match = _entry - break - } - } +/***/ }), - return match - } +/***/ 48108: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // if the user made a PUT/POST/PATCH then we invalidate our - // cache for the same url by deleting the index entirely - static async invalidate (request, options) { - const key = cacheKey(request) - try { - await cacache.rm.entry(options.cachePath, key, { removeFully: true }) - } catch (err) { - // ignore errors - } - } +"use strict"; - get request () { - if (!this[_request]) { - this[_request] = new Request(this.entry.metadata.url, { - method: 'GET', - headers: this.entry.metadata.reqHeaders, - ...this.entry.metadata.options, - }) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.exportSPKI = exportSPKI; +exports.exportPKCS8 = exportPKCS8; +exports.exportJWK = exportJWK; +const asn1_js_1 = __nccwpck_require__(12774); +const asn1_js_2 = __nccwpck_require__(12774); +const key_to_jwk_js_1 = __nccwpck_require__(9041); +async function exportSPKI(key) { + return (0, asn1_js_1.toSPKI)(key); +} +async function exportPKCS8(key) { + return (0, asn1_js_2.toPKCS8)(key); +} +async function exportJWK(key) { + return (0, key_to_jwk_js_1.default)(key); +} - return this[_request] - } - get response () { - if (!this[_response]) { - this[_response] = new Response(null, { - url: this.entry.metadata.url, - counter: this.options.counter, - status: this.entry.metadata.status || 200, - headers: { - ...this.entry.metadata.resHeaders, - 'content-length': this.entry.size, - }, - }) - } +/***/ }), - return this[_response] - } +/***/ 87820: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get policy () { - if (!this[_policy]) { - this[_policy] = new CachePolicy({ - entry: this.entry, - request: this.request, - response: this.response, - options: this.options, - }) - } +"use strict"; - return this[_policy] - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generateKeyPair = generateKeyPair; +const generate_js_1 = __nccwpck_require__(10088); +async function generateKeyPair(alg, options) { + return (0, generate_js_1.generateKeyPair)(alg, options); +} - // wraps the response in a pipeline that stores the data - // in the cache while the user consumes it - async store (status) { - // if we got a status other than 200, 301, or 308, - // or the CachePolicy forbid storage, append the - // cache status header and return it untouched - if ( - this.request.method !== 'GET' || - ![200, 301, 308].includes(this.response.status) || - !this.policy.storable() - ) { - this.response.headers.set('x-local-cache-status', 'skip') - return this.response - } - const size = this.response.headers.get('content-length') - const cacheOpts = { - algorithms: this.options.algorithms, - metadata: getMetadata(this.request, this.response, this.options), - size, - integrity: this.options.integrity, - integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body, - } +/***/ }), - let body = null - // we only set a body if the status is a 200, redirects are - // stored as metadata only - if (this.response.status === 200) { - let cacheWriteResolve, cacheWriteReject - const cacheWritePromise = new Promise((resolve, reject) => { - cacheWriteResolve = resolve - cacheWriteReject = reject - }).catch((err) => { - body.emit('error', err) - }) +/***/ 37152: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({ - flush () { - return cacheWritePromise - }, - })) - // this is always true since if we aren't reusing the one from the remote fetch, we - // are using the one from cacache - body.hasIntegrityEmitter = true +"use strict"; - const onResume = () => { - const tee = new Minipass() - const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts) - // re-emit the integrity and size events on our new response body so they can be reused - cacheStream.on('integrity', i => body.emit('integrity', i)) - cacheStream.on('size', s => body.emit('size', s)) - // stick a flag on here so downstream users will know if they can expect integrity events - tee.pipe(cacheStream) - // TODO if the cache write fails, log a warning but return the response anyway - // eslint-disable-next-line promise/catch-or-return - cacheStream.promise().then(cacheWriteResolve, cacheWriteReject) - body.unshift(tee) - body.unshift(this.response.body) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generateSecret = generateSecret; +const generate_js_1 = __nccwpck_require__(10088); +async function generateSecret(alg, options) { + return (0, generate_js_1.generateSecret)(alg, options); +} - body.once('resume', onResume) - body.once('end', () => body.removeListener('resume', onResume)) - } else { - await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts) - } - // note: we do not set the x-local-cache-hash header because we do not know - // the hash value until after the write to the cache completes, which doesn't - // happen until after the response has been sent and it's too late to write - // the header anyway - this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) - this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) - this.response.headers.set('x-local-cache-mode', 'stream') - this.response.headers.set('x-local-cache-status', status) - this.response.headers.set('x-local-cache-time', new Date().toISOString()) - const newResponse = new Response(body, { - url: this.response.url, - status: this.response.status, - headers: this.response.headers, - counter: this.options.counter, - }) - return newResponse - } +/***/ }), - // use the cached data to create a response and return it - async respond (method, options, status) { - let response - if (method === 'HEAD' || [301, 308].includes(this.response.status)) { - // if the request is a HEAD, or the response is a redirect, - // then the metadata in the entry already includes everything - // we need to build a response - response = this.response - } else { - // we're responding with a full cached response, so create a body - // that reads from cacache and attach it to a new Response - const body = new Minipass() - const headers = { ...this.policy.responseHeaders() } +/***/ 45647: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const onResume = () => { - const cacheStream = cacache.get.stream.byDigest( - this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } - ) - cacheStream.on('error', async (err) => { - cacheStream.pause() - if (err.code === 'EINTEGRITY') { - await cacache.rm.content( - this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } - ) - } - if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') { - await CacheEntry.invalidate(this.request, this.options) - } - body.emit('error', err) - cacheStream.resume() - }) - // emit the integrity and size events based on our metadata so we're consistent - body.emit('integrity', this.entry.integrity) - body.emit('size', Number(headers['content-length'])) - cacheStream.pipe(body) - } +"use strict"; - body.once('resume', onResume) - body.once('end', () => body.removeListener('resume', onResume)) - response = new Response(body, { - url: this.entry.metadata.url, - counter: options.counter, - status: 200, - headers, - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.importSPKI = importSPKI; +exports.importX509 = importX509; +exports.importPKCS8 = importPKCS8; +exports.importJWK = importJWK; +const base64url_js_1 = __nccwpck_require__(12635); +const asn1_js_1 = __nccwpck_require__(12774); +const jwk_to_key_js_1 = __nccwpck_require__(80939); +const errors_js_1 = __nccwpck_require__(15974); +const is_object_js_1 = __nccwpck_require__(92242); +async function importSPKI(spki, alg, options) { + if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { + throw new TypeError('"spki" must be SPKI formatted string'); + } + return (0, asn1_js_1.fromSPKI)(spki, alg, options); +} +async function importX509(x509, alg, options) { + if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { + throw new TypeError('"x509" must be X.509 formatted string'); + } + return (0, asn1_js_1.fromX509)(x509, alg, options); +} +async function importPKCS8(pkcs8, alg, options) { + if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { + throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); + } + return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options); +} +async function importJWK(jwk, alg) { + if (!(0, is_object_js_1.default)(jwk)) { + throw new TypeError('JWK must be an object'); + } + alg ||= jwk.alg; + switch (jwk.kty) { + case 'oct': + if (typeof jwk.k !== 'string' || !jwk.k) { + throw new TypeError('missing "k" (Key Value) Parameter value'); + } + return (0, base64url_js_1.decode)(jwk.k); + case 'RSA': + if (jwk.oth !== undefined) { + throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); + } + case 'EC': + case 'OKP': + return (0, jwk_to_key_js_1.default)({ ...jwk, alg }); + default: + throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } +} - response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) - response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity)) - response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) - response.headers.set('x-local-cache-mode', 'stream') - response.headers.set('x-local-cache-status', status) - response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString()) - return response - } - // use the provided request along with this cache entry to - // revalidate the stored response. returns a response, either - // from the cache or from the update - async revalidate (request, options) { - const revalidateRequest = new Request(request, { - headers: this.policy.revalidationHeaders(request), - }) +/***/ }), - try { - // NOTE: be sure to remove the headers property from the - // user supplied options, since we have already defined - // them on the new request object. if they're still in the - // options then those will overwrite the ones from the policy - var response = await remote(revalidateRequest, { - ...options, - headers: undefined, - }) - } catch (err) { - // if the network fetch fails, return the stale - // cached response unless it has a cache-control - // of 'must-revalidate' - if (!this.policy.mustRevalidate) { - return this.respond(request.method, options, 'stale') - } +/***/ 95864: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - throw err - } +"use strict"; - if (this.policy.revalidated(revalidateRequest, response)) { - // we got a 304, write a new index to the cache and respond from cache - const metadata = getMetadata(request, response, options) - // 304 responses do not include headers that are specific to the response data - // since they do not include a body, so we copy values for headers that were - // in the old cache entry to the new one, if the new metadata does not already - // include that header - for (const name of KEEP_RESPONSE_HEADERS) { - if ( - !hasOwnProperty(metadata.resHeaders, name) && - hasOwnProperty(this.entry.metadata.resHeaders, name) - ) { - metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.wrap = wrap; +exports.unwrap = unwrap; +const encrypt_js_1 = __nccwpck_require__(36286); +const decrypt_js_1 = __nccwpck_require__(52806); +const base64url_js_1 = __nccwpck_require__(12635); +async function wrap(alg, key, cek, iv) { + const jweAlgorithm = alg.slice(0, 7); + const wrapped = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0)); + return { + encryptedKey: wrapped.ciphertext, + iv: (0, base64url_js_1.encode)(wrapped.iv), + tag: (0, base64url_js_1.encode)(wrapped.tag), + }; +} +async function unwrap(alg, key, encryptedKey, iv, tag) { + const jweAlgorithm = alg.slice(0, 7); + return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); +} - for (const name of options.cacheAdditionalHeaders) { - const inMeta = hasOwnProperty(metadata.resHeaders, name) - const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name) - const inPolicy = hasOwnProperty(this.policy.response.headers, name) - // if the header is in the existing entry, but it is not in the metadata - // then we need to write it to the metadata as this will refresh the on-disk cache - if (!inMeta && inEntry) { - metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] - } - // if the header is in the metadata, but not in the policy, then we need to set - // it in the policy so that it's included in the immediate response. future - // responses will load a new cache entry, so we don't need to change that - if (!inPolicy && inMeta) { - this.policy.response.headers[name] = metadata.resHeaders[name] - } - } +/***/ }), - try { - await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, { - size: this.entry.size, - metadata, - }) - } catch (err) { - // if updating the cache index fails, we ignore it and - // respond anyway - } - return this.respond(request.method, options, 'revalidated') - } +/***/ 45734: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // if we got a modified response, create a new entry based on it - const newEntry = new CacheEntry({ - request, - response, - options, - }) +"use strict"; - // respond with the new entry while writing it to the cache - return newEntry.store('updated') - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decoder = exports.encoder = void 0; +exports.concat = concat; +exports.p2s = p2s; +exports.uint64be = uint64be; +exports.uint32be = uint32be; +exports.lengthAndInput = lengthAndInput; +exports.concatKdf = concatKdf; +const digest_js_1 = __nccwpck_require__(12931); +exports.encoder = new TextEncoder(); +exports.decoder = new TextDecoder(); +const MAX_INT32 = 2 ** 32; +function concat(...buffers) { + const size = buffers.reduce((acc, { length }) => acc + length, 0); + const buf = new Uint8Array(size); + let i = 0; + for (const buffer of buffers) { + buf.set(buffer, i); + i += buffer.length; + } + return buf; +} +function p2s(alg, p2sInput) { + return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput); +} +function writeUInt32BE(buf, value, offset) { + if (value < 0 || value >= MAX_INT32) { + throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); + } + buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); +} +function uint64be(value) { + const high = Math.floor(value / MAX_INT32); + const low = value % MAX_INT32; + const buf = new Uint8Array(8); + writeUInt32BE(buf, high, 0); + writeUInt32BE(buf, low, 4); + return buf; +} +function uint32be(value) { + const buf = new Uint8Array(4); + writeUInt32BE(buf, value); + return buf; +} +function lengthAndInput(input) { + return concat(uint32be(input.length), input); +} +async function concatKdf(secret, bits, value) { + const iterations = Math.ceil((bits >> 3) / 32); + const res = new Uint8Array(iterations * 32); + for (let iter = 0; iter < iterations; iter++) { + const buf = new Uint8Array(4 + secret.length + value.length); + buf.set(uint32be(iter + 1)); + buf.set(secret, 4); + buf.set(value, 4 + secret.length); + res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32); + } + return res.slice(0, bits >> 3); } - -module.exports = CacheEntry /***/ }), -/***/ 59456: -/***/ ((module) => { +/***/ 87937: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -class NotCachedError extends Error { - constructor (url) { - /* eslint-disable-next-line max-len */ - super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`) - this.code = 'ENOTCACHED' - } -} +"use strict"; -module.exports = { - NotCachedError, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bitLength = bitLength; +const errors_js_1 = __nccwpck_require__(15974); +const random_js_1 = __nccwpck_require__(23376); +function bitLength(alg) { + switch (alg) { + case 'A128GCM': + return 128; + case 'A192GCM': + return 192; + case 'A256GCM': + case 'A128CBC-HS256': + return 256; + case 'A192CBC-HS384': + return 384; + case 'A256CBC-HS512': + return 512; + default: + throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); + } } +exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); /***/ }), -/***/ 96807: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 63351: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const { NotCachedError } = __nccwpck_require__(59456) -const CacheEntry = __nccwpck_require__(85743) -const remote = __nccwpck_require__(20766) +"use strict"; -// do whatever is necessary to get a Response and return it -const cacheFetch = async (request, options) => { - // try to find a cached entry that satisfies this request - const entry = await CacheEntry.find(request, options) - if (!entry) { - // no cached result, if the cache mode is 'only-if-cached' that's a failure - if (options.cache === 'only-if-cached') { - throw new NotCachedError(request.url) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const errors_js_1 = __nccwpck_require__(15974); +const iv_js_1 = __nccwpck_require__(56565); +const checkIvLength = (enc, iv) => { + if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) { + throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length'); } +}; +exports["default"] = checkIvLength; - // otherwise, we make a request, store it and return it - const response = await remote(request, options) - const newEntry = new CacheEntry({ request, response, options }) - return newEntry.store('miss') - } - - // we have a cached response that satisfies this request, however if the cache - // mode is 'no-cache' then we send the revalidation request no matter what - if (options.cache === 'no-cache') { - return entry.revalidate(request, options) - } - // if the cached entry is not stale, or if the cache mode is 'force-cache' or - // 'only-if-cached' we can respond with the cached entry. set the status - // based on the result of needsRevalidation and respond - const _needsRevalidation = entry.policy.needsRevalidation(request) - if (options.cache === 'force-cache' || - options.cache === 'only-if-cached' || - !_needsRevalidation) { - return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit') - } +/***/ }), - // if we got here, the cache entry is stale so revalidate it - return entry.revalidate(request, options) -} +/***/ 29555: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -cacheFetch.invalidate = async (request, options) => { - if (!options.cachePath) { - return - } +"use strict"; - return CacheEntry.invalidate(request, options) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkKeyTypeWithJwk = void 0; +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const jwk = __nccwpck_require__(91229); +const tag = (key) => key?.[Symbol.toStringTag]; +const jwkMatchesOp = (alg, key, usage) => { + if (key.use !== undefined && key.use !== 'sig') { + throw new TypeError('Invalid key for this operation, when present its use must be sig'); + } + if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) { + throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); + } + if (key.alg !== undefined && key.alg !== alg) { + throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); + } + return true; +}; +const symmetricTypeCheck = (alg, key, usage, allowJwk) => { + if (key instanceof Uint8Array) + return; + if (allowJwk && jwk.isJWK(key)) { + if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); + } + if (!(0, is_key_like_js_1.default)(key)) { + throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null)); + } + if (key.type !== 'secret') { + throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); + } +}; +const asymmetricTypeCheck = (alg, key, usage, allowJwk) => { + if (allowJwk && jwk.isJWK(key)) { + switch (usage) { + case 'sign': + if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation be a private JWK`); + case 'verify': + if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) + return; + throw new TypeError(`JSON Web Key for this operation be a public JWK`); + } + } + if (!(0, is_key_like_js_1.default)(key)) { + throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, allowJwk ? 'JSON Web Key' : null)); + } + if (key.type === 'secret') { + throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); + } + if (usage === 'sign' && key.type === 'public') { + throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); + } + if (usage === 'decrypt' && key.type === 'public') { + throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); + } + if (key.algorithm && usage === 'verify' && key.type === 'private') { + throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); + } + if (key.algorithm && usage === 'encrypt' && key.type === 'private') { + throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); + } +}; +function checkKeyType(allowJwk, alg, key, usage) { + const symmetric = alg.startsWith('HS') || + alg === 'dir' || + alg.startsWith('PBES2') || + /^A\d{3}(?:GCM)?KW$/.test(alg); + if (symmetric) { + symmetricTypeCheck(alg, key, usage, allowJwk); + } + else { + asymmetricTypeCheck(alg, key, usage, allowJwk); + } } - -module.exports = cacheFetch +exports["default"] = checkKeyType.bind(undefined, false); +exports.checkKeyTypeWithJwk = checkKeyType.bind(undefined, true); /***/ }), -/***/ 45808: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { URL, format } = __nccwpck_require__(87016) +/***/ 88040: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// options passed to url.format() when generating a key -const formatOptions = { - auth: false, - fragment: false, - search: true, - unicode: false, -} +"use strict"; -// returns a string to be used as the cache key for the Request -const cacheKey = (request) => { - const parsed = new URL(request.url) - return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}` +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = checkP2s; +const errors_js_1 = __nccwpck_require__(15974); +function checkP2s(p2s) { + if (!(p2s instanceof Uint8Array) || p2s.length < 8) { + throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets'); + } } -module.exports = cacheKey - /***/ }), -/***/ 15281: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 26319: +/***/ ((__unused_webpack_module, exports) => { -const CacheSemantics = __nccwpck_require__(12203) -const Negotiator = __nccwpck_require__(60668) -const ssri = __nccwpck_require__(68951) +"use strict"; -// options passed to http-cache-semantics constructor -const policyOptions = { - shared: false, - ignoreCargoCult: true, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkSigCryptoKey = checkSigCryptoKey; +exports.checkEncCryptoKey = checkEncCryptoKey; +function unusable(name, prop = 'algorithm.name') { + return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } - -// a fake empty response, used when only testing the -// request for storability -const emptyResponse = { status: 200, headers: {} } - -// returns a plain object representation of the Request -const requestObject = (request) => { - const _obj = { - method: request.method, - url: request.url, - headers: {}, - compress: request.compress, - } - - request.headers.forEach((value, key) => { - _obj.headers[key] = value - }) - - return _obj +function isAlgorithm(algorithm, name) { + return algorithm.name === name; } - -// returns a plain object representation of the Response -const responseObject = (response) => { - const _obj = { - status: response.status, - headers: {}, - } - - response.headers.forEach((value, key) => { - _obj.headers[key] = value - }) - - return _obj +function getHashLength(hash) { + return parseInt(hash.name.slice(4), 10); +} +function getNamedCurve(alg) { + switch (alg) { + case 'ES256': + return 'P-256'; + case 'ES384': + return 'P-384'; + case 'ES512': + return 'P-521'; + default: + throw new Error('unreachable'); + } +} +function checkUsage(key, usages) { + if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { + let msg = 'CryptoKey does not support this operation, its usages must include '; + if (usages.length > 2) { + const last = usages.pop(); + msg += `one of ${usages.join(', ')}, or ${last}.`; + } + else if (usages.length === 2) { + msg += `one of ${usages[0]} or ${usages[1]}.`; + } + else { + msg += `${usages[0]}.`; + } + throw new TypeError(msg); + } +} +function checkSigCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': { + if (!isAlgorithm(key.algorithm, 'HMAC')) + throw unusable('HMAC'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'RS256': + case 'RS384': + case 'RS512': { + if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) + throw unusable('RSASSA-PKCS1-v1_5'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'PS256': + case 'PS384': + case 'PS512': { + if (!isAlgorithm(key.algorithm, 'RSA-PSS')) + throw unusable('RSA-PSS'); + const expected = parseInt(alg.slice(2), 10); + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + case 'EdDSA': { + if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { + throw unusable('Ed25519 or Ed448'); + } + break; + } + case 'ES256': + case 'ES384': + case 'ES512': { + if (!isAlgorithm(key.algorithm, 'ECDSA')) + throw unusable('ECDSA'); + const expected = getNamedCurve(alg); + const actual = key.algorithm.namedCurve; + if (actual !== expected) + throw unusable(expected, 'algorithm.namedCurve'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); +} +function checkEncCryptoKey(key, alg, ...usages) { + switch (alg) { + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': { + if (!isAlgorithm(key.algorithm, 'AES-GCM')) + throw unusable('AES-GCM'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (!isAlgorithm(key.algorithm, 'AES-KW')) + throw unusable('AES-KW'); + const expected = parseInt(alg.slice(1, 4), 10); + const actual = key.algorithm.length; + if (actual !== expected) + throw unusable(expected, 'algorithm.length'); + break; + } + case 'ECDH': { + switch (key.algorithm.name) { + case 'ECDH': + case 'X25519': + case 'X448': + break; + default: + throw unusable('ECDH, X25519, or X448'); + } + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': + if (!isAlgorithm(key.algorithm, 'PBKDF2')) + throw unusable('PBKDF2'); + break; + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) + throw unusable('RSA-OAEP'); + const expected = parseInt(alg.slice(9), 10) || 1; + const actual = getHashLength(key.algorithm.hash); + if (actual !== expected) + throw unusable(`SHA-${expected}`, 'algorithm.hash'); + break; + } + default: + throw new TypeError('CryptoKey does not support this operation'); + } + checkUsage(key, usages); } -class CachePolicy { - constructor ({ entry, request, response, options }) { - this.entry = entry - this.request = requestObject(request) - this.response = responseObject(response) - this.options = options - this.policy = new CacheSemantics(this.request, this.response, policyOptions) - if (this.entry) { - // if we have an entry, copy the timestamp to the _responseTime - // this is necessary because the CacheSemantics constructor forces - // the value to Date.now() which means a policy created from a - // cache entry is likely to always identify itself as stale - this.policy._responseTime = this.entry.metadata.time - } - } +/***/ }), - // static method to quickly determine if a request alone is storable - static storable (request, options) { - // no cachePath means no caching - if (!options.cachePath) { - return false - } +/***/ 56243: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // user explicitly asked not to cache - if (options.cache === 'no-store') { - return false - } +"use strict"; - // we only cache GET and HEAD requests - if (!['GET', 'HEAD'].includes(request.method)) { - return false +Object.defineProperty(exports, "__esModule", ({ value: true })); +const aeskw_js_1 = __nccwpck_require__(76202); +const ECDH = __nccwpck_require__(43359); +const pbes2kw_js_1 = __nccwpck_require__(52741); +const rsaes_js_1 = __nccwpck_require__(61129); +const base64url_js_1 = __nccwpck_require__(12635); +const normalize_key_js_1 = __nccwpck_require__(51276); +const errors_js_1 = __nccwpck_require__(15974); +const cek_js_1 = __nccwpck_require__(87937); +const import_js_1 = __nccwpck_require__(45647); +const check_key_type_js_1 = __nccwpck_require__(29555); +const is_object_js_1 = __nccwpck_require__(92242); +const aesgcmkw_js_1 = __nccwpck_require__(95864); +async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { + (0, check_key_type_js_1.default)(alg, key, 'decrypt'); + key = (await normalize_key_js_1.default.normalizePrivateKey?.(key, alg)) || key; + switch (alg) { + case 'dir': { + if (encryptedKey !== undefined) + throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); + return key; + } + case 'ECDH-ES': + if (encryptedKey !== undefined) + throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!(0, is_object_js_1.default)(joseHeader.epk)) + throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); + if (!ECDH.ecdhAllowed(key)) + throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg); + let partyUInfo; + let partyVInfo; + if (joseHeader.apu !== undefined) { + if (typeof joseHeader.apu !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); + try { + partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the apu'); + } + } + if (joseHeader.apv !== undefined) { + if (typeof joseHeader.apv !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); + try { + partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the apv'); + } + } + const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); + if (alg === 'ECDH-ES') + return sharedSecret; + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey); + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey); + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.p2c !== 'number') + throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); + const p2cLimit = options?.maxPBES2Count || 10_000; + if (joseHeader.p2c > p2cLimit) + throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); + if (typeof joseHeader.p2s !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); + let p2s; + try { + p2s = (0, base64url_js_1.decode)(joseHeader.p2s); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the p2s'); + } + return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s); + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey); + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + if (encryptedKey === undefined) + throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); + if (typeof joseHeader.iv !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); + if (typeof joseHeader.tag !== 'string') + throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); + let iv; + try { + iv = (0, base64url_js_1.decode)(joseHeader.iv); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv'); + } + let tag; + try { + tag = (0, base64url_js_1.decode)(joseHeader.tag); + } + catch { + throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag'); + } + return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag); + } + default: { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } } +} +exports["default"] = decryptKeyManagement; - // otherwise, let http-cache-semantics make the decision - // based on the request's headers - const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions) - return policy.storable() - } - // returns true if the policy satisfies the request - satisfies (request) { - const _req = requestObject(request) - if (this.request.headers.host !== _req.headers.host) { - return false - } +/***/ }), - if (this.request.compress !== _req.compress) { - return false - } +/***/ 96539: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const negotiatorA = new Negotiator(this.request) - const negotiatorB = new Negotiator(_req) +"use strict"; - if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) { - return false +Object.defineProperty(exports, "__esModule", ({ value: true })); +const aeskw_js_1 = __nccwpck_require__(76202); +const ECDH = __nccwpck_require__(43359); +const pbes2kw_js_1 = __nccwpck_require__(52741); +const rsaes_js_1 = __nccwpck_require__(61129); +const base64url_js_1 = __nccwpck_require__(12635); +const normalize_key_js_1 = __nccwpck_require__(51276); +const cek_js_1 = __nccwpck_require__(87937); +const errors_js_1 = __nccwpck_require__(15974); +const export_js_1 = __nccwpck_require__(48108); +const check_key_type_js_1 = __nccwpck_require__(29555); +const aesgcmkw_js_1 = __nccwpck_require__(95864); +async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { + let encryptedKey; + let parameters; + let cek; + (0, check_key_type_js_1.default)(alg, key, 'encrypt'); + key = (await normalize_key_js_1.default.normalizePublicKey?.(key, alg)) || key; + switch (alg) { + case 'dir': { + cek = key; + break; + } + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + if (!ECDH.ecdhAllowed(key)) { + throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); + } + const { apu, apv } = providedParameters; + let { epk: ephemeralKey } = providedParameters; + ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey; + const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey); + const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); + parameters = { epk: { x, crv, kty } }; + if (kty === 'EC') + parameters.epk.y = y; + if (apu) + parameters.apu = (0, base64url_js_1.encode)(apu); + if (apv) + parameters.apv = (0, base64url_js_1.encode)(apv); + if (alg === 'ECDH-ES') { + cek = sharedSecret; + break; + } + cek = providedCek || (0, cek_js_1.default)(enc); + const kwAlg = alg.slice(-6); + encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek); + break; + } + case 'RSA1_5': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': { + cek = providedCek || (0, cek_js_1.default)(enc); + encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek); + break; + } + case 'PBES2-HS256+A128KW': + case 'PBES2-HS384+A192KW': + case 'PBES2-HS512+A256KW': { + cek = providedCek || (0, cek_js_1.default)(enc); + const { p2c, p2s } = providedParameters; + ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s)); + break; + } + case 'A128KW': + case 'A192KW': + case 'A256KW': { + cek = providedCek || (0, cek_js_1.default)(enc); + encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek); + break; + } + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': { + cek = providedCek || (0, cek_js_1.default)(enc); + const { iv } = providedParameters; + ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv)); + break; + } + default: { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); + } } + return { cek, encryptedKey, parameters }; +} +exports["default"] = encryptKeyManagement; - if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) { - return false - } - if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) { - return false - } +/***/ }), - if (this.options.integrity) { - return ssri.parse(this.options.integrity).match(this.entry.integrity) - } +/***/ 40485: +/***/ ((__unused_webpack_module, exports) => { - return true - } +"use strict"; - // returns true if the request and response allow caching - storable () { - return this.policy.storable() - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = (date) => Math.floor(date.getTime() / 1000); - // NOTE: this is a hack to avoid parsing the cache-control - // header ourselves, it returns true if the response's - // cache-control contains must-revalidate - get mustRevalidate () { - return !!this.policy._rescc['must-revalidate'] - } - // returns true if the cached response requires revalidation - // for the given request - needsRevalidation (request) { - const _req = requestObject(request) - // force method to GET because we only cache GETs - // but can serve a HEAD from a cached GET - _req.method = 'GET' - return !this.policy.satisfiesWithoutRevalidation(_req) - } +/***/ }), - responseHeaders () { - return this.policy.responseHeaders() - } +/***/ 16632: +/***/ ((__unused_webpack_module, exports) => { - // returns a new object containing the appropriate headers - // to send a revalidation request - revalidationHeaders (request) { - const _req = requestObject(request) - return this.policy.revalidationHeaders(_req) - } +"use strict"; - // returns true if the request/response was revalidated - // successfully. returns false if a new response was received - revalidated (request, response) { - const _req = requestObject(request) - const _res = responseObject(response) - const policy = this.policy.revalidatedPolicy(_req, _res) - return !policy.modified - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.withAlg = withAlg; +function message(msg, actual, ...types) { + types = types.filter(Boolean); + if (types.length > 2) { + const last = types.pop(); + msg += `one of type ${types.join(', ')}, or ${last}.`; + } + else if (types.length === 2) { + msg += `one of type ${types[0]} or ${types[1]}.`; + } + else { + msg += `of type ${types[0]}.`; + } + if (actual == null) { + msg += ` Received ${actual}`; + } + else if (typeof actual === 'function' && actual.name) { + msg += ` Received function ${actual.name}`; + } + else if (typeof actual === 'object' && actual != null) { + if (actual.constructor?.name) { + msg += ` Received an instance of ${actual.constructor.name}`; + } + } + return msg; +} +exports["default"] = (actual, ...types) => { + return message('Key must be ', actual, ...types); +}; +function withAlg(alg, actual, ...types) { + return message(`Key for the ${alg} algorithm must be `, actual, ...types); } - -module.exports = CachePolicy /***/ }), -/***/ 67242: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 21853: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const isDisjoint = (...headers) => { + const sources = headers.filter(Boolean); + if (sources.length === 0 || sources.length === 1) { + return true; + } + let acc; + for (const header of sources) { + const parameters = Object.keys(header); + if (!acc || acc.size === 0) { + acc = new Set(parameters); + continue; + } + for (const parameter of parameters) { + if (acc.has(parameter)) { + return false; + } + acc.add(parameter); + } + } + return true; +}; +exports["default"] = isDisjoint; -const { FetchError, Request, isRedirect } = __nccwpck_require__(88483) -const url = __nccwpck_require__(87016) - -const CachePolicy = __nccwpck_require__(15281) -const cache = __nccwpck_require__(96807) -const remote = __nccwpck_require__(20766) - -// given a Request, a Response and user options -// return true if the response is a redirect that -// can be followed. we throw errors that will result -// in the fetch being rejected if the redirect is -// possible but invalid for some reason -const canFollowRedirect = (request, response, options) => { - if (!isRedirect(response.status)) { - return false - } - - if (options.redirect === 'manual') { - return false - } - if (options.redirect === 'error') { - throw new FetchError(`redirect mode is set to error: ${request.url}`, - 'no-redirect', { code: 'ENOREDIRECT' }) - } +/***/ }), - if (!response.headers.has('location')) { - throw new FetchError(`redirect location header missing for: ${request.url}`, - 'no-location', { code: 'EINVALIDREDIRECT' }) - } +/***/ 91229: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (request.counter >= request.follow) { - throw new FetchError(`maximum redirect reached at: ${request.url}`, - 'max-redirect', { code: 'EMAXREDIRECT' }) - } +"use strict"; - return true +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isJWK = isJWK; +exports.isPrivateJWK = isPrivateJWK; +exports.isPublicJWK = isPublicJWK; +exports.isSecretJWK = isSecretJWK; +const is_object_js_1 = __nccwpck_require__(92242); +function isJWK(key) { + return (0, is_object_js_1.default)(key) && typeof key.kty === 'string'; } - -// given a Request, a Response, and the user's options return an object -// with a new Request and a new options object that will be used for -// following the redirect -const getRedirect = (request, response, options) => { - const _opts = { ...options } - const location = response.headers.get('location') - const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url) - // Comment below is used under the following license: - /** - * @license - * Copyright (c) 2010-2012 Mikeal Rogers - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an "AS - * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language - * governing permissions and limitations under the License. - */ - - // Remove authorization if changing hostnames (but not if just - // changing ports or protocols). This matches the behavior of request: - // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 - if (new url.URL(request.url).hostname !== redirectUrl.hostname) { - request.headers.delete('authorization') - request.headers.delete('cookie') - } - - // for POST request with 301/302 response, or any request with 303 response, - // use GET when following redirect - if ( - response.status === 303 || - (request.method === 'POST' && [301, 302].includes(response.status)) - ) { - _opts.method = 'GET' - _opts.body = null - request.headers.delete('content-length') - } - - _opts.headers = {} - request.headers.forEach((value, key) => { - _opts.headers[key] = value - }) - - _opts.counter = ++request.counter - const redirectReq = new Request(url.format(redirectUrl), _opts) - return { - request: redirectReq, - options: _opts, - } +function isPrivateJWK(key) { + return key.kty !== 'oct' && typeof key.d === 'string'; } - -const fetch = async (request, options) => { - const response = CachePolicy.storable(request, options) - ? await cache(request, options) - : await remote(request, options) - - // if the request wasn't a GET or HEAD, and the response - // status is between 200 and 399 inclusive, invalidate the - // request url - if (!['GET', 'HEAD'].includes(request.method) && - response.status >= 200 && - response.status <= 399) { - await cache.invalidate(request, options) - } - - if (!canFollowRedirect(request, response, options)) { - return response - } - - const redirect = getRedirect(request, response, options) - return fetch(redirect.request, redirect.options) +function isPublicJWK(key) { + return key.kty !== 'oct' && typeof key.d === 'undefined'; +} +function isSecretJWK(key) { + return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string'; } - -module.exports = fetch /***/ }), -/***/ 39310: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { FetchError, Headers, Request, Response } = __nccwpck_require__(88483) - -const configureOptions = __nccwpck_require__(99824) -const fetch = __nccwpck_require__(67242) +/***/ 92242: +/***/ ((__unused_webpack_module, exports) => { -const makeFetchHappen = (url, opts) => { - const options = configureOptions(opts) +"use strict"; - const request = new Request(url, options) - return fetch(request, options) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = isObject; +function isObjectLike(value) { + return typeof value === 'object' && value !== null; } - -makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => { - if (typeof defaultUrl === 'object') { - defaultOptions = defaultUrl - defaultUrl = null - } - - const defaultedFetch = (url, options = {}) => { - const finalUrl = url || defaultUrl - const finalOptions = { - ...defaultOptions, - ...options, - headers: { - ...defaultOptions.headers, - ...options.headers, - }, +function isObject(input) { + if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { + return false; } - return wrappedFetch(finalUrl, finalOptions) - } - - defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) => - makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch) - return defaultedFetch + if (Object.getPrototypeOf(input) === null) { + return true; + } + let proto = input; + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto); + } + return Object.getPrototypeOf(input) === proto; } -module.exports = makeFetchHappen -module.exports.FetchError = FetchError -module.exports.Headers = Headers -module.exports.Request = Request -module.exports.Response = Response - /***/ }), -/***/ 99824: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const dns = __nccwpck_require__(72250) - -const conditionalHeaders = [ - 'if-modified-since', - 'if-none-match', - 'if-unmodified-since', - 'if-match', - 'if-range', -] - -const configureOptions = (opts) => { - const { strictSSL, ...options } = { ...opts } - options.method = options.method ? options.method.toUpperCase() : 'GET' - - if (strictSSL === undefined || strictSSL === null) { - options.rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0' - } else { - options.rejectUnauthorized = strictSSL !== false - } - - if (!options.retry) { - options.retry = { retries: 0 } - } else if (typeof options.retry === 'string') { - const retries = parseInt(options.retry, 10) - if (isFinite(retries)) { - options.retry = { retries } - } else { - options.retry = { retries: 0 } - } - } else if (typeof options.retry === 'number') { - options.retry = { retries: options.retry } - } else { - options.retry = { retries: 0, ...options.retry } - } +/***/ 56565: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns } +"use strict"; - options.cache = options.cache || 'default' - if (options.cache === 'default') { - const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => { - return conditionalHeaders.includes(name.toLowerCase()) - }) - if (hasConditionalHeader) { - options.cache = 'no-store' +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.bitLength = bitLength; +const errors_js_1 = __nccwpck_require__(15974); +const random_js_1 = __nccwpck_require__(23376); +function bitLength(alg) { + switch (alg) { + case 'A128GCM': + case 'A128GCMKW': + case 'A192GCM': + case 'A192GCMKW': + case 'A256GCM': + case 'A256GCMKW': + return 96; + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return 128; + default: + throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } - } - - options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || [] - - // cacheManager is deprecated, but if it's set and - // cachePath is not we should copy it to the new field - if (options.cacheManager && !options.cachePath) { - options.cachePath = options.cacheManager - } - - return options } - -module.exports = configureOptions +exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); /***/ }), -/***/ 22314: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 13354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const MinipassPipeline = __nccwpck_require__(52899) - -class CachingMinipassPipeline extends MinipassPipeline { - #events = [] - #data = new Map() - - constructor (opts, ...streams) { - // CRITICAL: do NOT pass the streams to the call to super(), this will start - // the flow of data and potentially cause the events we need to catch to emit - // before we've finished our own setup. instead we call super() with no args, - // finish our setup, and then push the streams into ourselves to start the - // data flow - super() - this.#events = opts.events - - /* istanbul ignore next - coverage disabled because this is pointless to test here */ - if (streams.length) { - this.push(...streams) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const epoch_js_1 = __nccwpck_require__(40485); +const secs_js_1 = __nccwpck_require__(40556); +const is_object_js_1 = __nccwpck_require__(92242); +const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); +const checkAudiencePresence = (audPayload, audOption) => { + if (typeof audPayload === 'string') { + return audOption.includes(audPayload); + } + if (Array.isArray(audPayload)) { + return audOption.some(Set.prototype.has.bind(new Set(audPayload))); + } + return false; +}; +exports["default"] = (protectedHeader, encodedPayload, options = {}) => { + let payload; + try { + payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload)); + } + catch { + } + if (!(0, is_object_js_1.default)(payload)) { + throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object'); + } + const { typ } = options; + if (typ && + (typeof protectedHeader.typ !== 'string' || + normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed'); + } + const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; + const presenceCheck = [...requiredClaims]; + if (maxTokenAge !== undefined) + presenceCheck.push('iat'); + if (audience !== undefined) + presenceCheck.push('aud'); + if (subject !== undefined) + presenceCheck.push('sub'); + if (issuer !== undefined) + presenceCheck.push('iss'); + for (const claim of new Set(presenceCheck.reverse())) { + if (!(claim in payload)) { + throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing'); + } + } + if (issuer && + !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed'); + } + if (subject && payload.sub !== subject) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed'); + } + if (audience && + !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { + throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed'); + } + let tolerance; + switch (typeof options.clockTolerance) { + case 'string': + tolerance = (0, secs_js_1.default)(options.clockTolerance); + break; + case 'number': + tolerance = options.clockTolerance; + break; + case 'undefined': + tolerance = 0; + break; + default: + throw new TypeError('Invalid clockTolerance option type'); + } + const { currentDate } = options; + const now = (0, epoch_js_1.default)(currentDate || new Date()); + if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') { + throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid'); + } + if (payload.nbf !== undefined) { + if (typeof payload.nbf !== 'number') { + throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid'); + } + if (payload.nbf > now + tolerance) { + throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed'); + } + } + if (payload.exp !== undefined) { + if (typeof payload.exp !== 'number') { + throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid'); + } + if (payload.exp <= now - tolerance) { + throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed'); + } + } + if (maxTokenAge) { + const age = now - payload.iat; + const max = typeof maxTokenAge === 'number' ? maxTokenAge : (0, secs_js_1.default)(maxTokenAge); + if (age - tolerance > max) { + throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed'); + } + if (age < 0 - tolerance) { + throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed'); + } } - } + return payload; +}; - on (event, handler) { - if (this.#events.includes(event) && this.#data.has(event)) { - return handler(...this.#data.get(event)) - } - return super.on(event, handler) - } +/***/ }), - emit (event, ...data) { - if (this.#events.includes(event)) { - this.#data.set(event, data) - } +/***/ 46433: +/***/ ((__unused_webpack_module, exports) => { - return super.emit(event, ...data) - } -} +"use strict"; -module.exports = CachingMinipassPipeline +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.unprotected = void 0; +exports.unprotected = Symbol(); /***/ }), -/***/ 20766: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 40556: +/***/ ((__unused_webpack_module, exports) => { -const { Minipass } = __nccwpck_require__(78275) -const fetch = __nccwpck_require__(88483) -const promiseRetry = __nccwpck_require__(90390) -const ssri = __nccwpck_require__(68951) -const { log } = __nccwpck_require__(26687) +"use strict"; -const CachingMinipassPipeline = __nccwpck_require__(22314) -const { getAgent } = __nccwpck_require__(57995) -const pkg = __nccwpck_require__(96734) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const minute = 60; +const hour = minute * 60; +const day = hour * 24; +const week = day * 7; +const year = day * 365.25; +const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; +exports["default"] = (str) => { + const matched = REGEX.exec(str); + if (!matched || (matched[4] && matched[1])) { + throw new TypeError('Invalid time period format'); + } + const value = parseFloat(matched[2]); + const unit = matched[3].toLowerCase(); + let numericDate; + switch (unit) { + case 'sec': + case 'secs': + case 'second': + case 'seconds': + case 's': + numericDate = Math.round(value); + break; + case 'minute': + case 'minutes': + case 'min': + case 'mins': + case 'm': + numericDate = Math.round(value * minute); + break; + case 'hour': + case 'hours': + case 'hr': + case 'hrs': + case 'h': + numericDate = Math.round(value * hour); + break; + case 'day': + case 'days': + case 'd': + numericDate = Math.round(value * day); + break; + case 'week': + case 'weeks': + case 'w': + numericDate = Math.round(value * week); + break; + default: + numericDate = Math.round(value * year); + break; + } + if (matched[1] === '-' || matched[4] === 'ago') { + return -numericDate; + } + return numericDate; +}; -const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` -const RETRY_ERRORS = [ - 'ECONNRESET', // remote socket closed on us - 'ECONNREFUSED', // remote host refused to open connection - 'EADDRINUSE', // failed to bind to a local port (proxy?) - 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW - // from @npmcli/agent - 'ECONNECTIONTIMEOUT', - 'EIDLETIMEOUT', - 'ERESPONSETIMEOUT', - 'ETRANSFERTIMEOUT', - // Known codes we do NOT retry on: - // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) - // EINVALIDPROXY // invalid protocol from @npmcli/agent - // EINVALIDRESPONSE // invalid status code from @npmcli/agent -] +/***/ }), -const RETRY_TYPES = [ - 'request-timeout', -] +/***/ 19917: +/***/ ((__unused_webpack_module, exports) => { -// make a request directly to the remote source, -// retrying certain classes of errors as well as -// following redirects (through the cache if necessary) -// and verifying response integrity -const remoteFetch = (request, options) => { - // options.signal is intended for the fetch itself, not the agent. Attaching it to the agent will re-use that signal across multiple requests, which prevents any connections beyond the first one. - const agent = getAgent(request.url, { ...options, signal: undefined }) - if (!request.headers.has('connection')) { - request.headers.set('connection', agent ? 'keep-alive' : 'close') - } +"use strict"; - if (!request.headers.has('user-agent')) { - request.headers.set('user-agent', USER_AGENT) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const validateAlgorithms = (option, algorithms) => { + if (algorithms !== undefined && + (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { + throw new TypeError(`"${option}" option must be an array of strings`); + } + if (!algorithms) { + return undefined; + } + return new Set(algorithms); +}; +exports["default"] = validateAlgorithms; - // keep our own options since we're overriding the agent - // and the redirect mode - const _opts = { - ...options, - agent, - redirect: 'manual', - } - return promiseRetry(async (retryHandler, attemptNum) => { - const req = new fetch.Request(request, _opts) - try { - let res = await fetch(req, _opts) - if (_opts.integrity && res.status === 200) { - // we got a 200 response and the user has specified an expected - // integrity value, so wrap the response in an ssri stream to verify it - const integrityStream = ssri.integrityStream({ - algorithms: _opts.algorithms, - integrity: _opts.integrity, - size: _opts.size, - }) - const pipeline = new CachingMinipassPipeline({ - events: ['integrity', 'size'], - }, res.body, integrityStream) - // we also propagate the integrity and size events out to the pipeline so we can use - // this new response body as an integrityEmitter for cacache - integrityStream.on('integrity', i => pipeline.emit('integrity', i)) - integrityStream.on('size', s => pipeline.emit('size', s)) - res = new fetch.Response(pipeline, res) - // set an explicit flag so we know if our response body will emit integrity and size - res.body.hasIntegrityEmitter = true - } +/***/ }), - res.headers.set('x-fetch-attempts', attemptNum) +/***/ 15595: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // do not retry POST requests, or requests with a streaming body - // do retry requests with a 408, 420, 429 or 500+ status in the response - const isStream = Minipass.isStream(req.body) - const isRetriable = req.method !== 'POST' && - !isStream && - ([408, 420, 429].includes(res.status) || res.status >= 500) +"use strict"; - if (isRetriable) { - if (typeof options.onRetry === 'function') { - options.onRetry(res) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const errors_js_1 = __nccwpck_require__(15974); +function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { + if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) { + throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); + } + if (!protectedHeader || protectedHeader.crit === undefined) { + return new Set(); + } + if (!Array.isArray(protectedHeader.crit) || + protectedHeader.crit.length === 0 || + protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { + throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); + } + let recognized; + if (recognizedOption !== undefined) { + recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); + } + else { + recognized = recognizedDefault; + } + for (const parameter of protectedHeader.crit) { + if (!recognized.has(parameter)) { + throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } + if (joseHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" is missing`); + } + if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { + throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); + } + } + return new Set(protectedHeader.crit); +} +exports["default"] = validateCrit; - /* eslint-disable-next-line max-len */ - log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) - return retryHandler(res) - } - - return res - } catch (err) { - const code = (err.code === 'EPROMISERETRY') - ? err.retried.code - : err.code - // err.retried will be the thing that was thrown from above - // if it's a response, we just got a bad status code and we - // can re-throw to allow the retry - const isRetryError = err.retried instanceof fetch.Response || - (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type)) +/***/ }), - if (req.method === 'POST' || isRetryError) { - throw err - } +/***/ 76202: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (typeof options.onRetry === 'function') { - options.onRetry(err) - } +"use strict"; - log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) - return retryHandler(err) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.unwrap = exports.wrap = void 0; +const node_buffer_1 = __nccwpck_require__(4573); +const node_crypto_1 = __nccwpck_require__(77598); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const ciphers_js_1 = __nccwpck_require__(99271); +const is_key_like_js_1 = __nccwpck_require__(7433); +function checkKeySize(key, alg) { + if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { + throw new TypeError(`Invalid key size for alg: ${alg}`); } - }, options.retry).catch((err) => { - // don't reject for http errors, just return them - if (err.status >= 400 && err.type !== 'system') { - return err +} +function ensureKeyObject(key, alg, usage) { + if ((0, is_key_object_js_1.default)(key)) { + return key; } - - throw err - }) + if (key instanceof Uint8Array) { + return (0, node_crypto_1.createSecretKey)(key); + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage); + return node_crypto_1.KeyObject.from(key); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); } - -module.exports = remoteFetch +const wrap = (alg, key, cek) => { + const size = parseInt(alg.slice(1, 4), 10); + const algorithm = `aes${size}-wrap`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + const keyObject = ensureKeyObject(key, alg, 'wrapKey'); + checkKeySize(keyObject, alg); + const cipher = (0, node_crypto_1.createCipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6)); + return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final()); +}; +exports.wrap = wrap; +const unwrap = (alg, key, encryptedKey) => { + const size = parseInt(alg.slice(1, 4), 10); + const algorithm = `aes${size}-wrap`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); + checkKeySize(keyObject, alg); + const cipher = (0, node_crypto_1.createDecipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6)); + return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final()); +}; +exports.unwrap = unwrap; /***/ }), -/***/ 43772: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = (function () { try { return __nccwpck_require__(16928) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep - -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(94691) +/***/ 12774: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} +"use strict"; -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0; +const node_crypto_1 = __nccwpck_require__(77598); +const node_buffer_1 = __nccwpck_require__(4573); +const webcrypto_js_1 = __nccwpck_require__(59044); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const genericExport = (keyType, keyFormat, key) => { + let keyObject; + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + keyObject = node_crypto_1.KeyObject.from(key); + } + else if ((0, is_key_object_js_1.default)(key)) { + keyObject = key; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); + } + if (keyObject.type !== keyType) { + throw new TypeError(`key is not a ${keyType} key`); + } + return keyObject.export({ format: 'pem', type: keyFormat }); +}; +const toSPKI = (key) => { + return genericExport('public', 'spki', key); +}; +exports.toSPKI = toSPKI; +const toPKCS8 = (key) => { + return genericExport('private', 'pkcs8', key); +}; +exports.toPKCS8 = toPKCS8; +const fromPKCS8 = (pem) => (0, node_crypto_1.createPrivateKey)({ + key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), + type: 'pkcs8', + format: 'der', +}); +exports.fromPKCS8 = fromPKCS8; +const fromSPKI = (pem) => (0, node_crypto_1.createPublicKey)({ + key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), + type: 'spki', + format: 'der', +}); +exports.fromSPKI = fromSPKI; +const fromX509 = (pem) => (0, node_crypto_1.createPublicKey)({ + key: pem, + type: 'spki', + format: 'pem', +}); +exports.fromX509 = fromX509; -// * => any number of characters -var star = qmark + '*?' -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' +/***/ }), -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' +/***/ 12635: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') +"use strict"; -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0; +const node_buffer_1 = __nccwpck_require__(4573); +const buffer_utils_js_1 = __nccwpck_require__(45734); +function normalize(input) { + let encoded = input; + if (encoded instanceof Uint8Array) { + encoded = buffer_utils_js_1.decoder.decode(encoded); + } + return encoded; } +const encode = (input) => node_buffer_1.Buffer.from(input).toString('base64url'); +exports.encode = encode; +const decodeBase64 = (input) => new Uint8Array(node_buffer_1.Buffer.from(input, 'base64')); +exports.decodeBase64 = decodeBase64; +const encodeBase64 = (input) => node_buffer_1.Buffer.from(input).toString('base64'); +exports.encodeBase64 = encodeBase64; +const decode = (input) => new Uint8Array(node_buffer_1.Buffer.from(normalize(input), 'base64url')); +exports.decode = decode; -// normalizes slashes. -var slashSplit = /\/+/ -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} +/***/ }), -function ext (a, b) { - b = b || {} - var t = {} - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - return t -} +/***/ 36910: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch - } +"use strict"; - var orig = minimatch +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = cbcTag; +const node_crypto_1 = __nccwpck_require__(77598); +const buffer_utils_js_1 = __nccwpck_require__(45734); +function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { + const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3)); + const hmac = (0, node_crypto_1.createHmac)(`sha${macSize}`, macKey); + hmac.update(macData); + return hmac.digest().slice(0, keySize >> 3); +} - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) - } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - m.Minimatch.defaults = function defaults (options) { - return orig.defaults(ext(def, options)).Minimatch - } +/***/ }), - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) - } +/***/ 67000: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) - } +"use strict"; - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const errors_js_1 = __nccwpck_require__(15974); +const is_key_object_js_1 = __nccwpck_require__(68685); +const checkCekLength = (enc, cek) => { + let expected; + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + expected = parseInt(enc.slice(-3), 10); + break; + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + expected = parseInt(enc.slice(1, 4), 10); + break; + default: + throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); + } + if (cek instanceof Uint8Array) { + const actual = cek.byteLength << 3; + if (actual !== expected) { + throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } + return; + } + if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') { + const actual = cek.symmetricKeySize << 3; + if (actual !== expected) { + throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); + } + return; + } + throw new TypeError('Invalid Content Encryption Key type'); +}; +exports["default"] = checkCekLength; - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) - } - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) - } +/***/ }), - return m -} +/***/ 65142: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch -} +"use strict"; -function minimatch (p, pattern, options) { - assertValidPattern(pattern) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +exports["default"] = (key, alg) => { + let modulusLength; + try { + if (key instanceof node_crypto_1.KeyObject) { + modulusLength = key.asymmetricKeyDetails?.modulusLength; + } + else { + modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3; + } + } + catch { } + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); + } +}; - if (!options) options = {} - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } +/***/ }), - return new Minimatch(pattern, options).match(p) -} +/***/ 99271: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } +"use strict"; - assertValidPattern(pattern) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +let ciphers; +exports["default"] = (algorithm) => { + ciphers ||= new Set((0, node_crypto_1.getCiphers)()); + return ciphers.has(algorithm); +}; - if (!options) options = {} - pattern = pattern.trim() +/***/ }), - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } +/***/ 52806: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial +"use strict"; - // make the set of regexps etc. - this.make() +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +const check_iv_length_js_1 = __nccwpck_require__(63351); +const check_cek_length_js_1 = __nccwpck_require__(67000); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const errors_js_1 = __nccwpck_require__(15974); +const timing_safe_equal_js_1 = __nccwpck_require__(39106); +const cbc_tag_js_1 = __nccwpck_require__(36910); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const ciphers_js_1 = __nccwpck_require__(99271); +const is_key_like_js_1 = __nccwpck_require__(7433); +function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + if ((0, is_key_object_js_1.default)(cek)) { + cek = cek.export(); + } + const encKey = cek.subarray(keySize >> 3); + const macKey = cek.subarray(0, keySize >> 3); + const macSize = parseInt(enc.slice(-3), 10); + const algorithm = `aes-${keySize}-cbc`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); + let macCheckPassed; + try { + macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag); + } + catch { + } + if (!macCheckPassed) { + throw new errors_js_1.JWEDecryptionFailed(); + } + let plaintext; + try { + const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, encKey, iv); + plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final()); + } + catch { + } + if (!plaintext) { + throw new errors_js_1.JWEDecryptionFailed(); + } + return plaintext; } +function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + const algorithm = `aes-${keySize}-gcm`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + try { + const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 }); + decipher.setAuthTag(tag); + if (aad.byteLength) { + decipher.setAAD(aad, { plaintextLength: ciphertext.length }); + } + const plaintext = decipher.update(ciphertext); + decipher.final(); + return plaintext; + } + catch { + throw new errors_js_1.JWEDecryptionFailed(); + } +} +const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(cek)) { + (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt'); + key = node_crypto_1.KeyObject.from(cek); + } + else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { + key = cek; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); + } + if (!iv) { + throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing'); + } + if (!tag) { + throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing'); + } + (0, check_cek_length_js_1.default)(enc, key); + (0, check_iv_length_js_1.default)(enc, iv); + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); + default: + throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); + } +}; +exports["default"] = decrypt; -Minimatch.prototype.debug = function () {} - -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } +/***/ }), - this.debug(this.pattern, set) +/***/ 12931: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) +"use strict"; - this.debug(this.pattern, set) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +const digest = (algorithm, data) => (0, node_crypto_1.createHash)(algorithm).update(data).digest(); +exports["default"] = digest; - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - this.debug(this.pattern, set) +/***/ }), - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) +/***/ 74510: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.debug(this.pattern, set) +"use strict"; - this.set = set +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = dsaDigest; +const errors_js_1 = __nccwpck_require__(15974); +function dsaDigest(alg) { + switch (alg) { + case 'PS256': + case 'RS256': + case 'ES256': + case 'ES256K': + return 'sha256'; + case 'PS384': + case 'RS384': + case 'ES384': + return 'sha384'; + case 'PS512': + case 'RS512': + case 'ES512': + return 'sha512'; + case 'EdDSA': + return undefined; + default: + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - - if (options.nonegate) return - - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} +/***/ }), -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} +/***/ 43359: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Minimatch.prototype.braceExpand = braceExpand +"use strict"; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ecdhAllowed = void 0; +exports.deriveKey = deriveKey; +exports.generateEpk = generateEpk; +const node_crypto_1 = __nccwpck_require__(77598); +const node_util_1 = __nccwpck_require__(57975); +const get_named_curve_js_1 = __nccwpck_require__(65661); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const errors_js_1 = __nccwpck_require__(15974); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const generateKeyPair = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair); +async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { + let publicKey; + if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) { + (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH'); + publicKey = node_crypto_1.KeyObject.from(publicKee); } - } - - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - assertValidPattern(pattern) - - // Thanks to Yeting Li for - // improving this regexp to avoid a ReDOS vulnerability. - if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { - // shortcut. no need to expand. - return [pattern] - } - - return expand(pattern) + else if ((0, is_key_object_js_1.default)(publicKee)) { + publicKey = publicKee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types)); + } + let privateKey; + if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) { + (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits'); + privateKey = node_crypto_1.KeyObject.from(privateKee); + } + else if ((0, is_key_object_js_1.default)(privateKee)) { + privateKey = privateKee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types)); + } + const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength)); + const sharedSecret = (0, node_crypto_1.diffieHellman)({ privateKey, publicKey }); + return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value); } - -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') - } - - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') - } +async function generateEpk(kee) { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(kee)) { + key = node_crypto_1.KeyObject.from(kee); + } + else if ((0, is_key_object_js_1.default)(kee)) { + key = kee; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); + } + switch (key.asymmetricKeyType) { + case 'x25519': + return generateKeyPair('x25519'); + case 'x448': { + return generateKeyPair('x448'); + } + case 'ec': { + const namedCurve = (0, get_named_curve_js_1.default)(key); + return generateKeyPair('ec', { namedCurve }); + } + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK'); + } } +const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key)); +exports.ecdhAllowed = ecdhAllowed; -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - assertValidPattern(pattern) - var options = this.options +/***/ }), - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' - } - if (pattern === '') return '' +/***/ 36286: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this +"use strict"; - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +const check_iv_length_js_1 = __nccwpck_require__(63351); +const check_cek_length_js_1 = __nccwpck_require__(67000); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const cbc_tag_js_1 = __nccwpck_require__(36910); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const iv_js_1 = __nccwpck_require__(56565); +const errors_js_1 = __nccwpck_require__(15974); +const ciphers_js_1 = __nccwpck_require__(99271); +const is_key_like_js_1 = __nccwpck_require__(7433); +function cbcEncrypt(enc, plaintext, cek, iv, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + if ((0, is_key_object_js_1.default)(cek)) { + cek = cek.export(); + } + const encKey = cek.subarray(keySize >> 3); + const macKey = cek.subarray(0, keySize >> 3); + const algorithm = `aes-${keySize}-cbc`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const cipher = (0, node_crypto_1.createCipheriv)(algorithm, encKey, iv); + const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final()); + const macSize = parseInt(enc.slice(-3), 10); + const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); + return { ciphertext, tag, iv }; +} +function gcmEncrypt(enc, plaintext, cek, iv, aad) { + const keySize = parseInt(enc.slice(1, 4), 10); + const algorithm = `aes-${keySize}-gcm`; + if (!(0, ciphers_js_1.default)(algorithm)) { + throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); + } + const cipher = (0, node_crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 }); + if (aad.byteLength) { + cipher.setAAD(aad, { plaintextLength: plaintext.length }); + } + const ciphertext = cipher.update(plaintext); + cipher.final(); + const tag = cipher.getAuthTag(); + return { ciphertext, tag, iv }; +} +const encrypt = (enc, plaintext, cek, iv, aad) => { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(cek)) { + (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt'); + key = node_crypto_1.KeyObject.from(cek); + } + else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { + key = cek; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); + } + (0, check_cek_length_js_1.default)(enc, key); + if (iv) { + (0, check_iv_length_js_1.default)(enc, iv); + } + else { + iv = (0, iv_js_1.default)(enc); + } + switch (enc) { + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + return cbcEncrypt(enc, plaintext, key, iv, aad); + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + return gcmEncrypt(enc, plaintext, key, iv, aad); default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false + throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) +}; +exports["default"] = encrypt; - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } +/***/ }), - case '\\': - clearStateChar() - escaping = true - continue +/***/ 20311: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) +"use strict"; - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const http = __nccwpck_require__(37067); +const https = __nccwpck_require__(44708); +const node_events_1 = __nccwpck_require__(78474); +const errors_js_1 = __nccwpck_require__(15974); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const fetchJwks = async (url, timeout, options) => { + let get; + switch (url.protocol) { + case 'https:': + get = https.get; + break; + case 'http:': + get = http.get; + break; + default: + throw new TypeError('Unsupported URL protocol.'); + } + const { agent, headers } = options; + const req = get(url.href, { + agent, + timeout, + headers, + }); + const [response] = (await Promise.race([(0, node_events_1.once)(req, 'response'), (0, node_events_1.once)(req, 'timeout')])); + if (!response) { + req.destroy(); + throw new errors_js_1.JWKSTimeout(); + } + if (response.statusCode !== 200) { + throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); + } + const parts = []; + for await (const part of response) { + parts.push(part); + } + try { + return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts))); + } + catch { + throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); + } +}; +exports["default"] = fetchJwks; - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - case '(': - if (inClass) { - re += '(' - continue - } +/***/ }), - if (!stateChar) { - re += '\\(' - continue - } +/***/ 10088: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue +"use strict"; - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generateSecret = generateSecret; +exports.generateKeyPair = generateKeyPair; +const node_crypto_1 = __nccwpck_require__(77598); +const node_util_1 = __nccwpck_require__(57975); +const random_js_1 = __nccwpck_require__(23376); +const errors_js_1 = __nccwpck_require__(15974); +const generate = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair); +async function generateSecret(alg, options) { + let length; + switch (alg) { + case 'HS256': + case 'HS384': + case 'HS512': + case 'A128CBC-HS256': + case 'A192CBC-HS384': + case 'A256CBC-HS512': + length = parseInt(alg.slice(-3), 10); + break; + case 'A128KW': + case 'A192KW': + case 'A256KW': + case 'A128GCMKW': + case 'A192GCMKW': + case 'A256GCMKW': + case 'A128GCM': + case 'A192GCM': + case 'A256GCM': + length = parseInt(alg.slice(1, 4), 10); + break; + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } + return (0, node_crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3))); +} +async function generateKeyPair(alg, options) { + switch (alg) { + case 'RS256': + case 'RS384': + case 'RS512': + case 'PS256': + case 'PS384': + case 'PS512': + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + case 'RSA1_5': { + const modulusLength = options?.modulusLength ?? 2048; + if (typeof modulusLength !== 'number' || modulusLength < 2048) { + throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); + } + const keypair = await generate('rsa', { + modulusLength, + publicExponent: 0x10001, + }); + return keypair; } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) + case 'ES256': + return generate('ec', { namedCurve: 'P-256' }); + case 'ES256K': + return generate('ec', { namedCurve: 'secp256k1' }); + case 'ES384': + return generate('ec', { namedCurve: 'P-384' }); + case 'ES512': + return generate('ec', { namedCurve: 'P-521' }); + case 'EdDSA': { + switch (options?.crv) { + case undefined: + case 'Ed25519': + return generate('ed25519'); + case 'Ed448': + return generate('ed448'); + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); + } } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue + case 'ECDH-ES': + case 'ECDH-ES+A128KW': + case 'ECDH-ES+A192KW': + case 'ECDH-ES+A256KW': { + const crv = options?.crv ?? 'P-256'; + switch (crv) { + case undefined: + case 'P-256': + case 'P-384': + case 'P-521': + return generate('ec', { namedCurve: crv }); + case 'X25519': + return generate('x25519'); + case 'X448': + return generate('x448'); + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); + } } + default: + throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); + } +} - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - if (inClass) { - re += '\\' + c - continue - } +/***/ }), - inClass = true - classStart = i - reClassStart = re.length - re += c - continue +/***/ 65661: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } +"use strict"; - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.weakMap = void 0; +const node_crypto_1 = __nccwpck_require__(77598); +const errors_js_1 = __nccwpck_require__(15974); +const webcrypto_js_1 = __nccwpck_require__(59044); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const is_jwk_js_1 = __nccwpck_require__(91229); +exports.weakMap = new WeakMap(); +const namedCurveToJOSE = (namedCurve) => { + switch (namedCurve) { + case 'prime256v1': + return 'P-256'; + case 'secp384r1': + return 'P-384'; + case 'secp521r1': + return 'P-521'; + case 'secp256k1': + return 'secp256k1'; + default: + throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); + } +}; +const getNamedCurve = (kee, raw) => { + let key; + if ((0, webcrypto_js_1.isCryptoKey)(kee)) { + key = node_crypto_1.KeyObject.from(kee); + } + else if ((0, is_key_object_js_1.default)(kee)) { + key = kee; + } + else if ((0, is_jwk_js_1.isJWK)(kee)) { + return kee.crv; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); + } + if (key.type === 'secret') { + throw new TypeError('only "private" or "public" type keys can be used for this operation'); + } + switch (key.asymmetricKeyType) { + case 'ed25519': + case 'ed448': + return `Ed${key.asymmetricKeyType.slice(2)}`; + case 'x25519': + case 'x448': + return `X${key.asymmetricKeyType.slice(1)}`; + case 'ec': { + const namedCurve = key.asymmetricKeyDetails.namedCurve; + if (raw) { + return namedCurve; + } + return namedCurveToJOSE(namedCurve); } + default: + throw new TypeError('Invalid asymmetric key type for this operation'); + } +}; +exports["default"] = getNamedCurve; - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } +/***/ }), - re += c +/***/ 80723: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } // switch - } // for +"use strict"; - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = getSignVerifyKey; +const node_crypto_1 = __nccwpck_require__(77598); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const jwk = __nccwpck_require__(91229); +function getSignVerifyKey(alg, key, usage) { + if (key instanceof Uint8Array) { + if (!alg.startsWith('HS')) { + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); + } + return (0, node_crypto_1.createSecretKey)(key); + } + if (key instanceof node_crypto_1.KeyObject) { + return key; + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage); + return node_crypto_1.KeyObject.from(key); + } + if (jwk.isJWK(key)) { + if (alg.startsWith('HS')) { + return (0, node_crypto_1.createSecretKey)(Buffer.from(key.k, 'base64url')); + } + return key; + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array', 'JSON Web Key')); +} - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) +/***/ }), - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type +/***/ 57399: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } +"use strict"; - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = hmacDigest; +const errors_js_1 = __nccwpck_require__(15974); +function hmacDigest(alg) { + switch (alg) { + case 'HS256': + return 'sha256'; + case 'HS384': + return 'sha384'; + case 'HS512': + return 'sha512'; + default: + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } +} - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '[': case '.': case '(': addPatternStart = true - } - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] +/***/ }), - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) +/***/ 7433: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - nlLast += nlAfter +"use strict"; - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.types = void 0; +const webcrypto_js_1 = __nccwpck_require__(59044); +const is_key_object_js_1 = __nccwpck_require__(68685); +exports["default"] = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key); +const types = ['KeyObject']; +exports.types = types; +if (globalThis.CryptoKey || webcrypto_js_1.default?.CryptoKey) { + types.push('CryptoKey'); +} - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } +/***/ }), - if (addPatternStart) { - re = patternStart + re - } +/***/ 68685: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } +"use strict"; - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util = __nccwpck_require__(57975); +exports["default"] = (obj) => util.types.isKeyObject(obj); - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) /* istanbul ignore next - should be impossible */ { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - regExp._glob = pattern - regExp._src = re +/***/ }), - return regExp -} +/***/ 80939: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} +"use strict"; -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +const parse = (key) => { + if (key.d) { + return (0, node_crypto_1.createPrivateKey)({ format: 'jwk', key }); + } + return (0, node_crypto_1.createPublicKey)({ format: 'jwk', key }); +}; +exports["default"] = parse; - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options +/***/ }), - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' +/***/ 9041: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') +"use strict"; - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +const base64url_js_1 = __nccwpck_require__(12635); +const errors_js_1 = __nccwpck_require__(15974); +const webcrypto_js_1 = __nccwpck_require__(59044); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const keyToJWK = (key) => { + let keyObject; + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + if (!key.extractable) { + throw new TypeError('CryptoKey is not extractable'); + } + keyObject = node_crypto_1.KeyObject.from(key); + } + else if ((0, is_key_object_js_1.default)(key)) { + keyObject = key; + } + else if (key instanceof Uint8Array) { + return { + kty: 'oct', + k: (0, base64url_js_1.encode)(key), + }; + } + else { + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); + } + if (keyObject.type !== 'secret' && + !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { + throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); + } + return keyObject.export({ format: 'jwk' }); +}; +exports["default"] = keyToJWK; - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false - } - return this.regexp -} +/***/ }), -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list +/***/ 70363: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = keyForCrypto; +const node_crypto_1 = __nccwpck_require__(77598); +const get_named_curve_js_1 = __nccwpck_require__(65661); +const errors_js_1 = __nccwpck_require__(15974); +const check_key_length_js_1 = __nccwpck_require__(65142); +const ecCurveAlgMap = new Map([ + ['ES256', 'P-256'], + ['ES256K', 'secp256k1'], + ['ES384', 'P-384'], + ['ES512', 'P-521'], +]); +function keyForCrypto(alg, key) { + let asymmetricKeyType; + let asymmetricKeyDetails; + let isJWK; + if (key instanceof node_crypto_1.KeyObject) { + asymmetricKeyType = key.asymmetricKeyType; + asymmetricKeyDetails = key.asymmetricKeyDetails; + } + else { + isJWK = true; + switch (key.kty) { + case 'RSA': + asymmetricKeyType = 'rsa'; + break; + case 'EC': + asymmetricKeyType = 'ec'; + break; + case 'OKP': { + if (key.crv === 'Ed25519') { + asymmetricKeyType = 'ed25519'; + break; + } + if (key.crv === 'Ed448') { + asymmetricKeyType = 'ed448'; + break; + } + throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448'); + } + default: + throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC'); + } + } + let options; + switch (alg) { + case 'EdDSA': + if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); + } + break; + case 'RS256': + case 'RS384': + case 'RS512': + if (asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + (0, check_key_length_js_1.default)(key, alg); + break; + case 'PS256': + case 'PS384': + case 'PS512': + if (asymmetricKeyType === 'rsa-pss') { + const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails; + const length = parseInt(alg.slice(-3), 10); + if (hashAlgorithm !== undefined && + (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { + throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); + } + if (saltLength !== undefined && saltLength > length >> 3) { + throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); + } + } + else if (asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); + } + (0, check_key_length_js_1.default)(key, alg); + options = { + padding: node_crypto_1.constants.RSA_PKCS1_PSS_PADDING, + saltLength: node_crypto_1.constants.RSA_PSS_SALTLEN_DIGEST, + }; + break; + case 'ES256': + case 'ES256K': + case 'ES384': + case 'ES512': { + if (asymmetricKeyType !== 'ec') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); + } + const actual = (0, get_named_curve_js_1.default)(key); + const expected = ecCurveAlgMap.get(alg); + if (actual !== expected) { + throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); + } + options = { dsaEncoding: 'ieee-p1363' }; + break; + } + default: + throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); + } + if (isJWK) { + return { format: 'jwk', key, ...options }; + } + return options ? { ...options, key } : key; } -Minimatch.prototype.match = function match (f, partial) { - if (typeof partial === 'undefined') partial = this.partial - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - if (f === '/' && partial) return true +/***/ }), - var options = this.options +/***/ 51276: +/***/ ((__unused_webpack_module, exports) => { - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } +"use strict"; - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = {}; - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - var set = this.set - this.debug(this.pattern, 'set', set) +/***/ }), - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } +/***/ 52741: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decrypt = exports.encrypt = void 0; +const node_util_1 = __nccwpck_require__(57975); +const node_crypto_1 = __nccwpck_require__(77598); +const random_js_1 = __nccwpck_require__(23376); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const base64url_js_1 = __nccwpck_require__(12635); +const aeskw_js_1 = __nccwpck_require__(76202); +const check_p2s_js_1 = __nccwpck_require__(88040); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const pbkdf2 = (0, node_util_1.promisify)(node_crypto_1.pbkdf2); +function getPassword(key, alg) { + if ((0, is_key_object_js_1.default)(key)) { + return key.export(); } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + if (key instanceof Uint8Array) { + return key; } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey'); + return node_crypto_1.KeyObject.from(key).export(); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); } +const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => { + (0, check_p2s_js_1.default)(p2s); + const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10) >> 3; + const password = getPassword(key, alg); + const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); + const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek); + return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) }; +}; +exports.encrypt = encrypt; +const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { + (0, check_p2s_js_1.default)(p2s); + const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); + const keylen = parseInt(alg.slice(13, 16), 10) >> 3; + const password = getPassword(key, alg); + const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); + return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey); +}; +exports.decrypt = decrypt; -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +/***/ }), - this.debug('matchOne', file.length, pattern.length) +/***/ 23376: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] +"use strict"; - this.debug(pattern, p, f) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = void 0; +var node_crypto_1 = __nccwpck_require__(77598); +Object.defineProperty(exports, "default", ({ enumerable: true, get: function () { return node_crypto_1.randomFillSync; } })); - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) +/***/ }), - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } +/***/ 61129: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] +"use strict"; - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decrypt = exports.encrypt = void 0; +const node_crypto_1 = __nccwpck_require__(77598); +const node_util_1 = __nccwpck_require__(57975); +const check_key_length_js_1 = __nccwpck_require__(65142); +const webcrypto_js_1 = __nccwpck_require__(59044); +const crypto_key_js_1 = __nccwpck_require__(26319); +const is_key_object_js_1 = __nccwpck_require__(68685); +const invalid_key_input_js_1 = __nccwpck_require__(16632); +const is_key_like_js_1 = __nccwpck_require__(7433); +const checkKey = (key, alg) => { + if (key.asymmetricKeyType !== 'rsa') { + throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); + } + (0, check_key_length_js_1.default)(key, alg); +}; +const RSA1_5 = (0, node_util_1.deprecate)(() => node_crypto_1.constants.RSA_PKCS1_PADDING, 'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'); +const resolvePadding = (alg) => { + switch (alg) { + case 'RSA-OAEP': + case 'RSA-OAEP-256': + case 'RSA-OAEP-384': + case 'RSA-OAEP-512': + return node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING; + case 'RSA1_5': + return RSA1_5(); + default: + return undefined; + } +}; +const resolveOaepHash = (alg) => { + switch (alg) { + case 'RSA-OAEP': + return 'sha1'; + case 'RSA-OAEP-256': + return 'sha256'; + case 'RSA-OAEP-384': + return 'sha384'; + case 'RSA-OAEP-512': + return 'sha512'; + default: + return undefined; + } +}; +function ensureKeyObject(key, alg, ...usages) { + if ((0, is_key_object_js_1.default)(key)) { + return key; + } + if ((0, webcrypto_js_1.isCryptoKey)(key)) { + (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages); + return node_crypto_1.KeyObject.from(key); + } + throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); +} +const encrypt = (alg, key, cek) => { + const padding = resolvePadding(alg); + const oaepHash = resolveOaepHash(alg); + const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); + checkKey(keyObject, alg); + return (0, node_crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek); +}; +exports.encrypt = encrypt; +const decrypt = (alg, key, encryptedKey) => { + const padding = resolvePadding(alg); + const oaepHash = resolveOaepHash(alg); + const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); + checkKey(keyObject, alg); + return (0, node_crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey); +}; +exports.decrypt = decrypt; - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } +/***/ }), - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - /* istanbul ignore if */ - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } +/***/ 95527: +/***/ ((__unused_webpack_module, exports) => { - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - hit = f === p - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } +"use strict"; - if (!hit) return false - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = 'node:crypto'; - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else /* istanbul ignore else */ if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - return (fi === fl - 1) && (file[fi] === '') - } +/***/ }), - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') -} +/***/ 26966: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} +"use strict"; -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const crypto = __nccwpck_require__(77598); +const node_util_1 = __nccwpck_require__(57975); +const dsa_digest_js_1 = __nccwpck_require__(74510); +const hmac_digest_js_1 = __nccwpck_require__(57399); +const node_key_js_1 = __nccwpck_require__(70363); +const get_sign_verify_key_js_1 = __nccwpck_require__(80723); +const oneShotSign = (0, node_util_1.promisify)(crypto.sign); +const sign = async (alg, key, data) => { + const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign'); + if (alg.startsWith('HS')) { + const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), k); + hmac.update(data); + return hmac.digest(); + } + return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, k)); +}; +exports["default"] = sign; /***/ }), -/***/ 11757: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 39106: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const { Minipass } = __nccwpck_require__(78275) -const _data = Symbol('_data') -const _length = Symbol('_length') -class Collect extends Minipass { - constructor (options) { - super(options) - this[_data] = [] - this[_length] = 0 - } - write (chunk, encoding, cb) { - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +"use strict"; - if (!encoding) - encoding = 'utf8' +Object.defineProperty(exports, "__esModule", ({ value: true })); +const node_crypto_1 = __nccwpck_require__(77598); +const timingSafeEqual = node_crypto_1.timingSafeEqual; +exports["default"] = timingSafeEqual; - const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) - this[_data].push(c) - this[_length] += c.length - if (cb) - cb() - return true - } - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - const result = Buffer.concat(this[_data], this[_length]) - super.write(result) - return super.end(cb) - } -} -module.exports = Collect -// it would be possible to DRY this a bit by doing something like -// this.collector = new Collect() and listening on its data event, -// but it's not much code, and we may as well save the extra obj -class CollectPassThrough extends Minipass { - constructor (options) { - super(options) - this[_data] = [] - this[_length] = 0 - } - write (chunk, encoding, cb) { - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +/***/ }), - if (!encoding) - encoding = 'utf8' +/***/ 11242: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) - this[_data].push(c) - this[_length] += c.length - return super.write(chunk, encoding, cb) - } - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - const result = Buffer.concat(this[_data], this[_length]) - this.emit('collect', result) - return super.end(cb) - } -} -module.exports.PassThrough = CollectPassThrough +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const crypto = __nccwpck_require__(77598); +const node_util_1 = __nccwpck_require__(57975); +const dsa_digest_js_1 = __nccwpck_require__(74510); +const node_key_js_1 = __nccwpck_require__(70363); +const sign_js_1 = __nccwpck_require__(26966); +const get_sign_verify_key_js_1 = __nccwpck_require__(80723); +const oneShotVerify = (0, node_util_1.promisify)(crypto.verify); +const verify = async (alg, key, signature, data) => { + const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify'); + if (alg.startsWith('HS')) { + const expected = await (0, sign_js_1.default)(alg, k, data); + const actual = signature; + try { + return crypto.timingSafeEqual(actual, expected); + } + catch { + return false; + } + } + const algorithm = (0, dsa_digest_js_1.default)(alg); + const keyInput = (0, node_key_js_1.default)(alg, k); + try { + return await oneShotVerify(algorithm, data, keyInput, signature); + } + catch { + return false; + } +}; +exports["default"] = verify; /***/ }), -/***/ 57442: -/***/ ((module) => { +/***/ 59044: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -class AbortError extends Error { - constructor (message) { - super(message) - this.code = 'FETCH_ABORTED' - this.type = 'aborted' - Error.captureStackTrace(this, this.constructor) - } - - get name () { - return 'AbortError' - } - - // don't allow name to be overridden, but don't throw either - set name (s) {} -} -module.exports = AbortError +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isCryptoKey = void 0; +const crypto = __nccwpck_require__(77598); +const util = __nccwpck_require__(57975); +const webcrypto = crypto.webcrypto; +exports["default"] = webcrypto; +const isCryptoKey = (key) => util.types.isCryptoKey(key); +exports.isCryptoKey = isCryptoKey; /***/ }), -/***/ 21256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 78305: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const { Minipass } = __nccwpck_require__(78275) -const TYPE = Symbol('type') -const BUFFER = Symbol('buffer') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decode = exports.encode = void 0; +const base64url = __nccwpck_require__(12635); +exports.encode = base64url.encode; +exports.decode = base64url.decode; -class Blob { - constructor (blobParts, options) { - this[TYPE] = '' - const buffers = [] - let size = 0 +/***/ }), - if (blobParts) { - const a = blobParts - const length = Number(a.length) - for (let i = 0; i < length; i++) { - const element = a[i] - const buffer = element instanceof Buffer ? element - : ArrayBuffer.isView(element) - ? Buffer.from(element.buffer, element.byteOffset, element.byteLength) - : element instanceof ArrayBuffer ? Buffer.from(element) - : element instanceof Blob ? element[BUFFER] - : typeof element === 'string' ? Buffer.from(element) - : Buffer.from(String(element)) - size += buffer.length - buffers.push(buffer) - } - } +/***/ 60002: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this[BUFFER] = Buffer.concat(buffers, size) +"use strict"; - const type = options && options.type !== undefined - && String(options.type).toLowerCase() - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decodeJwt = decodeJwt; +const base64url_js_1 = __nccwpck_require__(78305); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const is_object_js_1 = __nccwpck_require__(92242); +const errors_js_1 = __nccwpck_require__(15974); +function decodeJwt(jwt) { + if (typeof jwt !== 'string') + throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); + const { 1: payload, length } = jwt.split('.'); + if (length === 5) + throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); + if (length !== 3) + throw new errors_js_1.JWTInvalid('Invalid JWT'); + if (!payload) + throw new errors_js_1.JWTInvalid('JWTs must contain a payload'); + let decoded; + try { + decoded = (0, base64url_js_1.decode)(payload); } - } + catch { + throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload'); + } + let result; + try { + result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded)); + } + catch { + throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON'); + } + if (!(0, is_object_js_1.default)(result)) + throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set'); + return result; +} - get size () { - return this[BUFFER].length - } - get type () { - return this[TYPE] - } +/***/ }), - text () { - return Promise.resolve(this[BUFFER].toString()) - } +/***/ 14704: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - arrayBuffer () { - const buf = this[BUFFER] - const off = buf.byteOffset - const len = buf.byteLength - const ab = buf.buffer.slice(off, off + len) - return Promise.resolve(ab) - } +"use strict"; - stream () { - return new Minipass().end(this[BUFFER]) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.decodeProtectedHeader = decodeProtectedHeader; +const base64url_js_1 = __nccwpck_require__(78305); +const buffer_utils_js_1 = __nccwpck_require__(45734); +const is_object_js_1 = __nccwpck_require__(92242); +function decodeProtectedHeader(token) { + let protectedB64u; + if (typeof token === 'string') { + const parts = token.split('.'); + if (parts.length === 3 || parts.length === 5) { + ; + [protectedB64u] = parts; + } + } + else if (typeof token === 'object' && token) { + if ('protected' in token) { + protectedB64u = token.protected; + } + else { + throw new TypeError('Token does not contain a Protected Header'); + } + } + try { + if (typeof protectedB64u !== 'string' || !protectedB64u) { + throw new Error(); + } + const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u))); + if (!(0, is_object_js_1.default)(result)) { + throw new Error(); + } + return result; + } + catch { + throw new TypeError('Invalid Token or Protected Header formatting'); + } +} - slice (start, end, type) { - const size = this.size - const relativeStart = start === undefined ? 0 - : start < 0 ? Math.max(size + start, 0) - : Math.min(start, size) - const relativeEnd = end === undefined ? size - : end < 0 ? Math.max(size + end, 0) - : Math.min(end, size) - const span = Math.max(relativeEnd - relativeStart, 0) - const buffer = this[BUFFER] - const slicedBuffer = buffer.slice( - relativeStart, - relativeStart + span - ) - const blob = new Blob([], { type }) - blob[BUFFER] = slicedBuffer - return blob - } +/***/ }), - get [Symbol.toStringTag] () { - return 'Blob' - } +/***/ 15974: +/***/ ((__unused_webpack_module, exports) => { - static get BUFFER () { - return BUFFER - } +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0; +class JOSEError extends Error { + static code = 'ERR_JOSE_GENERIC'; + code = 'ERR_JOSE_GENERIC'; + constructor(message, options) { + super(message, options); + this.name = this.constructor.name; + Error.captureStackTrace?.(this, this.constructor); + } +} +exports.JOSEError = JOSEError; +class JWTClaimValidationFailed extends JOSEError { + static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; + claim; + reason; + payload; + constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { + super(message, { cause: { claim, reason, payload } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +} +exports.JWTClaimValidationFailed = JWTClaimValidationFailed; +class JWTExpired extends JOSEError { + static code = 'ERR_JWT_EXPIRED'; + code = 'ERR_JWT_EXPIRED'; + claim; + reason; + payload; + constructor(message, payload, claim = 'unspecified', reason = 'unspecified') { + super(message, { cause: { claim, reason, payload } }); + this.claim = claim; + this.reason = reason; + this.payload = payload; + } +} +exports.JWTExpired = JWTExpired; +class JOSEAlgNotAllowed extends JOSEError { + static code = 'ERR_JOSE_ALG_NOT_ALLOWED'; + code = 'ERR_JOSE_ALG_NOT_ALLOWED'; +} +exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed; +class JOSENotSupported extends JOSEError { + static code = 'ERR_JOSE_NOT_SUPPORTED'; + code = 'ERR_JOSE_NOT_SUPPORTED'; +} +exports.JOSENotSupported = JOSENotSupported; +class JWEDecryptionFailed extends JOSEError { + static code = 'ERR_JWE_DECRYPTION_FAILED'; + code = 'ERR_JWE_DECRYPTION_FAILED'; + constructor(message = 'decryption operation failed', options) { + super(message, options); + } +} +exports.JWEDecryptionFailed = JWEDecryptionFailed; +class JWEInvalid extends JOSEError { + static code = 'ERR_JWE_INVALID'; + code = 'ERR_JWE_INVALID'; +} +exports.JWEInvalid = JWEInvalid; +class JWSInvalid extends JOSEError { + static code = 'ERR_JWS_INVALID'; + code = 'ERR_JWS_INVALID'; +} +exports.JWSInvalid = JWSInvalid; +class JWTInvalid extends JOSEError { + static code = 'ERR_JWT_INVALID'; + code = 'ERR_JWT_INVALID'; +} +exports.JWTInvalid = JWTInvalid; +class JWKInvalid extends JOSEError { + static code = 'ERR_JWK_INVALID'; + code = 'ERR_JWK_INVALID'; +} +exports.JWKInvalid = JWKInvalid; +class JWKSInvalid extends JOSEError { + static code = 'ERR_JWKS_INVALID'; + code = 'ERR_JWKS_INVALID'; } - -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, -}) - -module.exports = Blob +exports.JWKSInvalid = JWKSInvalid; +class JWKSNoMatchingKey extends JOSEError { + static code = 'ERR_JWKS_NO_MATCHING_KEY'; + code = 'ERR_JWKS_NO_MATCHING_KEY'; + constructor(message = 'no applicable key found in the JSON Web Key Set', options) { + super(message, options); + } +} +exports.JWKSNoMatchingKey = JWKSNoMatchingKey; +class JWKSMultipleMatchingKeys extends JOSEError { + [Symbol.asyncIterator]; + static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; + constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) { + super(message, options); + } +} +exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys; +class JWKSTimeout extends JOSEError { + static code = 'ERR_JWKS_TIMEOUT'; + code = 'ERR_JWKS_TIMEOUT'; + constructor(message = 'request timed out', options) { + super(message, options); + } +} +exports.JWKSTimeout = JWKSTimeout; +class JWSSignatureVerificationFailed extends JOSEError { + static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; + constructor(message = 'signature verification failed', options) { + super(message, options); + } +} +exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed; /***/ }), -/***/ 28515: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 25021: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const { Minipass } = __nccwpck_require__(78275) -const MinipassSized = __nccwpck_require__(48484) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const runtime_js_1 = __nccwpck_require__(95527); +exports["default"] = runtime_js_1.default; -const Blob = __nccwpck_require__(21256) -const { BUFFER } = Blob -const FetchError = __nccwpck_require__(22644) -// optional dependency on 'encoding' -let convert -try { - convert = (__nccwpck_require__(24056)/* .convert */ .C) -} catch (e) { - // defer error until textConverted is called -} +/***/ }), -const INTERNALS = Symbol('Body internals') -const CONSUME_BODY = Symbol('consumeBody') +/***/ 95947: +/***/ (function(module, exports) { -class Body { - constructor (bodyArg, options = {}) { - const { size = 0, timeout = 0 } = options - const body = bodyArg === undefined || bodyArg === null ? null - : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString()) - : isBlob(bodyArg) ? bodyArg - : Buffer.isBuffer(bodyArg) ? bodyArg - : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]' - ? Buffer.from(bodyArg) - : ArrayBuffer.isView(bodyArg) - ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength) - : Minipass.isStream(bodyArg) ? bodyArg - : Buffer.from(String(bodyArg)) +(function(){ - this[INTERNALS] = { - body, - disturbed: false, - error: null, - } + // Copyright (c) 2005 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. - this.size = size - this.timeout = timeout + // Basic JavaScript BN library - subset useful for RSA encryption. - if (Minipass.isStream(body)) { - body.on('error', er => { - const error = er.name === 'AbortError' ? er - : new FetchError(`Invalid response while trying to fetch ${ - this.url}: ${er.message}`, 'system', er) - this[INTERNALS].error = error - }) - } - } + // Bits per digit + var dbits; - get body () { - return this[INTERNALS].body - } + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = ((canary&0xffffff)==0xefcafe); - get bodyUsed () { - return this[INTERNALS].disturbed - } + // (public) Constructor + function BigInteger(a,b,c) { + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); + } - arrayBuffer () { - return this[CONSUME_BODY]().then(buf => - buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)) - } + // return new, unset BigInteger + function nbi() { return new BigInteger(null); } - blob () { - const ct = this.headers && this.headers.get('content-type') || '' - return this[CONSUME_BODY]().then(buf => Object.assign( - new Blob([], { type: ct.toLowerCase() }), - { [BUFFER]: buf } - )) - } + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. - async json () { - const buf = await this[CONSUME_BODY]() - try { - return JSON.parse(buf.toString()) - } catch (er) { - throw new FetchError( - `invalid json response body at ${this.url} reason: ${er.message}`, - 'invalid-json' - ) + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this[i++]+w[j]+c; + c = Math.floor(v/0x4000000); + w[j++] = v&0x3ffffff; + } + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + function am2(i,x,w,j,c,n) { + var xl = x&0x7fff, xh = x>>15; + while(--n >= 0) { + var l = this[i]&0x7fff; + var h = this[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w[j++] = l&0x3fffffff; + } + return c; + } + // Alternately, set max digit bits to 28 since some + // browsers slow down when dealing with 32-bit numbers. + function am3(i,x,w,j,c,n) { + var xl = x&0x3fff, xh = x>>14; + while(--n >= 0) { + var l = this[i]&0x3fff; + var h = this[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w[j++] = l&0xfffffff; + } + return c; + } + var inBrowser = typeof navigator !== "undefined"; + if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; + } + else if(inBrowser && j_lm && (navigator.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; + } + else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; } - } - text () { - return this[CONSUME_BODY]().then(buf => buf.toString()) - } + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = ((1< convertBody(buf, this.headers)) - } + // Digit conversions + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + var BI_RC = new Array(); + var rr,vv; + rr = "0".charCodeAt(0); + for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; + rr = "a".charCodeAt(0); + for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; + rr = "A".charCodeAt(0); + for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - [CONSUME_BODY] () { - if (this[INTERNALS].disturbed) { - return Promise.reject(new TypeError(`body used already for: ${ - this.url}`)) + function int2char(n) { return BI_RM.charAt(n); } + function intAt(s,i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c==null)?-1:c; } - this[INTERNALS].disturbed = true - - if (this[INTERNALS].error) { - return Promise.reject(this[INTERNALS].error) + // (protected) copy this to r + function bnpCopyTo(r) { + for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; + r.t = this.t; + r.s = this.s; } - // body is null - if (this.body === null) { - return Promise.resolve(Buffer.alloc(0)) + // (protected) set from integer value x, -DV <= x < DV + function bnpFromInt(x) { + this.t = 1; + this.s = (x<0)?-1:0; + if(x > 0) this[0] = x; + else if(x < -1) this[0] = x+this.DV; + else this.t = 0; } - if (Buffer.isBuffer(this.body)) { - return Promise.resolve(this.body) + // return bigint initialized to value + function nbv(i) { var r = nbi(); r.fromInt(i); return r; } + + // (protected) set from string and radix + function bnpFromString(s,b) { + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this[this.t++] = x; + else if(sh+k > this.DB) { + this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + } + else + this[this.t-1] |= x<= this.DB) sh -= this.DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t; + } - /* istanbul ignore if: should never happen */ - if (!Minipass.isStream(upstream)) { - return Promise.resolve(Buffer.alloc(0)) + // (public) return string representation in given radix + function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(b); + var k; + if(b == 16) k = 4; + else if(b == 8) k = 3; + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else return this.toRadix(b); + var km = (1< 0) { + if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this[i]&((1<>(p+=this.DB-k); + } + else { + d = (this[i]>>(p-=k))&km; + if(p <= 0) { p += this.DB; --i; } + } + if(d > 0) m = true; + if(m) r += int2char(d); + } + } + return m?r:"0"; } - const stream = this.size && upstream instanceof MinipassSized ? upstream - : !this.size && upstream instanceof Minipass && - !(upstream instanceof MinipassSized) ? upstream - : this.size ? new MinipassSized({ size: this.size }) - : new Minipass() + // (public) -this + function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; } - // allow timeout on slow response body, but only if the stream is still writable. this - // makes the timeout center on the socket stream from lib/index.js rather than the - // intermediary minipass stream we create to receive the data - const resTimeout = this.timeout && stream.writable ? setTimeout(() => { - stream.emit('error', new FetchError( - `Response timeout while trying to fetch ${ - this.url} (over ${this.timeout}ms)`, 'body-timeout')) - }, this.timeout) : null + // (public) |this| + function bnAbs() { return (this.s<0)?this.negate():this; } - // do not keep the process open just for this timeout, even - // though we expect it'll get cleared eventually. - if (resTimeout && resTimeout.unref) { - resTimeout.unref() + // (public) return + if this > a, - if this < a, 0 if equal + function bnCompareTo(a) { + var r = this.s-a.s; + if(r != 0) return r; + var i = this.t; + r = i-a.t; + if(r != 0) return (this.s<0)?-r:r; + while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; + return 0; } - // do the pipe in the promise, because the pipe() can send too much - // data through right away and upset the MP Sized object - return new Promise((resolve) => { - // if the stream is some other kind of stream, then pipe through a MP - // so we can collect it more easily. - if (stream !== upstream) { - upstream.on('error', er => stream.emit('error', er)) - upstream.pipe(stream) - } - resolve() - }).then(() => stream.concat()).then(buf => { - clearTimeout(resTimeout) - return buf - }).catch(er => { - clearTimeout(resTimeout) - // request was aborted, reject with this Error - if (er.name === 'AbortError' || er.name === 'FetchError') { - throw er - } else if (er.name === 'RangeError') { - throw new FetchError(`Could not create Buffer from response body for ${ - this.url}: ${er.message}`, 'system', er) - } else { - // other errors, such as incorrect content-encoding or content-length - throw new FetchError(`Invalid response body while trying to fetch ${ - this.url}: ${er.message}`, 'system', er) - } - }) - } - - static clone (instance) { - if (instance.bodyUsed) { - throw new Error('cannot clone body after it is used') + // returns bit length of the integer x + function nbits(x) { + var r = 1, t; + if((t=x>>>16) != 0) { x = t; r += 16; } + if((t=x>>8) != 0) { x = t; r += 8; } + if((t=x>>4) != 0) { x = t; r += 4; } + if((t=x>>2) != 0) { x = t; r += 2; } + if((t=x>>1) != 0) { x = t; r += 1; } + return r; } - const body = instance.body - - // check that body is a stream and not form-data object - // NB: can't clone the form-data object without having it as a dependency - if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') { - // create a dedicated tee stream so that we don't lose data - // potentially sitting in the body stream's buffer by writing it - // immediately to p1 and not having it for p2. - const tee = new Minipass() - const p1 = new Minipass() - const p2 = new Minipass() - tee.on('error', er => { - p1.emit('error', er) - p2.emit('error', er) - }) - body.on('error', er => tee.emit('error', er)) - tee.pipe(p1) - tee.pipe(p2) - body.pipe(tee) - // set instance body to one fork, return the other - instance[INTERNALS].body = p1 - return p2 - } else { - return instance.body + // (public) return the number of bits in "this" + function bnBitLength() { + if(this.t <= 0) return 0; + return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM)); } - } - static extractContentType (body) { - return body === null || body === undefined ? null - : typeof body === 'string' ? 'text/plain;charset=UTF-8' - : isURLSearchParams(body) - ? 'application/x-www-form-urlencoded;charset=UTF-8' - : isBlob(body) ? body.type || null - : Buffer.isBuffer(body) ? null - : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null - : ArrayBuffer.isView(body) ? null - : typeof body.getBoundary === 'function' - ? `multipart/form-data;boundary=${body.getBoundary()}` - : Minipass.isStream(body) ? null - : 'text/plain;charset=UTF-8' - } + // (protected) r = this << n*DB + function bnpDLShiftTo(n,r) { + var i; + for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; + for(i = n-1; i >= 0; --i) r[i] = 0; + r.t = this.t+n; + r.s = this.s; + } - static getTotalBytes (instance) { - const { body } = instance - return (body === null || body === undefined) ? 0 - : isBlob(body) ? body.size - : Buffer.isBuffer(body) ? body.length - : body && typeof body.getLengthSync === 'function' && ( - // detect form data input from form-data module - body._lengthRetrievers && - /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x - body.hasKnownLength && body.hasKnownLength()) // 2.x - ? body.getLengthSync() - : null - } + // (protected) r = this >> n*DB + function bnpDRShiftTo(n,r) { + for(var i = n; i < this.t; ++i) r[i-n] = this[i]; + r.t = Math.max(this.t-n,0); + r.s = this.s; + } - static writeToStream (dest, instance) { - const { body } = instance + // (protected) r = this << n + function bnpLShiftTo(n,r) { + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<= 0; --i) { + r[i+ds+1] = (this[i]>>cbs)|c; + c = (this[i]&bm)<= 0; --i) r[i] = 0; + r[ds] = c; + r.t = this.t+ds+1; + r.s = this.s; + r.clamp(); + } - if (body === null || body === undefined) { - dest.end() - } else if (Buffer.isBuffer(body) || typeof body === 'string') { - dest.end(body) - } else { - // body is stream or blob - const stream = isBlob(body) ? body.stream() : body - stream.on('error', er => dest.emit('error', er)).pipe(dest) + // (protected) r = this >> n + function bnpRShiftTo(n,r) { + r.s = this.s; + var ds = Math.floor(n/this.DB); + if(ds >= this.t) { r.t = 0; return; } + var bs = n%this.DB; + var cbs = this.DB-bs; + var bm = (1<>bs; + for(var i = ds+1; i < this.t; ++i) { + r[i-ds-1] |= (this[i]&bm)<>bs; + } + if(bs > 0) r[this.t-ds-1] |= (this.s&bm)< - // Duck-typing as a necessary condition. - (typeof obj !== 'object' || - typeof obj.append !== 'function' || - typeof obj.delete !== 'function' || - typeof obj.get !== 'function' || - typeof obj.getAll !== 'function' || - typeof obj.has !== 'function' || - typeof obj.set !== 'function') ? false - // Brand-checking and more duck-typing as optional condition. - : obj.constructor.name === 'URLSearchParams' || - Object.prototype.toString.call(obj) === '[object URLSearchParams]' || - typeof obj.sort === 'function' - -const isBlob = obj => - typeof obj === 'object' && - typeof obj.arrayBuffer === 'function' && - typeof obj.type === 'string' && - typeof obj.stream === 'function' && - typeof obj.constructor === 'function' && - typeof obj.constructor.name === 'string' && - /^(Blob|File)$/.test(obj.constructor.name) && - /^(Blob|File)$/.test(obj[Symbol.toStringTag]) + // (protected) r = this - a + function bnpSubTo(a,r) { + var i = 0, c = 0, m = Math.min(a.t,this.t); + while(i < m) { + c += this[i]-a[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c -= a[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r[i++] = this.DV+c; + else if(c > 0) r[i++] = c; + r.t = i; + r.clamp(); + } -const convertBody = (buffer, headers) => { - /* istanbul ignore if */ - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function') - } + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + function bnpMultiplyTo(a,r) { + var x = this.abs(), y = a.abs(); + var i = x.t; + r.t = i+y.t; + while(--i >= 0) r[i] = 0; + for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); + r.s = 0; + r.clamp(); + if(this.s != a.s) BigInteger.ZERO.subTo(r,r); + } - const ct = headers && headers.get('content-type') - let charset = 'utf-8' - let res + // (protected) r = this^2, r != this (HAC 14.16) + function bnpSquareTo(r) { + var x = this.abs(); + var i = r.t = 2*x.t; + while(--i >= 0) r[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x[i],r,2*i,0,1); + if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { + r[i+x.t] -= x.DV; + r[i+x.t+1] = 1; + } + } + if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); + r.s = 0; + r.clamp(); + } - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct) - } + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + function bnpDivRemTo(m,q,r) { + var pm = m.abs(); + if(pm.t <= 0) return; + var pt = this.abs(); + if(pt.t < pm.t) { + if(q != null) q.fromInt(0); + if(r != null) this.copyTo(r); + return; + } + if(r == null) r = nbi(); + var y = nbi(), ts = this.s, ms = m.s; + var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus + if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } + else { pm.copyTo(y); pt.copyTo(r); } + var ys = y.t; + var y0 = y[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y[ys-2]>>this.F2:0); + var d1 = this.FV/yt, d2 = (1<= 0) { + r[r.t++] = 1; + r.subTo(t,r); + } + BigInteger.ONE.dlShiftTo(ys,t); + t.subTo(y,y); // "negative" y so we can replace sub with am later + while(y.t < ys) y[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2); + if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r[i] < --qd) r.subTo(t,r); + } + } + if(q != null) { + r.drShiftTo(ys,q); + if(ts != ms) BigInteger.ZERO.subTo(q,q); + } + r.t = ys; + r.clamp(); + if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder + if(ts < 0) BigInteger.ZERO.subTo(r,r); + } - // no charset in content type, peek at response body for at most 1024 bytes - const str = buffer.slice(0, 1024).toString() + // (public) this mod a + function bnMod(a) { + var r = nbi(); + this.abs().divRemTo(a,null,r); + if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); + return r; + } - // html5 - if (!res && str) { - res = /= 0) return x.mod(this.m); + else return x; + } + function cRevert(x) { return x; } + function cReduce(x) { x.divRemTo(this.m,null,x); } + function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } - // html4 - if (!res && str) { - res = /0)?this.DV-y:-y; } - if (res) { - res = /charset=(.*)/i.exec(res.pop()) + // Montgomery reduction + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp&0x7fff; + this.mph = this.mp>>15; + this.um = (1<<(m.DB-15))-1; + this.mt2 = 2*m.t; } - } - // xml - if (!res && str) { - res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str) - } + // xR mod m + function montConvert(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t,r); + r.divRemTo(this.m,null,r); + if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r); + return r; + } - // found charset - if (res) { - charset = res.pop() + // x/R mod m + function montRevert(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } - // prevent decode issues when sites use incorrect encoding - // ref: https://hsivonen.fi/encoding-menu/ - if (charset === 'gb2312' || charset === 'gbk') { - charset = 'gb18030' + // x = x/R mod m (HAC 14.32) + function montReduce(x) { + while(x.t <= this.mt2) // pad x so am has enough room later + x[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM; + // use am to combine the multiply-shift-add into one call + j = i+this.m.t; + x[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; } + } + x.clamp(); + x.drShiftTo(this.m.t,x); + if(x.compareTo(this.m) >= 0) x.subTo(this.m,x); } - } - // turn raw buffers into a single utf-8 buffer - return convert( - buffer, - 'UTF-8', - charset - ).toString() -} + // r = "x^2/R mod m"; x != r + function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); } -module.exports = Body + // r = "xy/R mod m"; x,y != r + function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + Montgomery.prototype.convert = montConvert; + Montgomery.prototype.revert = montRevert; + Montgomery.prototype.reduce = montReduce; + Montgomery.prototype.mulTo = montMulTo; + Montgomery.prototype.sqrTo = montSqrTo; -/***/ }), + // (protected) true iff this is even + function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } -/***/ 22644: -/***/ ((module) => { + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); + } -"use strict"; + // (public) this^e % m, 0 <= e < 2^32 + function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); + } -class FetchError extends Error { - constructor (message, type, systemError) { - super(message) - this.code = 'FETCH_ERROR' + // protected + BigInteger.prototype.copyTo = bnpCopyTo; + BigInteger.prototype.fromInt = bnpFromInt; + BigInteger.prototype.fromString = bnpFromString; + BigInteger.prototype.clamp = bnpClamp; + BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + BigInteger.prototype.drShiftTo = bnpDRShiftTo; + BigInteger.prototype.lShiftTo = bnpLShiftTo; + BigInteger.prototype.rShiftTo = bnpRShiftTo; + BigInteger.prototype.subTo = bnpSubTo; + BigInteger.prototype.multiplyTo = bnpMultiplyTo; + BigInteger.prototype.squareTo = bnpSquareTo; + BigInteger.prototype.divRemTo = bnpDivRemTo; + BigInteger.prototype.invDigit = bnpInvDigit; + BigInteger.prototype.isEven = bnpIsEven; + BigInteger.prototype.exp = bnpExp; - // pick up code, expected, path, ... - if (systemError) { - Object.assign(this, systemError) - } + // public + BigInteger.prototype.toString = bnToString; + BigInteger.prototype.negate = bnNegate; + BigInteger.prototype.abs = bnAbs; + BigInteger.prototype.compareTo = bnCompareTo; + BigInteger.prototype.bitLength = bnBitLength; + BigInteger.prototype.mod = bnMod; + BigInteger.prototype.modPowInt = bnModPowInt; - this.errno = this.code + // "constants" + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); - // override anything the system error might've clobbered - this.type = this.code === 'EBADSIZE' && this.found > this.expect - ? 'max-size' : type - this.message = message - Error.captureStackTrace(this, this.constructor) - } + // Copyright (c) 2005-2009 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. - get name () { - return 'FetchError' - } + // Extended JavaScript BN functions, required for RSA private ops. - // don't allow name to be overwritten - set name (n) {} + // Version 1.1: new BigInteger("0", 10) returns "proper" zero + // Version 1.2: square() API, isProbablePrime fix - get [Symbol.toStringTag] () { - return 'FetchError' - } -} -module.exports = FetchError + // (public) + function bnClone() { var r = nbi(); this.copyTo(r); return r; } + // (public) return value as integer + function bnIntValue() { + if(this.s < 0) { + if(this.t == 1) return this[0]-this.DV; + else if(this.t == 0) return -1; + } + else if(this.t == 1) return this[0]; + else if(this.t == 0) return 0; + // assumes 16 < DB < 32 + return ((this[1]&((1<<(32-this.DB))-1))<>24; } -/***/ 98645: -/***/ ((module) => { + // (public) return value as short (assumes DB>=16) + function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; } -"use strict"; + // (protected) return x s.t. r^x < DV + function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } -const invalidTokenRegex = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/ -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + // (public) 0 if this == 0, 1 if this > 0 + function bnSigNum() { + if(this.s < 0) return -1; + else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0; + else return 1; + } -const validateName = name => { - name = `${name}` - if (invalidTokenRegex.test(name) || name === '') { - throw new TypeError(`${name} is not a legal HTTP header name`) - } -} + // (protected) convert to radix string + function bnpToRadix(b) { + if(b == null) b = 10; + if(this.signum() == 0 || b < 2 || b > 36) return "0"; + var cs = this.chunkSize(b); + var a = Math.pow(b,cs); + var d = nbv(a), y = nbi(), z = nbi(), r = ""; + this.divRemTo(d,y,z); + while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); + } + return z.intValue().toString(b) + r; + } -const validateValue = value => { - value = `${value}` - if (invalidHeaderCharRegex.test(value)) { - throw new TypeError(`${value} is not a legal HTTP header value`) - } -} + // (protected) convert from radix string + function bnpFromRadix(s,b) { + this.fromInt(0); + if(b == null) b = 10; + var cs = this.chunkSize(b); + var d = Math.pow(b,cs), mi = false, j = 0, w = 0; + for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } + } + if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); + } + if(mi) BigInteger.ZERO.subTo(this,this); + } -const find = (map, name) => { - name = name.toLowerCase() - for (const key in map) { - if (key.toLowerCase() === name) { - return key + // (protected) alternate constructor + function bnpFromNumber(a,b,c) { + if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } + } + else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p) + r[k++] = d|(this.s<<(this.DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this[i]&((1<>(p+=this.DB-8); + } + else { + d = (this[i]>>(p-=8))&0xff; + if(p <= 0) { p += this.DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; } } - return - } - - // no-op - if (init === undefined || init === null) { - return + return r; } - if (typeof init === 'object') { - const method = init[Symbol.iterator] - if (method !== null && method !== undefined) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable') - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = [] - for (const pair of init) { - if (typeof pair !== 'object' || - typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable') - } - const arrPair = Array.from(pair) - if (arrPair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple') - } - pairs.push(arrPair) - } + function bnEquals(a) { return(this.compareTo(a)==0); } + function bnMin(a) { return(this.compareTo(a)<0)?this:a; } + function bnMax(a) { return(this.compareTo(a)>0)?this:a; } - for (const pair of pairs) { - this.append(pair[0], pair[1]) - } - } else { - // record - for (const key of Object.keys(init)) { - this.append(key, init[key]) - } + // (protected) r = this op a (bitwise) + function bnpBitwiseTo(a,op,r) { + var i, f, m = Math.min(a.t,this.t); + for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]); + if(a.t < this.t) { + f = a.s&this.DM; + for(i = m; i < this.t; ++i) r[i] = op(this[i],f); + r.t = this.t; } - } else { - throw new TypeError('Provided initializer must be an object') + else { + f = this.s&this.DM; + for(i = m; i < a.t; ++i) r[i] = op(f,a[i]); + r.t = a.t; + } + r.s = op(this.s,a.s); + r.clamp(); } - } - get (name) { - name = `${name}` - validateName(name) - const key = find(this[MAP], name) - if (key === undefined) { - return null - } + // (public) this & a + function op_and(x,y) { return x&y; } + function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } - return this[MAP][key].join(', ') - } + // (public) this | a + function op_or(x,y) { return x|y; } + function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } - forEach (callback, thisArg = undefined) { - let pairs = getHeaders(this) - for (let i = 0; i < pairs.length; i++) { - const [name, value] = pairs[i] - callback.call(thisArg, value, name, this) - // refresh in case the callback added more headers - pairs = getHeaders(this) - } - } + // (public) this ^ a + function op_xor(x,y) { return x^y; } + function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } - set (name, value) { - name = `${name}` - value = `${value}` - validateName(name) - validateValue(value) - const key = find(this[MAP], name) - this[MAP][key !== undefined ? key : name] = [value] - } + // (public) this & ~a + function op_andnot(x,y) { return x&~y; } + function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } - append (name, value) { - name = `${name}` - value = `${value}` - validateName(name) - validateValue(value) - const key = find(this[MAP], name) - if (key !== undefined) { - this[MAP][key].push(value) - } else { - this[MAP][name] = [value] + // (public) ~this + function bnNot() { + var r = nbi(); + for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i]; + r.t = this.t; + r.s = ~this.s; + return r; } - } - - has (name) { - name = `${name}` - validateName(name) - return find(this[MAP], name) !== undefined - } - delete (name) { - name = `${name}` - validateName(name) - const key = find(this[MAP], name) - if (key !== undefined) { - delete this[MAP][key] + // (public) this << n + function bnShiftLeft(n) { + var r = nbi(); + if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); + return r; } - } - - raw () { - return this[MAP] - } - keys () { - return new HeadersIterator(this, 'key') - } + // (public) this >> n + function bnShiftRight(n) { + var r = nbi(); + if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); + return r; + } - values () { - return new HeadersIterator(this, 'value') - } + // return index of lowest 1-bit in x, x < 2^31 + function lbit(x) { + if(x == 0) return -1; + var r = 0; + if((x&0xffff) == 0) { x >>= 16; r += 16; } + if((x&0xff) == 0) { x >>= 8; r += 8; } + if((x&0xf) == 0) { x >>= 4; r += 4; } + if((x&3) == 0) { x >>= 2; r += 2; } + if((x&1) == 0) ++r; + return r; + } - [Symbol.iterator] () { - return new HeadersIterator(this, 'key+value') - } + // (public) returns index of lowest 1-bit (or -1 if none) + function bnGetLowestSetBit() { + for(var i = 0; i < this.t; ++i) + if(this[i] != 0) return i*this.DB+lbit(this[i]); + if(this.s < 0) return this.t*this.DB; + return -1; + } - entries () { - return new HeadersIterator(this, 'key+value') - } + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while(x != 0) { x &= x-1; ++r; } + return r; + } - get [Symbol.toStringTag] () { - return 'Headers' - } + // (public) return number of set bits + function bnBitCount() { + var r = 0, x = this.s&this.DM; + for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x); + return r; + } - static exportNodeCompatibleHeaders (headers) { - const obj = Object.assign(Object.create(null), headers[MAP]) + // (public) true iff nth bit is set + function bnTestBit(n) { + var j = Math.floor(n/this.DB); + if(j >= this.t) return(this.s!=0); + return((this[j]&(1<<(n%this.DB)))!=0); + } - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host') - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0] + // (protected) this op (1<>= this.DB; + } + if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this[i]; + r[i++] = c&this.DM; + c >>= this.DB; } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]] + c += this.s; + } + else { + c += this.s; + while(i < a.t) { + c += a[i]; + r[i++] = c&this.DM; + c >>= this.DB; + } + c += a.s; } + r.s = (c<0)?-1:0; + if(c > 0) r[i++] = c; + else if(c < -1) r[i++] = this.DV+c; + r.t = i; + r.clamp(); } - return headers - } -} -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true }, -}) + // (public) this + a + function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; } -const getHeaders = (headers, kind = 'key+value') => - Object.keys(headers[MAP]).sort().map( - kind === 'key' ? k => k.toLowerCase() - : kind === 'value' ? k => headers[MAP][k].join(', ') - : k => [k.toLowerCase(), headers[MAP][k].join(', ')] - ) + // (public) this - a + function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; } -const INTERNAL = Symbol('internal') + // (public) this * a + function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; } -class HeadersIterator { - constructor (target, kind) { - this[INTERNAL] = { - target, - kind, - index: 0, - } - } + // (public) this^2 + function bnSquare() { var r = nbi(); this.squareTo(r); return r; } - get [Symbol.toStringTag] () { - return 'HeadersIterator' - } + // (public) this / a + function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; } - next () { - /* istanbul ignore if: should be impossible */ - if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) { - throw new TypeError('Value of `this` is not a HeadersIterator') + // (public) this % a + function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + + // (public) [this/a,this%a] + function bnDivideAndRemainder(a) { + var q = nbi(), r = nbi(); + this.divRemTo(a,q,r); + return new Array(q,r); } - const { target, kind, index } = this[INTERNAL] - const values = getHeaders(target, kind) - const len = values.length - if (index >= len) { - return { - value: undefined, - done: true, + // (protected) this *= n, this >= 0, 1 < n < DV + function bnpDMultiply(n) { + this[this.t] = this.am(0,n-1,this,0,0,this.t); + ++this.t; + this.clamp(); + } + + // (protected) this += n << w words, this >= 0 + function bnpDAddOffset(n,w) { + if(n == 0) return; + while(this.t <= w) this[this.t++] = 0; + this[w] += n; + while(this[w] >= this.DV) { + this[w] -= this.DV; + if(++w >= this.t) this[this.t++] = 0; + ++this[w]; } } - this[INTERNAL].index++ + // A "null" reducer + function NullExp() {} + function nNop(x) { return x; } + function nMulTo(x,y,r) { x.multiplyTo(y,r); } + function nSqrTo(x,r) { x.squareTo(r); } - return { value: values[index], done: false } - } -} + NullExp.prototype.convert = nNop; + NullExp.prototype.revert = nNop; + NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.sqrTo = nSqrTo; -// manually extend because 'extends' requires a ctor -Object.setPrototypeOf(HeadersIterator.prototype, - Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))) + // (public) this^e + function bnPow(e) { return this.exp(e,new NullExp()); } -module.exports = Headers + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + function bnpMultiplyLowerTo(a,n,r) { + var i = Math.min(this.t+a.t,n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while(i > 0) r[--i] = 0; + var j; + for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t); + for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i); + r.clamp(); + } + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + function bnpMultiplyUpperTo(a,n,r) { + --n; + var i = r.t = this.t+a.t-n; + r.s = 0; // assumes a,this >= 0 + while(--i >= 0) r[i] = 0; + for(i = Math.max(n-this.t,0); i < a.t; ++i) + r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n); + r.clamp(); + r.drShiftTo(1,r); + } -/***/ }), + // Barrett modular reduction + function Barrett(m) { + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2*m.t,this.r2); + this.mu = this.r2.divide(m); + this.m = m; + } -/***/ 88483: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function barrettConvert(x) { + if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); + else if(x.compareTo(this.m) < 0) return x; + else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } + } -"use strict"; + function barrettRevert(x) { return x; } -const { URL } = __nccwpck_require__(87016) -const http = __nccwpck_require__(58611) -const https = __nccwpck_require__(65692) -const zlib = __nccwpck_require__(37119) -const { Minipass } = __nccwpck_require__(78275) + // x = x mod m (HAC 14.42) + function barrettReduce(x) { + x.drShiftTo(this.m.t-1,this.r2); + if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } + this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); + this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); + while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); + x.subTo(this.r2,x); + while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); + } -const Body = __nccwpck_require__(28515) -const { writeToStream, getTotalBytes } = Body -const Response = __nccwpck_require__(43852) -const Headers = __nccwpck_require__(98645) -const { createHeadersLenient } = Headers -const Request = __nccwpck_require__(99586) -const { getNodeRequestOptions } = Request -const FetchError = __nccwpck_require__(22644) -const AbortError = __nccwpck_require__(57442) + // r = x^2 mod m; x != r + function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } -// XXX this should really be split up and unit-ized for easier testing -// and better DRY implementation of data/http request aborting -const fetch = async (url, opts) => { - if (/^data:/.test(url)) { - const request = new Request(url, opts) - // delay 1 promise tick so that the consumer can abort right away - return Promise.resolve().then(() => new Promise((resolve, reject) => { - let type, data - try { - const { pathname, search } = new URL(url) - const split = pathname.split(',') - if (split.length < 2) { - throw new Error('invalid data: URI') + // r = x*y mod m; x,y != r + function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + + Barrett.prototype.convert = barrettConvert; + Barrett.prototype.revert = barrettRevert; + Barrett.prototype.reduce = barrettReduce; + Barrett.prototype.mulTo = barrettMulTo; + Barrett.prototype.sqrTo = barrettSqrTo; + + // (public) this^e % m (HAC 14.85) + function bnModPow(e,m) { + var i = e.bitLength(), k, r = nbv(1), z; + if(i <= 0) return r; + else if(i < 18) k = 1; + else if(i < 48) k = 3; + else if(i < 144) k = 4; + else if(i < 768) k = 5; + else k = 6; + if(i < 8) + z = new Classic(m); + else if(m.isEven()) + z = new Barrett(m); + else + z = new Montgomery(m); + + // precomputation + var g = new Array(), n = 3, k1 = k-1, km = (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1],g2); + while(n <= km) { + g[n] = nbi(); + z.mulTo(g2,g[n-2],g[n]); + n += 2; } - const mime = split.shift() - const base64 = /;base64$/.test(mime) - type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime - const rawData = decodeURIComponent(split.join(',') + search) - data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData) - } catch (er) { - return reject(new FetchError(`[${request.method}] ${ - request.url} invalid URL, ${er.message}`, 'system', er)) } - const { signal } = request - if (signal && signal.aborted) { - return reject(new AbortError('The user aborted a request.')) - } + var j = e.t-1, w, is1 = true, r2 = nbi(), t; + i = nbits(e[j])-1; + while(j >= 0) { + if(i >= k1) w = (e[j]>>(i-k1))&km; + else { + w = (e[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e[j-1]>>(this.DB+i-k1); + } - const headers = { 'Content-Length': data.length } - if (type) { - headers['Content-Type'] = type - } - return resolve(new Response(data, { headers })) - })) - } + n = k; + while((w&1) == 0) { w >>= 1; --n; } + if((i -= n) < 0) { i += this.DB; --j; } + if(is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } + else { + while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; } + if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; } + z.mulTo(r2,g[w],r); + } - return new Promise((resolve, reject) => { - // build request object - const request = new Request(url, opts) - let options - try { - options = getNodeRequestOptions(request) - } catch (er) { - return reject(er) + while(j >= 0 && (e[j]&(1< { - const error = new AbortError('The user aborted a request.') - reject(error) - if (Minipass.isStream(request.body) && - typeof request.body.destroy === 'function') { - request.body.destroy(error) + // (public) gcd(this,a) (HAC 14.54) + function bnGCD(a) { + var x = (this.s<0)?this.negate():this.clone(); + var y = (a.s<0)?a.negate():a.clone(); + if(x.compareTo(y) < 0) { var t = x; x = y; y = t; } + var i = x.getLowestSetBit(), g = y.getLowestSetBit(); + if(g < 0) return x; + if(i < g) g = i; + if(g > 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); } - if (response && response.body) { - response.body.emit('error', error) + while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } + else { + y.subTo(x,y); + y.rShiftTo(1,y); + } } + if(g > 0) y.lShiftTo(g,y); + return y; } - if (signal && signal.aborted) { - return abort() - } - - const abortAndFinalize = () => { - abort() - finalize() + // (protected) this % n, n < 2^26 + function bnpModInt(n) { + if(n <= 0) return 0; + var d = this.DV%n, r = (this.s<0)?n-1:0; + if(this.t > 0) + if(d == 0) r = this[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n; + return r; } - const finalize = () => { - req.abort() - if (signal) { - signal.removeEventListener('abort', abortAndFinalize) + // (public) 1/this % m (HAC 14.61) + function bnModInverse(m) { + var ac = m.isEven(); + if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; + var u = m.clone(), v = this.clone(); + var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); + while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } + else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } + else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } + else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } } - clearTimeout(reqTimeout) + if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; + if(d.compareTo(m) >= 0) return d.subtract(m); + if(d.signum() < 0) d.addTo(m,d); else return d; + if(d.signum() < 0) return d.add(m); else return d; } - // send request - const req = send(options) + var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; + var lplim = (1<<26)/lowprimes[lowprimes.length-1]; - if (signal) { - signal.addEventListener('abort', abortAndFinalize) + // (public) test primality with certainty >= 1-.5^t + function bnIsProbablePrime(t) { + var i, x = this.abs(); + if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x[0] == lowprimes[i]) return true; + return false; + } + if(x.isEven()) return false; + i = 1; + while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; + } + return x.millerRabin(t); } - let reqTimeout = null - if (request.timeout) { - req.once('socket', () => { - reqTimeout = setTimeout(() => { - reject(new FetchError(`network timeout at: ${ - request.url}`, 'request-timeout')) - finalize() - }, request.timeout) - }) + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + function bnpMillerRabin(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if(k <= 0) return false; + var r = n1.shiftRight(k); + t = (t+1)>>1; + if(t > lowprimes.length) t = lowprimes.length; + var a = nbi(); + for(var i = 0; i < t; ++i) { + //Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } + } + return true; } - req.on('error', er => { - // if a 'response' event is emitted before the 'error' event, then by the - // time this handler is run it's too late to reject the Promise for the - // response. instead, we forward the error event to the response stream - // so that the error will surface to the user when they try to consume - // the body. this is done as a side effect of aborting the request except - // for in windows, where we must forward the event manually, otherwise - // there is no longer a ref'd socket attached to the request and the - // stream never ends so the event loop runs out of work and the process - // exits without warning. - // coverage skipped here due to the difficulty in testing - // istanbul ignore next - if (req.res) { - req.res.emit('error', er) - } - reject(new FetchError(`request to ${request.url} failed, reason: ${ - er.message}`, 'system', er)) - finalize() - }) + // protected + BigInteger.prototype.chunkSize = bnpChunkSize; + BigInteger.prototype.toRadix = bnpToRadix; + BigInteger.prototype.fromRadix = bnpFromRadix; + BigInteger.prototype.fromNumber = bnpFromNumber; + BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + BigInteger.prototype.changeBit = bnpChangeBit; + BigInteger.prototype.addTo = bnpAddTo; + BigInteger.prototype.dMultiply = bnpDMultiply; + BigInteger.prototype.dAddOffset = bnpDAddOffset; + BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + BigInteger.prototype.modInt = bnpModInt; + BigInteger.prototype.millerRabin = bnpMillerRabin; - req.on('response', res => { - clearTimeout(reqTimeout) + // public + BigInteger.prototype.clone = bnClone; + BigInteger.prototype.intValue = bnIntValue; + BigInteger.prototype.byteValue = bnByteValue; + BigInteger.prototype.shortValue = bnShortValue; + BigInteger.prototype.signum = bnSigNum; + BigInteger.prototype.toByteArray = bnToByteArray; + BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.min = bnMin; + BigInteger.prototype.max = bnMax; + BigInteger.prototype.and = bnAnd; + BigInteger.prototype.or = bnOr; + BigInteger.prototype.xor = bnXor; + BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.not = bnNot; + BigInteger.prototype.shiftLeft = bnShiftLeft; + BigInteger.prototype.shiftRight = bnShiftRight; + BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + BigInteger.prototype.bitCount = bnBitCount; + BigInteger.prototype.testBit = bnTestBit; + BigInteger.prototype.setBit = bnSetBit; + BigInteger.prototype.clearBit = bnClearBit; + BigInteger.prototype.flipBit = bnFlipBit; + BigInteger.prototype.add = bnAdd; + BigInteger.prototype.subtract = bnSubtract; + BigInteger.prototype.multiply = bnMultiply; + BigInteger.prototype.divide = bnDivide; + BigInteger.prototype.remainder = bnRemainder; + BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; + BigInteger.prototype.modPow = bnModPow; + BigInteger.prototype.modInverse = bnModInverse; + BigInteger.prototype.pow = bnPow; + BigInteger.prototype.gcd = bnGCD; + BigInteger.prototype.isProbablePrime = bnIsProbablePrime; - const headers = createHeadersLenient(res.headers) + // JSBN-specific extension + BigInteger.prototype.square = bnSquare; - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location') + // Expose the Barrett function + BigInteger.prototype.Barrett = Barrett - // HTTP fetch step 5.3 - let locationURL = null - try { - locationURL = location === null ? null : new URL(location, request.url).toString() - } catch { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - /* eslint-disable-next-line max-len */ - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')) - finalize() - return - } - } + // BigInteger interfaces not implemented in jsbn: - // HTTP fetch step 5.5 - if (request.redirect === 'error') { - reject(new FetchError('uri requested responds with a redirect, ' + - `redirect mode is set to error: ${request.url}`, 'no-redirect')) - finalize() - return - } else if (request.redirect === 'manual') { - // node-fetch-specific step: make manual redirect a bit easier to - // use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL) - } catch (err) { - /* istanbul ignore next: nodejs server prevent invalid - response headers, we can't test this through normal - request */ - reject(err) - } - } - } else if (request.redirect === 'follow' && locationURL !== null) { - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${ - request.url}`, 'max-redirect')) - finalize() - return - } + // BigInteger(int signum, byte[] magnitude) + // double doubleValue() + // float floatValue() + // int hashCode() + // long longValue() + // static BigInteger valueOf(long val) - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && - request.body && - getTotalBytes(request) === null) { - reject(new FetchError( - 'Cannot follow redirect with body being a readable stream', - 'unsupported-redirect' - )) - finalize() - return - } + // Random number generator - requires a PRNG backend, e.g. prng4.js - // Update host due to redirection - request.headers.set('host', (new URL(locationURL)).host) + // For best results, put code like + // + // in your main HTML document. - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - } + var rng_state; + var rng_pool; + var rng_pptr; - // if the redirect is to a new hostname, strip the authorization and cookie headers - const parsedOriginal = new URL(request.url) - const parsedRedirect = new URL(locationURL) - if (parsedOriginal.hostname !== parsedRedirect.hostname) { - requestOpts.headers.delete('authorization') - requestOpts.headers.delete('cookie') - } + // Mix in a 32-bit integer into the pool + function rng_seed_int(x) { + rng_pool[rng_pptr++] ^= x & 255; + rng_pool[rng_pptr++] ^= (x >> 8) & 255; + rng_pool[rng_pptr++] ^= (x >> 16) & 255; + rng_pool[rng_pptr++] ^= (x >> 24) & 255; + if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; + } - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || ( - (res.statusCode === 301 || res.statusCode === 302) && - request.method === 'POST' - )) { - requestOpts.method = 'GET' - requestOpts.body = undefined - requestOpts.headers.delete('content-length') - } + // Mix in the current time (w/milliseconds) into the pool + function rng_seed_time() { + rng_seed_int(new Date().getTime()); + } - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))) - finalize() - return + // Initialize the pool with junk if needed. + if(rng_pool == null) { + rng_pool = new Array(); + rng_pptr = 0; + var t; + if(typeof window !== "undefined" && window.crypto) { + if (window.crypto.getRandomValues) { + // Use webcrypto if available + var ua = new Uint8Array(32); + window.crypto.getRandomValues(ua); + for(t = 0; t < 32; ++t) + rng_pool[rng_pptr++] = ua[t]; + } + else if(navigator.appName == "Netscape" && navigator.appVersion < "5") { + // Extract entropy (256 bits) from NS4 RNG if available + var z = window.crypto.random(32); + for(t = 0; t < z.length; ++t) + rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } - } // end if(isRedirect) - - // prepare response - res.once('end', () => - signal && signal.removeEventListener('abort', abortAndFinalize)) - - const body = new Minipass() - // if an error occurs, either on the response stream itself, on one of the - // decoder streams, or a response length timeout from the Body class, we - // forward the error through to our internal body stream. If we see an - // error event on that, we call finalize to abort the request and ensure - // we don't leave a socket believing a request is in flight. - // this is difficult to test, so lacks specific coverage. - body.on('error', finalize) - // exceedingly rare that the stream would have an error, - // but just in case we proxy it to the stream in use. - res.on('error', /* istanbul ignore next */ er => body.emit('error', er)) - res.on('data', (chunk) => body.write(chunk)) - res.on('end', () => body.end()) - - const responseOptions = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter, - trailer: new Promise(resolveTrailer => - res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))), } - - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding') - - // HTTP-network fetch step 12.1.1.4: handle content codings - - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || - request.method === 'HEAD' || - codings === null || - res.statusCode === 204 || - res.statusCode === 304) { - response = new Response(body, responseOptions) - resolve(response) - return + while(rng_pptr < rng_psize) { // extract some randomness from Math.random() + t = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = t >>> 8; + rng_pool[rng_pptr++] = t & 255; } + rng_pptr = 0; + rng_seed_time(); + //rng_seed_int(window.screenX); + //rng_seed_int(window.screenY); + } - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: zlib.constants.Z_SYNC_FLUSH, + function rng_get_byte() { + if(rng_state == null) { + rng_seed_time(); + rng_state = prng_newstate(); + rng_state.init(rng_pool); + for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) + rng_pool[rng_pptr] = 0; + rng_pptr = 0; + //rng_pool = null; } + // TODO: allow reseeding after first request + return rng_state.next(); + } - // for gzip - if (codings === 'gzip' || codings === 'x-gzip') { - const unzip = new zlib.Gunzip(zlibOptions) - response = new Response( - // exceedingly rare that the stream would have an error, - // but just in case we proxy it to the stream in use. - body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip), - responseOptions - ) - resolve(response) - return - } + function rng_get_bytes(ba) { + var i; + for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); + } - // for deflate - if (codings === 'deflate' || codings === 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new Minipass()) - raw.once('data', chunk => { - // see http://stackoverflow.com/questions/37519828 - const decoder = (chunk[0] & 0x0F) === 0x08 - ? new zlib.Inflate() - : new zlib.InflateRaw() - // exceedingly rare that the stream would have an error, - // but just in case we proxy it to the stream in use. - body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) - response = new Response(decoder, responseOptions) - resolve(response) - }) - return - } + function SecureRandom() {} - // for br - if (codings === 'br') { - // ignoring coverage so tests don't have to fake support (or lack of) for brotli - // istanbul ignore next - try { - var decoder = new zlib.BrotliDecompress() - } catch (err) { - reject(err) - finalize() - return - } - // exceedingly rare that the stream would have an error, - // but just in case we proxy it to the stream in use. - body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) - response = new Response(decoder, responseOptions) - resolve(response) - return + SecureRandom.prototype.nextBytes = rng_get_bytes; + + // prng4.js - uses Arcfour as a PRNG + + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = new Array(); + } + + // Initialize arcfour context from key, an array of ints, each from [0..255] + function ARC4init(key) { + var i, j, t; + for(i = 0; i < 256; ++i) + this.S[i] = i; + j = 0; + for(i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; } + this.i = 0; + this.j = 0; + } - // otherwise, use response as-is - response = new Response(body, responseOptions) - resolve(response) - }) + function ARC4next() { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + } - writeToStream(req, request) - }) -} + Arcfour.prototype.init = ARC4init; + Arcfour.prototype.next = ARC4next; -module.exports = fetch + // Plug in your RNG constructor here + function prng_newstate() { + return new Arcfour(); + } -fetch.isRedirect = code => - code === 301 || - code === 302 || - code === 303 || - code === 307 || - code === 308 + // Pool size must be a multiple of 4 and greater than 32. + // An array of bytes the size of the pool will be passed to init() + var rng_psize = 256; -fetch.Headers = Headers -fetch.Request = Request -fetch.Response = Response -fetch.FetchError = FetchError -fetch.AbortError = AbortError + if (true) { + exports = module.exports = { + default: BigInteger, + BigInteger: BigInteger, + SecureRandom: SecureRandom, + }; + } else {} + +}).call(this); /***/ }), -/***/ 99586: +/***/ 85743: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -const { URL } = __nccwpck_require__(87016) +const { Request, Response } = __nccwpck_require__(88483) const { Minipass } = __nccwpck_require__(78275) -const Headers = __nccwpck_require__(98645) -const { exportNodeCompatibleHeaders } = Headers -const Body = __nccwpck_require__(28515) -const { clone, extractContentType, getTotalBytes } = Body +const MinipassFlush = __nccwpck_require__(37633) +const cacache = __nccwpck_require__(85742) +const url = __nccwpck_require__(87016) -const version = (__nccwpck_require__(27573)/* .version */ .rE) -const defaultUserAgent = - `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)` +const CachingMinipassPipeline = __nccwpck_require__(22314) +const CachePolicy = __nccwpck_require__(15281) +const cacheKey = __nccwpck_require__(45808) +const remote = __nccwpck_require__(20766) -const INTERNALS = Symbol('Request internals') +const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) -const isRequest = input => - typeof input === 'object' && typeof input[INTERNALS] === 'object' +// allow list for request headers that will be written to the cache index +// note: we will also store any request headers +// that are named in a response's vary header +const KEEP_REQUEST_HEADERS = [ + 'accept-charset', + 'accept-encoding', + 'accept-language', + 'accept', + 'cache-control', +] -const isAbortSignal = signal => { - const proto = ( - signal - && typeof signal === 'object' - && Object.getPrototypeOf(signal) - ) - return !!(proto && proto.constructor.name === 'AbortSignal') -} +// allow list for response headers that will be written to the cache index +// note: we must not store the real response's age header, or when we load +// a cache policy based on the metadata it will think the cached response +// is always stale +const KEEP_RESPONSE_HEADERS = [ + 'cache-control', + 'content-encoding', + 'content-language', + 'content-type', + 'date', + 'etag', + 'expires', + 'last-modified', + 'link', + 'location', + 'pragma', + 'vary', +] -class Request extends Body { - constructor (input, init = {}) { - const parsedURL = isRequest(input) ? new URL(input.url) - : input && input.href ? new URL(input.href) - : new URL(`${input}`) +// return an object containing all metadata to be written to the index +const getMetadata = (request, response, options) => { + const metadata = { + time: Date.now(), + url: request.url, + reqHeaders: {}, + resHeaders: {}, - if (isRequest(input)) { - init = { ...input[INTERNALS], ...init } - } else if (!input || typeof input === 'string') { - input = {} + // options on which we must match the request and vary the response + options: { + compress: options.compress != null ? options.compress : request.compress, + }, + } + + // only save the status if it's not a 200 or 304 + if (response.status !== 200 && response.status !== 304) { + metadata.status = response.status + } + + for (const name of KEEP_REQUEST_HEADERS) { + if (request.headers.has(name)) { + metadata.reqHeaders[name] = request.headers.get(name) } + } - const method = (init.method || input.method || 'GET').toUpperCase() - const isGETHEAD = method === 'GET' || method === 'HEAD' + // if the request's host header differs from the host in the url + // we need to keep it, otherwise it's just noise and we ignore it + const host = request.headers.get('host') + const parsedUrl = new url.URL(request.url) + if (host && parsedUrl.host !== host) { + metadata.reqHeaders.host = host + } - if ((init.body !== null && init.body !== undefined || - isRequest(input) && input.body !== null) && isGETHEAD) { - throw new TypeError('Request with GET/HEAD method cannot have body') + // if the response has a vary header, make sure + // we store the relevant request headers too + if (response.headers.has('vary')) { + const vary = response.headers.get('vary') + // a vary of "*" means every header causes a different response. + // in that scenario, we do not include any additional headers + // as the freshness check will always fail anyway and we don't + // want to bloat the cache indexes + if (vary !== '*') { + // copy any other request headers that will vary the response + const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/) + for (const name of varyHeaders) { + if (request.headers.has(name)) { + metadata.reqHeaders[name] = request.headers.get(name) + } + } } + } - const inputBody = init.body !== null && init.body !== undefined ? init.body - : isRequest(input) && input.body !== null ? clone(input) - : null + for (const name of KEEP_RESPONSE_HEADERS) { + if (response.headers.has(name)) { + metadata.resHeaders[name] = response.headers.get(name) + } + } - super(inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0, - }) + for (const name of options.cacheAdditionalHeaders) { + if (response.headers.has(name)) { + metadata.resHeaders[name] = response.headers.get(name) + } + } - const headers = new Headers(init.headers || input.headers || {}) + return metadata +} - if (inputBody !== null && inputBody !== undefined && - !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody) - if (contentType) { - headers.append('Content-Type', contentType) - } +// symbols used to hide objects that may be lazily evaluated in a getter +const _request = Symbol('request') +const _response = Symbol('response') +const _policy = Symbol('policy') + +class CacheEntry { + constructor ({ entry, request, response, options }) { + if (entry) { + this.key = entry.key + this.entry = entry + // previous versions of this module didn't write an explicit timestamp in + // the metadata, so fall back to the entry's timestamp. we can't use the + // entry timestamp to determine staleness because cacache will update it + // when it verifies its data + this.entry.metadata.time = this.entry.metadata.time || this.entry.time + } else { + this.key = cacheKey(request) } - const signal = 'signal' in init ? init.signal - : null + this.options = options - if (signal !== null && signal !== undefined && !isAbortSignal(signal)) { - throw new TypeError('Expected signal must be an instanceof AbortSignal') + // these properties are behind getters that lazily evaluate + this[_request] = request + this[_response] = response + this[_policy] = null + } + + // returns a CacheEntry instance that satisfies the given request + // or undefined if no existing entry satisfies + static async find (request, options) { + try { + // compacts the index and returns an array of unique entries + var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => { + const entryA = new CacheEntry({ entry: A, options }) + const entryB = new CacheEntry({ entry: B, options }) + return entryA.policy.satisfies(entryB.request) + }, { + validateEntry: (entry) => { + // clean out entries with a buggy content-encoding value + if (entry.metadata && + entry.metadata.resHeaders && + entry.metadata.resHeaders['content-encoding'] === null) { + return false + } + + // if an integrity is null, it needs to have a status specified + if (entry.integrity === null) { + return !!(entry.metadata && entry.metadata.status) + } + + return true + }, + }) + } catch (err) { + // if the compact request fails, ignore the error and return + return } - // TLS specific options that are handled by node - const { - ca, - cert, - ciphers, - clientCertEngine, - crl, - dhparam, - ecdhCurve, - family, - honorCipherOrder, - key, - passphrase, - pfx, - rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0', - secureOptions, - secureProtocol, - servername, - sessionIdContext, - } = init + // a cache mode of 'reload' means to behave as though we have no cache + // on the way to the network. return undefined to allow cacheFetch to + // create a brand new request no matter what. + if (options.cache === 'reload') { + return + } - this[INTERNALS] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal, - ca, - cert, - ciphers, - clientCertEngine, - crl, - dhparam, - ecdhCurve, - family, - honorCipherOrder, - key, - passphrase, - pfx, - rejectUnauthorized, - secureOptions, - secureProtocol, - servername, - sessionIdContext, + // find the specific entry that satisfies the request + let match + for (const entry of matches) { + const _entry = new CacheEntry({ + entry, + options, + }) + + if (_entry.policy.satisfies(request)) { + match = _entry + break + } } - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow - : input.follow !== undefined ? input.follow - : 20 - this.compress = init.compress !== undefined ? init.compress - : input.compress !== undefined ? input.compress - : true - this.counter = init.counter || input.counter || 0 - this.agent = init.agent || input.agent + return match } - get method () { - return this[INTERNALS].method + // if the user made a PUT/POST/PATCH then we invalidate our + // cache for the same url by deleting the index entirely + static async invalidate (request, options) { + const key = cacheKey(request) + try { + await cacache.rm.entry(options.cachePath, key, { removeFully: true }) + } catch (err) { + // ignore errors + } } - get url () { - return this[INTERNALS].parsedURL.toString() + get request () { + if (!this[_request]) { + this[_request] = new Request(this.entry.metadata.url, { + method: 'GET', + headers: this.entry.metadata.reqHeaders, + ...this.entry.metadata.options, + }) + } + + return this[_request] } - get headers () { - return this[INTERNALS].headers + get response () { + if (!this[_response]) { + this[_response] = new Response(null, { + url: this.entry.metadata.url, + counter: this.options.counter, + status: this.entry.metadata.status || 200, + headers: { + ...this.entry.metadata.resHeaders, + 'content-length': this.entry.size, + }, + }) + } + + return this[_response] } - get redirect () { - return this[INTERNALS].redirect + get policy () { + if (!this[_policy]) { + this[_policy] = new CachePolicy({ + entry: this.entry, + request: this.request, + response: this.response, + options: this.options, + }) + } + + return this[_policy] } - get signal () { - return this[INTERNALS].signal + // wraps the response in a pipeline that stores the data + // in the cache while the user consumes it + async store (status) { + // if we got a status other than 200, 301, or 308, + // or the CachePolicy forbid storage, append the + // cache status header and return it untouched + if ( + this.request.method !== 'GET' || + ![200, 301, 308].includes(this.response.status) || + !this.policy.storable() + ) { + this.response.headers.set('x-local-cache-status', 'skip') + return this.response + } + + const size = this.response.headers.get('content-length') + const cacheOpts = { + algorithms: this.options.algorithms, + metadata: getMetadata(this.request, this.response, this.options), + size, + integrity: this.options.integrity, + integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body, + } + + let body = null + // we only set a body if the status is a 200, redirects are + // stored as metadata only + if (this.response.status === 200) { + let cacheWriteResolve, cacheWriteReject + const cacheWritePromise = new Promise((resolve, reject) => { + cacheWriteResolve = resolve + cacheWriteReject = reject + }).catch((err) => { + body.emit('error', err) + }) + + body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({ + flush () { + return cacheWritePromise + }, + })) + // this is always true since if we aren't reusing the one from the remote fetch, we + // are using the one from cacache + body.hasIntegrityEmitter = true + + const onResume = () => { + const tee = new Minipass() + const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts) + // re-emit the integrity and size events on our new response body so they can be reused + cacheStream.on('integrity', i => body.emit('integrity', i)) + cacheStream.on('size', s => body.emit('size', s)) + // stick a flag on here so downstream users will know if they can expect integrity events + tee.pipe(cacheStream) + // TODO if the cache write fails, log a warning but return the response anyway + // eslint-disable-next-line promise/catch-or-return + cacheStream.promise().then(cacheWriteResolve, cacheWriteReject) + body.unshift(tee) + body.unshift(this.response.body) + } + + body.once('resume', onResume) + body.once('end', () => body.removeListener('resume', onResume)) + } else { + await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts) + } + + // note: we do not set the x-local-cache-hash header because we do not know + // the hash value until after the write to the cache completes, which doesn't + // happen until after the response has been sent and it's too late to write + // the header anyway + this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) + this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) + this.response.headers.set('x-local-cache-mode', 'stream') + this.response.headers.set('x-local-cache-status', status) + this.response.headers.set('x-local-cache-time', new Date().toISOString()) + const newResponse = new Response(body, { + url: this.response.url, + status: this.response.status, + headers: this.response.headers, + counter: this.options.counter, + }) + return newResponse } - clone () { - return new Request(this) - } + // use the cached data to create a response and return it + async respond (method, options, status) { + let response + if (method === 'HEAD' || [301, 308].includes(this.response.status)) { + // if the request is a HEAD, or the response is a redirect, + // then the metadata in the entry already includes everything + // we need to build a response + response = this.response + } else { + // we're responding with a full cached response, so create a body + // that reads from cacache and attach it to a new Response + const body = new Minipass() + const headers = { ...this.policy.responseHeaders() } + + const onResume = () => { + const cacheStream = cacache.get.stream.byDigest( + this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } + ) + cacheStream.on('error', async (err) => { + cacheStream.pause() + if (err.code === 'EINTEGRITY') { + await cacache.rm.content( + this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize } + ) + } + if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') { + await CacheEntry.invalidate(this.request, this.options) + } + body.emit('error', err) + cacheStream.resume() + }) + // emit the integrity and size events based on our metadata so we're consistent + body.emit('integrity', this.entry.integrity) + body.emit('size', Number(headers['content-length'])) + cacheStream.pipe(body) + } + + body.once('resume', onResume) + body.once('end', () => body.removeListener('resume', onResume)) + response = new Response(body, { + url: this.entry.metadata.url, + counter: options.counter, + status: 200, + headers, + }) + } - get [Symbol.toStringTag] () { - return 'Request' + response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath)) + response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity)) + response.headers.set('x-local-cache-key', encodeURIComponent(this.key)) + response.headers.set('x-local-cache-mode', 'stream') + response.headers.set('x-local-cache-status', status) + response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString()) + return response } - static getNodeRequestOptions (request) { - const parsedURL = request[INTERNALS].parsedURL - const headers = new Headers(request[INTERNALS].headers) + // use the provided request along with this cache entry to + // revalidate the stored response. returns a response, either + // from the cache or from the update + async revalidate (request, options) { + const revalidateRequest = new Request(request, { + headers: this.policy.revalidationHeaders(request), + }) - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*') - } + try { + // NOTE: be sure to remove the headers property from the + // user supplied options, since we have already defined + // them on the new request object. if they're still in the + // options then those will overwrite the ones from the policy + var response = await remote(revalidateRequest, { + ...options, + headers: undefined, + }) + } catch (err) { + // if the network fetch fails, return the stale + // cached response unless it has a cache-control + // of 'must-revalidate' + if (!this.policy.mustRevalidate) { + return this.respond(request.method, options, 'stale') + } - // Basic fetch - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported') + throw err } - if (request.signal && - Minipass.isStream(request.body) && - typeof request.body.destroy !== 'function') { - throw new Error( - 'Cancellation of streamed requests with AbortSignal is not supported') - } + if (this.policy.revalidated(revalidateRequest, response)) { + // we got a 304, write a new index to the cache and respond from cache + const metadata = getMetadata(request, response, options) + // 304 responses do not include headers that are specific to the response data + // since they do not include a body, so we copy values for headers that were + // in the old cache entry to the new one, if the new metadata does not already + // include that header + for (const name of KEEP_RESPONSE_HEADERS) { + if ( + !hasOwnProperty(metadata.resHeaders, name) && + hasOwnProperty(this.entry.metadata.resHeaders, name) + ) { + metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] + } + } - // HTTP-network-or-cache fetch steps 2.4-2.7 - const contentLengthValue = - (request.body === null || request.body === undefined) && - /^(POST|PUT)$/i.test(request.method) ? '0' - : request.body !== null && request.body !== undefined - ? getTotalBytes(request) - : null + for (const name of options.cacheAdditionalHeaders) { + const inMeta = hasOwnProperty(metadata.resHeaders, name) + const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name) + const inPolicy = hasOwnProperty(this.policy.response.headers, name) - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue + '') - } + // if the header is in the existing entry, but it is not in the metadata + // then we need to write it to the metadata as this will refresh the on-disk cache + if (!inMeta && inEntry) { + metadata.resHeaders[name] = this.entry.metadata.resHeaders[name] + } + // if the header is in the metadata, but not in the policy, then we need to set + // it in the policy so that it's included in the immediate response. future + // responses will load a new cache entry, so we don't need to change that + if (!inPolicy && inMeta) { + this.policy.response.headers[name] = metadata.resHeaders[name] + } + } - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', defaultUserAgent) + try { + await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, { + size: this.entry.size, + metadata, + }) + } catch (err) { + // if updating the cache index fails, we ignore it and + // respond anyway + } + return this.respond(request.method, options, 'revalidated') } - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate') - } + // if we got a modified response, create a new entry based on it + const newEntry = new CacheEntry({ + request, + response, + options, + }) - const agent = typeof request.agent === 'function' - ? request.agent(parsedURL) - : request.agent + // respond with the new entry while writing it to the cache + return newEntry.store('updated') + } +} - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close') - } +module.exports = CacheEntry - // TLS specific options that are handled by node - const { - ca, - cert, - ciphers, - clientCertEngine, - crl, - dhparam, - ecdhCurve, - family, - honorCipherOrder, - key, - passphrase, - pfx, - rejectUnauthorized, - secureOptions, - secureProtocol, - servername, - sessionIdContext, - } = request[INTERNALS] - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js +/***/ }), - // we cannot spread parsedURL directly, so we have to read each property one-by-one - // and map them to the equivalent https?.request() method options - const urlProps = { - auth: parsedURL.username || parsedURL.password - ? `${parsedURL.username}:${parsedURL.password}` - : '', - host: parsedURL.host, - hostname: parsedURL.hostname, - path: `${parsedURL.pathname}${parsedURL.search}`, - port: parsedURL.port, - protocol: parsedURL.protocol, - } +/***/ 59456: +/***/ ((module) => { - return { - ...urlProps, - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent, - ca, - cert, - ciphers, - clientCertEngine, - crl, - dhparam, - ecdhCurve, - family, - honorCipherOrder, - key, - passphrase, - pfx, - rejectUnauthorized, - secureOptions, - secureProtocol, - servername, - sessionIdContext, - timeout: request.timeout, - } +class NotCachedError extends Error { + constructor (url) { + /* eslint-disable-next-line max-len */ + super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`) + this.code = 'ENOTCACHED' } } -module.exports = Request - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true }, -}) +module.exports = { + NotCachedError, +} /***/ }), -/***/ 43852: +/***/ 96807: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -const http = __nccwpck_require__(58611) -const { STATUS_CODES } = http - -const Headers = __nccwpck_require__(98645) -const Body = __nccwpck_require__(28515) -const { clone, extractContentType } = Body - -const INTERNALS = Symbol('Response internals') - -class Response extends Body { - constructor (body = null, opts = {}) { - super(body, opts) - - const status = opts.status || 200 - const headers = new Headers(opts.headers) +const { NotCachedError } = __nccwpck_require__(59456) +const CacheEntry = __nccwpck_require__(85743) +const remote = __nccwpck_require__(20766) - if (body !== null && body !== undefined && !headers.has('Content-Type')) { - const contentType = extractContentType(body) - if (contentType) { - headers.append('Content-Type', contentType) - } +// do whatever is necessary to get a Response and return it +const cacheFetch = async (request, options) => { + // try to find a cached entry that satisfies this request + const entry = await CacheEntry.find(request, options) + if (!entry) { + // no cached result, if the cache mode is 'only-if-cached' that's a failure + if (options.cache === 'only-if-cached') { + throw new NotCachedError(request.url) } - this[INTERNALS] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter, - trailer: Promise.resolve(opts.trailer || new Headers()), - } + // otherwise, we make a request, store it and return it + const response = await remote(request, options) + const newEntry = new CacheEntry({ request, response, options }) + return newEntry.store('miss') } - get trailer () { - return this[INTERNALS].trailer + // we have a cached response that satisfies this request, however if the cache + // mode is 'no-cache' then we send the revalidation request no matter what + if (options.cache === 'no-cache') { + return entry.revalidate(request, options) } - get url () { - return this[INTERNALS].url || '' + // if the cached entry is not stale, or if the cache mode is 'force-cache' or + // 'only-if-cached' we can respond with the cached entry. set the status + // based on the result of needsRevalidation and respond + const _needsRevalidation = entry.policy.needsRevalidation(request) + if (options.cache === 'force-cache' || + options.cache === 'only-if-cached' || + !_needsRevalidation) { + return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit') } - get status () { - return this[INTERNALS].status - } + // if we got here, the cache entry is stale so revalidate it + return entry.revalidate(request, options) +} - get ok () { - return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300 +cacheFetch.invalidate = async (request, options) => { + if (!options.cachePath) { + return } - get redirected () { - return this[INTERNALS].counter > 0 - } + return CacheEntry.invalidate(request, options) +} - get statusText () { - return this[INTERNALS].statusText - } +module.exports = cacheFetch - get headers () { - return this[INTERNALS].headers - } - clone () { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected, - trailer: this.trailer, - }) - } +/***/ }), - get [Symbol.toStringTag] () { - return 'Response' - } +/***/ 45808: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { URL, format } = __nccwpck_require__(87016) + +// options passed to url.format() when generating a key +const formatOptions = { + auth: false, + fragment: false, + search: true, + unicode: false, } -module.exports = Response +// returns a string to be used as the cache key for the Request +const cacheKey = (request) => { + const parsed = new URL(request.url) + return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}` +} -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true }, -}) +module.exports = cacheKey /***/ }), -/***/ 37633: +/***/ 15281: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Minipass = __nccwpck_require__(64387) -const _flush = Symbol('_flush') -const _flushed = Symbol('_flushed') -const _flushing = Symbol('_flushing') -class Flush extends Minipass { - constructor (opt = {}) { - if (typeof opt === 'function') - opt = { flush: opt } +const CacheSemantics = __nccwpck_require__(12203) +const Negotiator = __nccwpck_require__(60668) +const ssri = __nccwpck_require__(68951) - super(opt) +// options passed to http-cache-semantics constructor +const policyOptions = { + shared: false, + ignoreCargoCult: true, +} - // or extend this class and provide a 'flush' method in your subclass - if (typeof opt.flush !== 'function' && typeof this.flush !== 'function') - throw new TypeError('must provide flush function in options') +// a fake empty response, used when only testing the +// request for storability +const emptyResponse = { status: 200, headers: {} } - this[_flush] = opt.flush || this.flush +// returns a plain object representation of the Request +const requestObject = (request) => { + const _obj = { + method: request.method, + url: request.url, + headers: {}, + compress: request.compress, } - emit (ev, ...data) { - if ((ev !== 'end' && ev !== 'finish') || this[_flushed]) - return super.emit(ev, ...data) + request.headers.forEach((value, key) => { + _obj.headers[key] = value + }) - if (this[_flushing]) - return + return _obj +} - this[_flushing] = true +// returns a plain object representation of the Response +const responseObject = (response) => { + const _obj = { + status: response.status, + headers: {}, + } - const afterFlush = er => { - this[_flushed] = true - er ? super.emit('error', er) : super.emit('end') - } + response.headers.forEach((value, key) => { + _obj.headers[key] = value + }) - const ret = this[_flush](afterFlush) - if (ret && ret.then) - ret.then(() => afterFlush(), er => afterFlush(er)) - } + return _obj } -module.exports = Flush +class CachePolicy { + constructor ({ entry, request, response, options }) { + this.entry = entry + this.request = requestObject(request) + this.response = responseObject(response) + this.options = options + this.policy = new CacheSemantics(this.request, this.response, policyOptions) + if (this.entry) { + // if we have an entry, copy the timestamp to the _responseTime + // this is necessary because the CacheSemantics constructor forces + // the value to Date.now() which means a policy created from a + // cache entry is likely to always identify itself as stale + this.policy._responseTime = this.entry.metadata.time + } + } -/***/ }), + // static method to quickly determine if a request alone is storable + static storable (request, options) { + // no cachePath means no caching + if (!options.cachePath) { + return false + } -/***/ 64387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // user explicitly asked not to cache + if (options.cache === 'no-store') { + return false + } -"use strict"; + // we only cache GET and HEAD requests + if (!['GET', 'HEAD'].includes(request.method)) { + return false + } -const proc = typeof process === 'object' && process ? process : { - stdout: null, - stderr: null, -} -const EE = __nccwpck_require__(24434) -const Stream = __nccwpck_require__(2203) -const SD = (__nccwpck_require__(13193).StringDecoder) + // otherwise, let http-cache-semantics make the decision + // based on the request's headers + const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions) + return policy.storable() + } -const EOF = Symbol('EOF') -const MAYBE_EMIT_END = Symbol('maybeEmitEnd') -const EMITTED_END = Symbol('emittedEnd') -const EMITTING_END = Symbol('emittingEnd') -const EMITTED_ERROR = Symbol('emittedError') -const CLOSED = Symbol('closed') -const READ = Symbol('read') -const FLUSH = Symbol('flush') -const FLUSHCHUNK = Symbol('flushChunk') -const ENCODING = Symbol('encoding') -const DECODER = Symbol('decoder') -const FLOWING = Symbol('flowing') -const PAUSED = Symbol('paused') -const RESUME = Symbol('resume') -const BUFFERLENGTH = Symbol('bufferLength') -const BUFFERPUSH = Symbol('bufferPush') -const BUFFERSHIFT = Symbol('bufferShift') -const OBJECTMODE = Symbol('objectMode') -const DESTROYED = Symbol('destroyed') -const EMITDATA = Symbol('emitData') -const EMITEND = Symbol('emitEnd') -const EMITEND2 = Symbol('emitEnd2') -const ASYNC = Symbol('async') + // returns true if the policy satisfies the request + satisfies (request) { + const _req = requestObject(request) + if (this.request.headers.host !== _req.headers.host) { + return false + } -const defer = fn => Promise.resolve().then(fn) + if (this.request.compress !== _req.compress) { + return false + } -// TODO remove when Node v8 support drops -const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' -const ASYNCITERATOR = doIter && Symbol.asyncIterator - || Symbol('asyncIterator not implemented') -const ITERATOR = doIter && Symbol.iterator - || Symbol('iterator not implemented') + const negotiatorA = new Negotiator(this.request) + const negotiatorB = new Negotiator(_req) -// events that mean 'the stream is over' -// these are treated specially, and re-emitted -// if they are listened for after emitting. -const isEndish = ev => - ev === 'end' || - ev === 'finish' || - ev === 'prefinish' + if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) { + return false + } + + if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) { + return false + } + + if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) { + return false + } + + if (this.options.integrity) { + return ssri.parse(this.options.integrity).match(this.entry.integrity) + } -const isArrayBuffer = b => b instanceof ArrayBuffer || - typeof b === 'object' && - b.constructor && - b.constructor.name === 'ArrayBuffer' && - b.byteLength >= 0 + return true + } -const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + // returns true if the request and response allow caching + storable () { + return this.policy.storable() + } -class Pipe { - constructor (src, dest, opts) { - this.src = src - this.dest = dest - this.opts = opts - this.ondrain = () => src[RESUME]() - dest.on('drain', this.ondrain) + // NOTE: this is a hack to avoid parsing the cache-control + // header ourselves, it returns true if the response's + // cache-control contains must-revalidate + get mustRevalidate () { + return !!this.policy._rescc['must-revalidate'] } - unpipe () { - this.dest.removeListener('drain', this.ondrain) + + // returns true if the cached response requires revalidation + // for the given request + needsRevalidation (request) { + const _req = requestObject(request) + // force method to GET because we only cache GETs + // but can serve a HEAD from a cached GET + _req.method = 'GET' + return !this.policy.satisfiesWithoutRevalidation(_req) } - // istanbul ignore next - only here for the prototype - proxyErrors () {} - end () { - this.unpipe() - if (this.opts.end) - this.dest.end() + + responseHeaders () { + return this.policy.responseHeaders() } -} -class PipeProxyErrors extends Pipe { - unpipe () { - this.src.removeListener('error', this.proxyErrors) - super.unpipe() + // returns a new object containing the appropriate headers + // to send a revalidation request + revalidationHeaders (request) { + const _req = requestObject(request) + return this.policy.revalidationHeaders(_req) } - constructor (src, dest, opts) { - super(src, dest, opts) - this.proxyErrors = er => dest.emit('error', er) - src.on('error', this.proxyErrors) + + // returns true if the request/response was revalidated + // successfully. returns false if a new response was received + revalidated (request, response) { + const _req = requestObject(request) + const _res = responseObject(response) + const policy = this.policy.revalidatedPolicy(_req, _res) + return !policy.modified } } -module.exports = class Minipass extends Stream { - constructor (options) { - super() - this[FLOWING] = false - // whether we're explicitly paused - this[PAUSED] = false - this.pipes = [] - this.buffer = [] - this[OBJECTMODE] = options && options.objectMode || false - if (this[OBJECTMODE]) - this[ENCODING] = null - else - this[ENCODING] = options && options.encoding || null - if (this[ENCODING] === 'buffer') - this[ENCODING] = null - this[ASYNC] = options && !!options.async || false - this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null - this[EOF] = false - this[EMITTED_END] = false - this[EMITTING_END] = false - this[CLOSED] = false - this[EMITTED_ERROR] = null - this.writable = true - this.readable = true - this[BUFFERLENGTH] = 0 - this[DESTROYED] = false - } +module.exports = CachePolicy - get bufferLength () { return this[BUFFERLENGTH] } - get encoding () { return this[ENCODING] } - set encoding (enc) { - if (this[OBJECTMODE]) - throw new Error('cannot set encoding in objectMode') +/***/ }), - if (this[ENCODING] && enc !== this[ENCODING] && - (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error('cannot change encoding') +/***/ 67242: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this[ENCODING] !== enc) { - this[DECODER] = enc ? new SD(enc) : null - if (this.buffer.length) - this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) - } +"use strict"; - this[ENCODING] = enc + +const { FetchError, Request, isRedirect } = __nccwpck_require__(88483) +const url = __nccwpck_require__(87016) + +const CachePolicy = __nccwpck_require__(15281) +const cache = __nccwpck_require__(96807) +const remote = __nccwpck_require__(20766) + +// given a Request, a Response and user options +// return true if the response is a redirect that +// can be followed. we throw errors that will result +// in the fetch being rejected if the redirect is +// possible but invalid for some reason +const canFollowRedirect = (request, response, options) => { + if (!isRedirect(response.status)) { + return false } - setEncoding (enc) { - this.encoding = enc + if (options.redirect === 'manual') { + return false } - get objectMode () { return this[OBJECTMODE] } - set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } + if (options.redirect === 'error') { + throw new FetchError(`redirect mode is set to error: ${request.url}`, + 'no-redirect', { code: 'ENOREDIRECT' }) + } - get ['async'] () { return this[ASYNC] } - set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } + if (!response.headers.has('location')) { + throw new FetchError(`redirect location header missing for: ${request.url}`, + 'no-location', { code: 'EINVALIDREDIRECT' }) + } - write (chunk, encoding, cb) { - if (this[EOF]) - throw new Error('write after end') + if (request.counter >= request.follow) { + throw new FetchError(`maximum redirect reached at: ${request.url}`, + 'max-redirect', { code: 'EMAXREDIRECT' }) + } - if (this[DESTROYED]) { - this.emit('error', Object.assign( - new Error('Cannot call write after a stream was destroyed'), - { code: 'ERR_STREAM_DESTROYED' } - )) - return true - } + return true +} - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +// given a Request, a Response, and the user's options return an object +// with a new Request and a new options object that will be used for +// following the redirect +const getRedirect = (request, response, options) => { + const _opts = { ...options } + const location = response.headers.get('location') + const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url) + // Comment below is used under the following license: + /** + * @license + * Copyright (c) 2010-2012 Mikeal Rogers + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS + * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ - if (!encoding) - encoding = 'utf8' + // Remove authorization if changing hostnames (but not if just + // changing ports or protocols). This matches the behavior of request: + // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138 + if (new url.URL(request.url).hostname !== redirectUrl.hostname) { + request.headers.delete('authorization') + request.headers.delete('cookie') + } - const fn = this[ASYNC] ? defer : f => f() + // for POST request with 301/302 response, or any request with 303 response, + // use GET when following redirect + if ( + response.status === 303 || + (request.method === 'POST' && [301, 302].includes(response.status)) + ) { + _opts.method = 'GET' + _opts.body = null + request.headers.delete('content-length') + } - // convert array buffers and typed array views into buffers - // at some point in the future, we may want to do the opposite! - // leave strings and buffers as-is - // anything else switches us into object mode - if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { - if (isArrayBufferView(chunk)) - chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) - else if (isArrayBuffer(chunk)) - chunk = Buffer.from(chunk) - else if (typeof chunk !== 'string') - // use the setter so we throw if we have encoding set - this.objectMode = true - } + _opts.headers = {} + request.headers.forEach((value, key) => { + _opts.headers[key] = value + }) - // handle object mode up front, since it's simpler - // this yields better performance, fewer checks later. - if (this[OBJECTMODE]) { - /* istanbul ignore if - maybe impossible? */ - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) + _opts.counter = ++request.counter + const redirectReq = new Request(url.format(redirectUrl), _opts) + return { + request: redirectReq, + options: _opts, + } +} - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) +const fetch = async (request, options) => { + const response = CachePolicy.storable(request, options) + ? await cache(request, options) + : await remote(request, options) - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') + // if the request wasn't a GET or HEAD, and the response + // status is between 200 and 399 inclusive, invalidate the + // request url + if (!['GET', 'HEAD'].includes(request.method) && + response.status >= 200 && + response.status <= 399) { + await cache.invalidate(request, options) + } - if (cb) - fn(cb) + if (!canFollowRedirect(request, response, options)) { + return response + } - return this.flowing - } + const redirect = getRedirect(request, response, options) + return fetch(redirect.request, redirect.options) +} - // at this point the chunk is a buffer or string - // don't buffer it up or send it to the decoder - if (!chunk.length) { - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - fn(cb) - return this.flowing - } +module.exports = fetch - // fast-path writing strings of same encoding to a stream with - // an empty buffer, skipping the buffer/decoder dance - if (typeof chunk === 'string' && - // unless it is a string already ready for us to use - !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { - chunk = Buffer.from(chunk, encoding) - } - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk) +/***/ }), - // Note: flushing CAN potentially switch us into not-flowing mode - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) +/***/ 39310: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) +const { FetchError, Headers, Request, Response } = __nccwpck_require__(88483) - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') +const configureOptions = __nccwpck_require__(99824) +const fetch = __nccwpck_require__(67242) - if (cb) - fn(cb) +const makeFetchHappen = (url, opts) => { + const options = configureOptions(opts) - return this.flowing - } + const request = new Request(url, options) + return fetch(request, options) +} - read (n) { - if (this[DESTROYED]) - return null +makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => { + if (typeof defaultUrl === 'object') { + defaultOptions = defaultUrl + defaultUrl = null + } - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { - this[MAYBE_EMIT_END]() - return null + const defaultedFetch = (url, options = {}) => { + const finalUrl = url || defaultUrl + const finalOptions = { + ...defaultOptions, + ...options, + headers: { + ...defaultOptions.headers, + ...options.headers, + }, } + return wrappedFetch(finalUrl, finalOptions) + } - if (this[OBJECTMODE]) - n = null + defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) => + makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch) + return defaultedFetch +} - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = [this.buffer.join('')] - else - this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] - } +module.exports = makeFetchHappen +module.exports.FetchError = FetchError +module.exports.Headers = Headers +module.exports.Request = Request +module.exports.Response = Response - const ret = this[READ](n || null, this.buffer[0]) - this[MAYBE_EMIT_END]() - return ret - } - [READ] (n, chunk) { - if (n === chunk.length || n === null) - this[BUFFERSHIFT]() - else { - this.buffer[0] = chunk.slice(n) - chunk = chunk.slice(0, n) - this[BUFFERLENGTH] -= n - } +/***/ }), - this.emit('data', chunk) +/***/ 99824: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!this.buffer.length && !this[EOF]) - this.emit('drain') +const dns = __nccwpck_require__(72250) - return chunk - } +const conditionalHeaders = [ + 'if-modified-since', + 'if-none-match', + 'if-unmodified-since', + 'if-match', + 'if-range', +] - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - if (cb) - this.once('end', cb) - this[EOF] = true - this.writable = false +const configureOptions = (opts) => { + const { strictSSL, ...options } = { ...opts } + options.method = options.method ? options.method.toUpperCase() : 'GET' - // if we haven't written anything, then go ahead and emit, - // even if we're not reading. - // we'll re-emit if a new 'end' listener is added anyway. - // This makes MP more suitable to write-only use cases. - if (this.flowing || !this[PAUSED]) - this[MAYBE_EMIT_END]() - return this + if (strictSSL === undefined || strictSSL === null) { + options.rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0' + } else { + options.rejectUnauthorized = strictSSL !== false } - // don't let the internal resume be overwritten - [RESUME] () { - if (this[DESTROYED]) - return - - this[PAUSED] = false - this[FLOWING] = true - this.emit('resume') - if (this.buffer.length) - this[FLUSH]() - else if (this[EOF]) - this[MAYBE_EMIT_END]() - else - this.emit('drain') + if (!options.retry) { + options.retry = { retries: 0 } + } else if (typeof options.retry === 'string') { + const retries = parseInt(options.retry, 10) + if (isFinite(retries)) { + options.retry = { retries } + } else { + options.retry = { retries: 0 } + } + } else if (typeof options.retry === 'number') { + options.retry = { retries: options.retry } + } else { + options.retry = { retries: 0, ...options.retry } } - resume () { - return this[RESUME]() - } + options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns } - pause () { - this[FLOWING] = false - this[PAUSED] = true + options.cache = options.cache || 'default' + if (options.cache === 'default') { + const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => { + return conditionalHeaders.includes(name.toLowerCase()) + }) + if (hasConditionalHeader) { + options.cache = 'no-store' + } } - get destroyed () { - return this[DESTROYED] - } + options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || [] - get flowing () { - return this[FLOWING] + // cacheManager is deprecated, but if it's set and + // cachePath is not we should copy it to the new field + if (options.cacheManager && !options.cachePath) { + options.cachePath = options.cacheManager } - get paused () { - return this[PAUSED] - } + return options +} - [BUFFERPUSH] (chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1 - else - this[BUFFERLENGTH] += chunk.length - this.buffer.push(chunk) - } +module.exports = configureOptions - [BUFFERSHIFT] () { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1 - else - this[BUFFERLENGTH] -= this.buffer[0].length - } - return this.buffer.shift() - } - [FLUSH] (noDrain) { - do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) +/***/ }), - if (!noDrain && !this.buffer.length && !this[EOF]) - this.emit('drain') - } +/***/ 22314: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - [FLUSHCHUNK] (chunk) { - return chunk ? (this.emit('data', chunk), this.flowing) : false - } +"use strict"; - pipe (dest, opts) { - if (this[DESTROYED]) - return - const ended = this[EMITTED_END] - opts = opts || {} - if (dest === proc.stdout || dest === proc.stderr) - opts.end = false - else - opts.end = opts.end !== false - opts.proxyErrors = !!opts.proxyErrors +const MinipassPipeline = __nccwpck_require__(52899) - // piping an ended stream ends immediately - if (ended) { - if (opts.end) - dest.end() - } else { - this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) - : new PipeProxyErrors(this, dest, opts)) - if (this[ASYNC]) - defer(() => this[RESUME]()) - else - this[RESUME]() - } +class CachingMinipassPipeline extends MinipassPipeline { + #events = [] + #data = new Map() + + constructor (opts, ...streams) { + // CRITICAL: do NOT pass the streams to the call to super(), this will start + // the flow of data and potentially cause the events we need to catch to emit + // before we've finished our own setup. instead we call super() with no args, + // finish our setup, and then push the streams into ourselves to start the + // data flow + super() + this.#events = opts.events - return dest + /* istanbul ignore next - coverage disabled because this is pointless to test here */ + if (streams.length) { + this.push(...streams) + } } - unpipe (dest) { - const p = this.pipes.find(p => p.dest === dest) - if (p) { - this.pipes.splice(this.pipes.indexOf(p), 1) - p.unpipe() + on (event, handler) { + if (this.#events.includes(event) && this.#data.has(event)) { + return handler(...this.#data.get(event)) } - } - addListener (ev, fn) { - return this.on(ev, fn) + return super.on(event, handler) } - on (ev, fn) { - const ret = super.on(ev, fn) - if (ev === 'data' && !this.pipes.length && !this.flowing) - this[RESUME]() - else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) - super.emit('readable') - else if (isEndish(ev) && this[EMITTED_END]) { - super.emit(ev) - this.removeAllListeners(ev) - } else if (ev === 'error' && this[EMITTED_ERROR]) { - if (this[ASYNC]) - defer(() => fn.call(this, this[EMITTED_ERROR])) - else - fn.call(this, this[EMITTED_ERROR]) + emit (event, ...data) { + if (this.#events.includes(event)) { + this.#data.set(event, data) } - return ret - } - get emittedEnd () { - return this[EMITTED_END] + return super.emit(event, ...data) } +} - [MAYBE_EMIT_END] () { - if (!this[EMITTING_END] && - !this[EMITTED_END] && - !this[DESTROYED] && - this.buffer.length === 0 && - this[EOF]) { - this[EMITTING_END] = true - this.emit('end') - this.emit('prefinish') - this.emit('finish') - if (this[CLOSED]) - this.emit('close') - this[EMITTING_END] = false - } - } +module.exports = CachingMinipassPipeline - emit (ev, data, ...extra) { - // error and close are only events allowed after calling destroy() - if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) - return - else if (ev === 'data') { - return !data ? false - : this[ASYNC] ? defer(() => this[EMITDATA](data)) - : this[EMITDATA](data) - } else if (ev === 'end') { - return this[EMITEND]() - } else if (ev === 'close') { - this[CLOSED] = true - // don't emit close before 'end' and 'finish' - if (!this[EMITTED_END] && !this[DESTROYED]) - return - const ret = super.emit('close') - this.removeAllListeners('close') - return ret - } else if (ev === 'error') { - this[EMITTED_ERROR] = data - const ret = super.emit('error', data) - this[MAYBE_EMIT_END]() - return ret - } else if (ev === 'resume') { - const ret = super.emit('resume') - this[MAYBE_EMIT_END]() - return ret - } else if (ev === 'finish' || ev === 'prefinish') { - const ret = super.emit(ev) - this.removeAllListeners(ev) - return ret - } - // Some other unknown event - const ret = super.emit(ev, data, ...extra) - this[MAYBE_EMIT_END]() - return ret - } +/***/ }), - [EMITDATA] (data) { - for (const p of this.pipes) { - if (p.dest.write(data) === false) - this.pause() - } - const ret = super.emit('data', data) - this[MAYBE_EMIT_END]() - return ret - } +/***/ 20766: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - [EMITEND] () { - if (this[EMITTED_END]) - return +const { Minipass } = __nccwpck_require__(78275) +const fetch = __nccwpck_require__(88483) +const promiseRetry = __nccwpck_require__(90390) +const ssri = __nccwpck_require__(68951) +const { log } = __nccwpck_require__(26687) - this[EMITTED_END] = true - this.readable = false - if (this[ASYNC]) - defer(() => this[EMITEND2]()) - else - this[EMITEND2]() - } +const CachingMinipassPipeline = __nccwpck_require__(22314) +const { getAgent } = __nccwpck_require__(57995) +const pkg = __nccwpck_require__(96734) - [EMITEND2] () { - if (this[DECODER]) { - const data = this[DECODER].end() - if (data) { - for (const p of this.pipes) { - p.dest.write(data) - } - super.emit('data', data) - } - } +const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})` - for (const p of this.pipes) { - p.end() - } - const ret = super.emit('end') - this.removeAllListeners('end') - return ret - } +const RETRY_ERRORS = [ + 'ECONNRESET', // remote socket closed on us + 'ECONNREFUSED', // remote host refused to open connection + 'EADDRINUSE', // failed to bind to a local port (proxy?) + 'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW + // from @npmcli/agent + 'ECONNECTIONTIMEOUT', + 'EIDLETIMEOUT', + 'ERESPONSETIMEOUT', + 'ETRANSFERTIMEOUT', + // Known codes we do NOT retry on: + // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline) + // EINVALIDPROXY // invalid protocol from @npmcli/agent + // EINVALIDRESPONSE // invalid status code from @npmcli/agent +] - // const all = await stream.collect() - collect () { - const buf = [] - if (!this[OBJECTMODE]) - buf.dataLength = 0 - // set the promise first, in case an error is raised - // by triggering the flow here. - const p = this.promise() - this.on('data', c => { - buf.push(c) - if (!this[OBJECTMODE]) - buf.dataLength += c.length - }) - return p.then(() => buf) - } +const RETRY_TYPES = [ + 'request-timeout', +] - // const data = await stream.concat() - concat () { - return this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this.collect().then(buf => - this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) +// make a request directly to the remote source, +// retrying certain classes of errors as well as +// following redirects (through the cache if necessary) +// and verifying response integrity +const remoteFetch = (request, options) => { + // options.signal is intended for the fetch itself, not the agent. Attaching it to the agent will re-use that signal across multiple requests, which prevents any connections beyond the first one. + const agent = getAgent(request.url, { ...options, signal: undefined }) + if (!request.headers.has('connection')) { + request.headers.set('connection', agent ? 'keep-alive' : 'close') } - // stream.promise().then(() => done, er => emitted error) - promise () { - return new Promise((resolve, reject) => { - this.on(DESTROYED, () => reject(new Error('stream destroyed'))) - this.on('error', er => reject(er)) - this.on('end', () => resolve()) - }) + if (!request.headers.has('user-agent')) { + request.headers.set('user-agent', USER_AGENT) } - // for await (let chunk of stream) - [ASYNCITERATOR] () { - const next = () => { - const res = this.read() - if (res !== null) - return Promise.resolve({ done: false, value: res }) - - if (this[EOF]) - return Promise.resolve({ done: true }) + // keep our own options since we're overriding the agent + // and the redirect mode + const _opts = { + ...options, + agent, + redirect: 'manual', + } - let resolve = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - resolve({ done: true }) + return promiseRetry(async (retryHandler, attemptNum) => { + const req = new fetch.Request(request, _opts) + try { + let res = await fetch(req, _opts) + if (_opts.integrity && res.status === 200) { + // we got a 200 response and the user has specified an expected + // integrity value, so wrap the response in an ssri stream to verify it + const integrityStream = ssri.integrityStream({ + algorithms: _opts.algorithms, + integrity: _opts.integrity, + size: _opts.size, + }) + const pipeline = new CachingMinipassPipeline({ + events: ['integrity', 'size'], + }, res.body, integrityStream) + // we also propagate the integrity and size events out to the pipeline so we can use + // this new response body as an integrityEmitter for cacache + integrityStream.on('integrity', i => pipeline.emit('integrity', i)) + integrityStream.on('size', s => pipeline.emit('size', s)) + res = new fetch.Response(pipeline, res) + // set an explicit flag so we know if our response body will emit integrity and size + res.body.hasIntegrityEmitter = true } - const ondestroy = () => onerr(new Error('stream destroyed')) - return new Promise((res, rej) => { - reject = rej - resolve = res - this.once(DESTROYED, ondestroy) - this.once('error', onerr) - this.once('end', onend) - this.once('data', ondata) - }) - } - return { next } - } + res.headers.set('x-fetch-attempts', attemptNum) - // for (let chunk of stream) - [ITERATOR] () { - const next = () => { - const value = this.read() - const done = value === null - return { value, done } - } - return { next } - } + // do not retry POST requests, or requests with a streaming body + // do retry requests with a 408, 420, 429 or 500+ status in the response + const isStream = Minipass.isStream(req.body) + const isRetriable = req.method !== 'POST' && + !isStream && + ([408, 420, 429].includes(res.status) || res.status >= 500) - destroy (er) { - if (this[DESTROYED]) { - if (er) - this.emit('error', er) - else - this.emit(DESTROYED) - return this - } + if (isRetriable) { + if (typeof options.onRetry === 'function') { + options.onRetry(res) + } - this[DESTROYED] = true + /* eslint-disable-next-line max-len */ + log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`) + return retryHandler(res) + } - // throw away all buffered data, it's never coming out - this.buffer.length = 0 - this[BUFFERLENGTH] = 0 + return res + } catch (err) { + const code = (err.code === 'EPROMISERETRY') + ? err.retried.code + : err.code - if (typeof this.close === 'function' && !this[CLOSED]) - this.close() + // err.retried will be the thing that was thrown from above + // if it's a response, we just got a bad status code and we + // can re-throw to allow the retry + const isRetryError = err.retried instanceof fetch.Response || + (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type)) - if (er) - this.emit('error', er) - else // if no error to emit, still reject pending promises - this.emit(DESTROYED) + if (req.method === 'POST' || isRetryError) { + throw err + } - return this - } + if (typeof options.onRetry === 'function') { + options.onRetry(err) + } - static isStream (s) { - return !!s && (s instanceof Minipass || s instanceof Stream || - s instanceof EE && ( - typeof s.pipe === 'function' || // readable - (typeof s.write === 'function' && typeof s.end === 'function') // writable - )) - } + log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`) + return retryHandler(err) + } + }, options.retry).catch((err) => { + // don't reject for http errors, just return them + if (err.status >= 400 && err.type !== 'system') { + return err + } + + throw err + }) } +module.exports = remoteFetch + /***/ }), -/***/ 52899: +/***/ 43772: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Minipass = __nccwpck_require__(45485) -const EE = __nccwpck_require__(24434) -const isStream = s => s && s instanceof EE && ( - typeof s.pipe === 'function' || // readable - (typeof s.write === 'function' && typeof s.end === 'function') // writable -) +module.exports = minimatch +minimatch.Minimatch = Minimatch -const _head = Symbol('_head') -const _tail = Symbol('_tail') -const _linkStreams = Symbol('_linkStreams') -const _setHead = Symbol('_setHead') -const _setTail = Symbol('_setTail') -const _onError = Symbol('_onError') -const _onData = Symbol('_onData') -const _onEnd = Symbol('_onEnd') -const _onDrain = Symbol('_onDrain') -const _streams = Symbol('_streams') -class Pipeline extends Minipass { - constructor (opts, ...streams) { - if (isStream(opts)) { - streams.unshift(opts) - opts = {} - } +var path = (function () { try { return __nccwpck_require__(16928) } catch (e) {}}()) || { + sep: '/' +} +minimatch.sep = path.sep - super(opts) - this[_streams] = [] - if (streams.length) - this.push(...streams) - } +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __nccwpck_require__(94691) - [_linkStreams] (streams) { - // reduce takes (left,right), and we return right to make it the - // new left value. - return streams.reduce((src, dest) => { - src.on('error', er => dest.emit('error', er)) - src.pipe(dest) - return dest - }) - } +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} - push (...streams) { - this[_streams].push(...streams) - if (this[_tail]) - streams.unshift(this[_tail]) +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - const linkRet = this[_linkStreams](streams) +// * => any number of characters +var star = qmark + '*?' - this[_setTail](linkRet) - if (!this[_head]) - this[_setHead](streams[0]) - } +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - unshift (...streams) { - this[_streams].unshift(...streams) - if (this[_head]) - streams.push(this[_head]) +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - const linkRet = this[_linkStreams](streams) - this[_setHead](streams[0]) - if (!this[_tail]) - this[_setTail](linkRet) - } +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - destroy (er) { - // set fire to the whole thing. - this[_streams].forEach(s => - typeof s.destroy === 'function' && s.destroy()) - return super.destroy(er) - } +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} - // readable interface -> tail - [_setTail] (stream) { - this[_tail] = stream - stream.on('error', er => this[_onError](stream, er)) - stream.on('data', chunk => this[_onData](stream, chunk)) - stream.on('end', () => this[_onEnd](stream)) - stream.on('finish', () => this[_onEnd](stream)) - } +// normalizes slashes. +var slashSplit = /\/+/ - // errors proxied down the pipeline - // they're considered part of the "read" interface - [_onError] (stream, er) { - if (stream === this[_tail]) - this.emit('error', er) - } - [_onData] (stream, chunk) { - if (stream === this[_tail]) - super.write(chunk) - } - [_onEnd] (stream) { - if (stream === this[_tail]) - super.end() +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) } - pause () { - super.pause() - return this[_tail] && this[_tail].pause && this[_tail].pause() +} + +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch } - // NB: Minipass calls its internal private [RESUME] method during - // pipe drains, to avoid hazards where stream.resume() is overridden. - // Thus, we need to listen to the resume *event*, not override the - // resume() method, and proxy *that* to the tail. - emit (ev, ...args) { - if (ev === 'resume' && this[_tail] && this[_tail].resume) - this[_tail].resume() - return super.emit(ev, ...args) + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) } - // writable interface -> head - [_setHead] (stream) { - this[_head] = stream - stream.on('drain', () => this[_onDrain](stream)) - } - [_onDrain] (stream) { - if (stream === this[_head]) - this.emit('drain') + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) } - write (chunk, enc, cb) { - return this[_head].write(chunk, enc, cb) && - (this.flowing || this.buffer.length === 0) + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch } - end (chunk, enc, cb) { - this[_head].end(chunk, enc, cb) - return this + + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) } -} -module.exports = Pipeline + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) + } -/***/ }), + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } -/***/ 45485: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } -"use strict"; + return m +} -const proc = typeof process === 'object' && process ? process : { - stdout: null, - stderr: null, +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch } -const EE = __nccwpck_require__(24434) -const Stream = __nccwpck_require__(2203) -const SD = (__nccwpck_require__(13193).StringDecoder) -const EOF = Symbol('EOF') -const MAYBE_EMIT_END = Symbol('maybeEmitEnd') -const EMITTED_END = Symbol('emittedEnd') -const EMITTING_END = Symbol('emittingEnd') -const EMITTED_ERROR = Symbol('emittedError') -const CLOSED = Symbol('closed') -const READ = Symbol('read') -const FLUSH = Symbol('flush') -const FLUSHCHUNK = Symbol('flushChunk') -const ENCODING = Symbol('encoding') -const DECODER = Symbol('decoder') -const FLOWING = Symbol('flowing') -const PAUSED = Symbol('paused') -const RESUME = Symbol('resume') -const BUFFERLENGTH = Symbol('bufferLength') -const BUFFERPUSH = Symbol('bufferPush') -const BUFFERSHIFT = Symbol('bufferShift') -const OBJECTMODE = Symbol('objectMode') -const DESTROYED = Symbol('destroyed') -const EMITDATA = Symbol('emitData') -const EMITEND = Symbol('emitEnd') -const EMITEND2 = Symbol('emitEnd2') -const ASYNC = Symbol('async') +function minimatch (p, pattern, options) { + assertValidPattern(pattern) -const defer = fn => Promise.resolve().then(fn) + if (!options) options = {} -// TODO remove when Node v8 support drops -const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' -const ASYNCITERATOR = doIter && Symbol.asyncIterator - || Symbol('asyncIterator not implemented') -const ITERATOR = doIter && Symbol.iterator - || Symbol('iterator not implemented') + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } -// events that mean 'the stream is over' -// these are treated specially, and re-emitted -// if they are listened for after emitting. -const isEndish = ev => - ev === 'end' || - ev === 'finish' || - ev === 'prefinish' + return new Minimatch(pattern, options).match(p) +} -const isArrayBuffer = b => b instanceof ArrayBuffer || - typeof b === 'object' && - b.constructor && - b.constructor.name === 'ArrayBuffer' && - b.byteLength >= 0 +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } -const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + assertValidPattern(pattern) -class Pipe { - constructor (src, dest, opts) { - this.src = src - this.dest = dest - this.opts = opts - this.ondrain = () => src[RESUME]() - dest.on('drain', this.ondrain) - } - unpipe () { - this.dest.removeListener('drain', this.ondrain) - } - // istanbul ignore next - only here for the prototype - proxyErrors () {} - end () { - this.unpipe() - if (this.opts.end) - this.dest.end() - } -} + if (!options) options = {} -class PipeProxyErrors extends Pipe { - unpipe () { - this.src.removeListener('error', this.proxyErrors) - super.unpipe() - } - constructor (src, dest, opts) { - super(src, dest, opts) - this.proxyErrors = er => dest.emit('error', er) - src.on('error', this.proxyErrors) - } -} + pattern = pattern.trim() -module.exports = class Minipass extends Stream { - constructor (options) { - super() - this[FLOWING] = false - // whether we're explicitly paused - this[PAUSED] = false - this.pipes = [] - this.buffer = [] - this[OBJECTMODE] = options && options.objectMode || false - if (this[OBJECTMODE]) - this[ENCODING] = null - else - this[ENCODING] = options && options.encoding || null - if (this[ENCODING] === 'buffer') - this[ENCODING] = null - this[ASYNC] = options && !!options.async || false - this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null - this[EOF] = false - this[EMITTED_END] = false - this[EMITTING_END] = false - this[CLOSED] = false - this[EMITTED_ERROR] = null - this.writable = true - this.readable = true - this[BUFFERLENGTH] = 0 - this[DESTROYED] = false + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') } - get bufferLength () { return this[BUFFERLENGTH] } + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial - get encoding () { return this[ENCODING] } - set encoding (enc) { - if (this[OBJECTMODE]) - throw new Error('cannot set encoding in objectMode') + // make the set of regexps etc. + this.make() +} - if (this[ENCODING] && enc !== this[ENCODING] && - (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error('cannot change encoding') +Minimatch.prototype.debug = function () {} - if (this[ENCODING] !== enc) { - this[DECODER] = enc ? new SD(enc) : null - if (this.buffer.length) - this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) - } +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options - this[ENCODING] = enc + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return } - - setEncoding (enc) { - this.encoding = enc + if (!pattern) { + this.empty = true + return } - get objectMode () { return this[OBJECTMODE] } - set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } + // step 1: figure out negation, etc. + this.parseNegate() - get ['async'] () { return this[ASYNC] } - set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } + // step 2: expand braces + var set = this.globSet = this.braceExpand() - write (chunk, encoding, cb) { - if (this[EOF]) - throw new Error('write after end') + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } - if (this[DESTROYED]) { - this.emit('error', Object.assign( - new Error('Cannot call write after a stream was destroyed'), - { code: 'ERR_STREAM_DESTROYED' } - )) - return true - } + this.debug(this.pattern, set) - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) - if (!encoding) - encoding = 'utf8' + this.debug(this.pattern, set) - const fn = this[ASYNC] ? defer : f => f() + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) - // convert array buffers and typed array views into buffers - // at some point in the future, we may want to do the opposite! - // leave strings and buffers as-is - // anything else switches us into object mode - if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { - if (isArrayBufferView(chunk)) - chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) - else if (isArrayBuffer(chunk)) - chunk = Buffer.from(chunk) - else if (typeof chunk !== 'string') - // use the setter so we throw if we have encoding set - this.objectMode = true - } + this.debug(this.pattern, set) - // handle object mode up front, since it's simpler - // this yields better performance, fewer checks later. - if (this[OBJECTMODE]) { - /* istanbul ignore if - maybe impossible? */ - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) + this.debug(this.pattern, set) - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') + this.set = set +} - if (cb) - fn(cb) +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 - return this.flowing - } + if (options.nonegate) return - // at this point the chunk is a buffer or string - // don't buffer it up or send it to the decoder - if (!chunk.length) { - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - fn(cb) - return this.flowing - } + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } - // fast-path writing strings of same encoding to a stream with - // an empty buffer, skipping the buffer/decoder dance - if (typeof chunk === 'string' && - // unless it is a string already ready for us to use - !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { - chunk = Buffer.from(chunk, encoding) + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} } + } - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk) + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern - // Note: flushing CAN potentially switch us into not-flowing mode - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) + assertValidPattern(pattern) - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') + return expand(pattern) +} - if (cb) - fn(cb) +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } - return this.flowing + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') } +} - read (n) { - if (this[DESTROYED]) - return null +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { - this[MAYBE_EMIT_END]() - return null - } + var options = this.options - if (this[OBJECTMODE]) - n = null + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = [this.buffer.join('')] - else - this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] - } + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this - const ret = this[READ](n || null, this.buffer[0]) - this[MAYBE_EMIT_END]() - return ret + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } } - [READ] (n, chunk) { - if (n === chunk.length || n === null) - this[BUFFERSHIFT]() - else { - this.buffer[0] = chunk.slice(n) - chunk = chunk.slice(0, n) - this[BUFFERLENGTH] -= n + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue } - this.emit('data', chunk) + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } - if (!this.buffer.length && !this[EOF]) - this.emit('drain') + case '\\': + clearStateChar() + escaping = true + continue - return chunk - } + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - if (cb) - this.once('end', cb) - this[EOF] = true - this.writable = false + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue - // if we haven't written anything, then go ahead and emit, - // even if we're not reading. - // we'll re-emit if a new 'end' listener is added anyway. - // This makes MP more suitable to write-only use cases. - if (this.flowing || !this[PAUSED]) - this[MAYBE_EMIT_END]() - return this - } + case '(': + if (inClass) { + re += '(' + continue + } - // don't let the internal resume be overwritten - [RESUME] () { - if (this[DESTROYED]) - return + if (!stateChar) { + re += '\\(' + continue + } - this[PAUSED] = false - this[FLOWING] = true - this.emit('resume') - if (this.buffer.length) - this[FLUSH]() - else if (this[EOF]) - this[MAYBE_EMIT_END]() - else - this.emit('drain') - } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue - resume () { - return this[RESUME]() - } + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } - pause () { - this[FLOWING] = false - this[PAUSED] = true - } + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue - get destroyed () { - return this[DESTROYED] - } + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } - get flowing () { - return this[FLOWING] - } + clearStateChar() + re += '|' + continue - get paused () { - return this[PAUSED] - } + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() - [BUFFERPUSH] (chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1 - else - this[BUFFERLENGTH] += chunk.length - this.buffer.push(chunk) - } + if (inClass) { + re += '\\' + c + continue + } - [BUFFERSHIFT] () { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1 - else - this[BUFFERLENGTH] -= this.buffer[0].length - } - return this.buffer.shift() - } + inClass = true + classStart = i + reClassStart = re.length + re += c + continue - [FLUSH] (noDrain) { - do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } - if (!noDrain && !this.buffer.length && !this[EOF]) - this.emit('drain') - } + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } - [FLUSHCHUNK] (chunk) { - return chunk ? (this.emit('data', chunk), this.flowing) : false - } + // finish up the class. + hasMagic = true + inClass = false + re += c + continue - pipe (dest, opts) { - if (this[DESTROYED]) - return + default: + // swallow any state char that wasn't consumed + clearStateChar() - const ended = this[EMITTED_END] - opts = opts || {} - if (dest === proc.stdout || dest === proc.stderr) - opts.end = false - else - opts.end = opts.end !== false - opts.proxyErrors = !!opts.proxyErrors + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } - // piping an ended stream ends immediately - if (ended) { - if (opts.end) - dest.end() - } else { - this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) - : new PipeProxyErrors(this, dest, opts)) - if (this[ASYNC]) - defer(() => this[RESUME]()) - else - this[RESUME]() - } + re += c - return dest - } + } // switch + } // for - unpipe (dest) { - const p = this.pipes.find(p => p.dest === dest) - if (p) { - this.pipes.splice(this.pipes.indexOf(p), 1) - p.unpipe() - } + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] } - addListener (ev, fn) { - return this.on(ev, fn) - } + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } - on (ev, fn) { - const ret = super.on(ev, fn) - if (ev === 'data' && !this.pipes.length && !this.flowing) - this[RESUME]() - else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) - super.emit('readable') - else if (isEndish(ev) && this[EMITTED_END]) { - super.emit(ev) - this.removeAllListeners(ev) - } else if (ev === 'error' && this[EMITTED_ERROR]) { - if (this[ASYNC]) - defer(() => fn.call(this, this[EMITTED_ERROR])) - else - fn.call(this, this[EMITTED_ERROR]) - } - return ret - } + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) - get emittedEnd () { - return this[EMITTED_END] - } + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type - [MAYBE_EMIT_END] () { - if (!this[EMITTING_END] && - !this[EMITTED_END] && - !this[DESTROYED] && - this.buffer.length === 0 && - this[EOF]) { - this[EMITTING_END] = true - this.emit('end') - this.emit('prefinish') - this.emit('finish') - if (this[CLOSED]) - this.emit('close') - this[EMITTING_END] = false - } + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail } - emit (ev, data, ...extra) { - // error and close are only events allowed after calling destroy() - if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) - return - else if (ev === 'data') { - return !data ? false - : this[ASYNC] ? defer(() => this[EMITDATA](data)) - : this[EMITDATA](data) - } else if (ev === 'end') { - return this[EMITEND]() - } else if (ev === 'close') { - this[CLOSED] = true - // don't emit close before 'end' and 'finish' - if (!this[EMITTED_END] && !this[DESTROYED]) - return - const ret = super.emit('close') - this.removeAllListeners('close') - return ret - } else if (ev === 'error') { - this[EMITTED_ERROR] = data - const ret = super.emit('error', data) - this[MAYBE_EMIT_END]() - return ret - } else if (ev === 'resume') { - const ret = super.emit('resume') - this[MAYBE_EMIT_END]() - return ret - } else if (ev === 'finish' || ev === 'prefinish') { - const ret = super.emit(ev) - this.removeAllListeners(ev) - return ret - } - - // Some other unknown event - const ret = super.emit(ev, data, ...extra) - this[MAYBE_EMIT_END]() - return ret + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' } - [EMITDATA] (data) { - for (const p of this.pipes) { - if (p.dest.write(data) === false) - this.pause() - } - const ret = super.emit('data', data) - this[MAYBE_EMIT_END]() - return ret + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true } - [EMITEND] () { - if (this[EMITTED_END]) - return + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] - this[EMITTED_END] = true - this.readable = false - if (this[ASYNC]) - defer(() => this[EMITEND2]()) - else - this[EMITEND2]() - } + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) - [EMITEND2] () { - if (this[DECODER]) { - const data = this[DECODER].end() - if (data) { - for (const p of this.pipes) { - p.dest.write(data) - } - super.emit('data', data) - } + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } + nlAfter = cleanAfter - for (const p of this.pipes) { - p.end() + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' } - const ret = super.emit('end') - this.removeAllListeners('end') - return ret + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe } - // const all = await stream.collect() - collect () { - const buf = [] - if (!this[OBJECTMODE]) - buf.dataLength = 0 - // set the promise first, in case an error is raised - // by triggering the flow here. - const p = this.promise() - this.on('data', c => { - buf.push(c) - if (!this[OBJECTMODE]) - buf.dataLength += c.length - }) - return p.then(() => buf) + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re } - // const data = await stream.concat() - concat () { - return this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this.collect().then(buf => - this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) + if (addPatternStart) { + re = patternStart + re } - // stream.promise().then(() => done, er => emitted error) - promise () { - return new Promise((resolve, reject) => { - this.on(DESTROYED, () => reject(new Error('stream destroyed'))) - this.on('error', er => reject(er)) - this.on('end', () => resolve()) - }) + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] } - // for await (let chunk of stream) - [ASYNCITERATOR] () { - const next = () => { - const res = this.read() - if (res !== null) - return Promise.resolve({ done: false, value: res }) - - if (this[EOF]) - return Promise.resolve({ done: true }) - - let resolve = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - resolve({ done: true }) - } - const ondestroy = () => onerr(new Error('stream destroyed')) - return new Promise((res, rej) => { - reject = rej - resolve = res - this.once(DESTROYED, ondestroy) - this.once('error', onerr) - this.once('end', onend) - this.once('data', ondata) - }) - } - - return { next } + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) } - // for (let chunk of stream) - [ITERATOR] () { - const next = () => { - const value = this.read() - const done = value === null - return { value, done } - } - return { next } + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } - destroy (er) { - if (this[DESTROYED]) { - if (er) - this.emit('error', er) - else - this.emit(DESTROYED) - return this - } - - this[DESTROYED] = true + regExp._glob = pattern + regExp._src = re - // throw away all buffered data, it's never coming out - this.buffer.length = 0 - this[BUFFERLENGTH] = 0 + return regExp +} - if (typeof this.close === 'function' && !this[CLOSED]) - this.close() +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} - if (er) - this.emit('error', er) - else // if no error to emit, still reject pending promises - this.emit(DESTROYED) +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - return this - } + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set - static isStream (s) { - return !!s && (s instanceof Minipass || s instanceof Stream || - s instanceof EE && ( - typeof s.pipe === 'function' || // readable - (typeof s.write === 'function' && typeof s.end === 'function') // writable - )) + if (!set.length) { + this.regexp = false + return this.regexp } -} + var options = this.options + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' -/***/ }), + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') -/***/ 48484: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' -const Minipass = __nccwpck_require__(56670) + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' -class SizeError extends Error { - constructor (found, expect) { - super(`Bad data size: expected ${expect} bytes, but got ${found}`) - this.expect = expect - this.found = found - this.code = 'EBADSIZE' - Error.captureStackTrace(this, this.constructor) + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false } - get name () { - return 'SizeError' + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) } + return list } -class MinipassSized extends Minipass { - constructor (options = {}) { - super(options) +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' - if (options.objectMode) - throw new TypeError(`${ - this.constructor.name - } streams only work with string and buffer data`) + if (f === '/' && partial) return true - this.found = 0 - this.expect = options.size - if (typeof this.expect !== 'number' || - this.expect > Number.MAX_SAFE_INTEGER || - isNaN(this.expect) || - this.expect < 0 || - !isFinite(this.expect) || - this.expect !== Math.floor(this.expect)) - throw new Error('invalid expected size: ' + this.expect) + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') } - write (chunk, encoding, cb) { - const buffer = Buffer.isBuffer(chunk) ? chunk - : typeof chunk === 'string' ? - Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8') - : chunk + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - if (!Buffer.isBuffer(buffer)) { - this.emit('error', new TypeError(`${ - this.constructor.name - } streams only work with string and buffer data`)) - return false - } + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - this.found += buffer.length - if (this.found > this.expect) - this.emit('error', new SizeError(this.found, this.expect)) + var set = this.set + this.debug(this.pattern, 'set', set) - return super.write(chunk, encoding, cb) + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break } - emit (ev, ...data) { - if (ev === 'end') { - if (this.found !== this.expect) - this.emit('error', new SizeError(this.found, this.expect)) + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } - return super.emit(ev, ...data) } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate } -MinipassSized.SizeError = SizeError +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options -module.exports = MinipassSized + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + this.debug('matchOne', file.length, pattern.length) -/***/ }), + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] -/***/ 56670: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.debug(pattern, p, f) -"use strict"; + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false -const proc = typeof process === 'object' && process ? process : { - stdout: null, - stderr: null, -} -const EE = __nccwpck_require__(24434) -const Stream = __nccwpck_require__(2203) -const SD = (__nccwpck_require__(13193).StringDecoder) + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) -const EOF = Symbol('EOF') -const MAYBE_EMIT_END = Symbol('maybeEmitEnd') -const EMITTED_END = Symbol('emittedEnd') -const EMITTING_END = Symbol('emittingEnd') -const EMITTED_ERROR = Symbol('emittedError') -const CLOSED = Symbol('closed') -const READ = Symbol('read') -const FLUSH = Symbol('flush') -const FLUSHCHUNK = Symbol('flushChunk') -const ENCODING = Symbol('encoding') -const DECODER = Symbol('decoder') -const FLOWING = Symbol('flowing') -const PAUSED = Symbol('paused') -const RESUME = Symbol('resume') -const BUFFERLENGTH = Symbol('bufferLength') -const BUFFERPUSH = Symbol('bufferPush') -const BUFFERSHIFT = Symbol('bufferShift') -const OBJECTMODE = Symbol('objectMode') -const DESTROYED = Symbol('destroyed') -const EMITDATA = Symbol('emitData') -const EMITEND = Symbol('emitEnd') -const EMITEND2 = Symbol('emitEnd2') -const ASYNC = Symbol('async') + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } -const defer = fn => Promise.resolve().then(fn) + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] -// TODO remove when Node v8 support drops -const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' -const ASYNCITERATOR = doIter && Symbol.asyncIterator - || Symbol('asyncIterator not implemented') -const ITERATOR = doIter && Symbol.iterator - || Symbol('iterator not implemented') + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) -// events that mean 'the stream is over' -// these are treated specially, and re-emitted -// if they are listened for after emitting. -const isEndish = ev => - ev === 'end' || - ev === 'finish' || - ev === 'prefinish' + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } -const isArrayBuffer = b => b instanceof ArrayBuffer || - typeof b === 'object' && - b.constructor && - b.constructor.name === 'ArrayBuffer' && - b.byteLength >= 0 + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } -const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } -class Pipe { - constructor (src, dest, opts) { - this.src = src - this.dest = dest - this.opts = opts - this.ondrain = () => src[RESUME]() - dest.on('drain', this.ondrain) - } - unpipe () { - this.dest.removeListener('drain', this.ondrain) + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false } - // istanbul ignore next - only here for the prototype - proxyErrors () {} - end () { - this.unpipe() - if (this.opts.end) - this.dest.end() + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') } -class PipeProxyErrors extends Pipe { - unpipe () { - this.src.removeListener('error', this.proxyErrors) - super.unpipe() +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + + +/***/ }), + +/***/ 11757: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { Minipass } = __nccwpck_require__(78275) +const _data = Symbol('_data') +const _length = Symbol('_length') +class Collect extends Minipass { + constructor (options) { + super(options) + this[_data] = [] + this[_length] = 0 } - constructor (src, dest, opts) { - super(src, dest, opts) - this.proxyErrors = er => dest.emit('error', er) - src.on('error', this.proxyErrors) + write (chunk, encoding, cb) { + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + + if (!encoding) + encoding = 'utf8' + + const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) + this[_data].push(c) + this[_length] += c.length + if (cb) + cb() + return true + } + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + const result = Buffer.concat(this[_data], this[_length]) + super.write(result) + return super.end(cb) } } +module.exports = Collect -module.exports = class Minipass extends Stream { +// it would be possible to DRY this a bit by doing something like +// this.collector = new Collect() and listening on its data event, +// but it's not much code, and we may as well save the extra obj +class CollectPassThrough extends Minipass { constructor (options) { - super() - this[FLOWING] = false - // whether we're explicitly paused - this[PAUSED] = false - this.pipes = [] - this.buffer = [] - this[OBJECTMODE] = options && options.objectMode || false - if (this[OBJECTMODE]) - this[ENCODING] = null - else - this[ENCODING] = options && options.encoding || null - if (this[ENCODING] === 'buffer') - this[ENCODING] = null - this[ASYNC] = options && !!options.async || false - this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null - this[EOF] = false - this[EMITTED_END] = false - this[EMITTING_END] = false - this[CLOSED] = false - this[EMITTED_ERROR] = null - this.writable = true - this.readable = true - this[BUFFERLENGTH] = 0 - this[DESTROYED] = false + super(options) + this[_data] = [] + this[_length] = 0 } + write (chunk, encoding, cb) { + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' - get bufferLength () { return this[BUFFERLENGTH] } + if (!encoding) + encoding = 'utf8' - get encoding () { return this[ENCODING] } - set encoding (enc) { - if (this[OBJECTMODE]) - throw new Error('cannot set encoding in objectMode') + const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) + this[_data].push(c) + this[_length] += c.length + return super.write(chunk, encoding, cb) + } + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + const result = Buffer.concat(this[_data], this[_length]) + this.emit('collect', result) + return super.end(cb) + } +} +module.exports.PassThrough = CollectPassThrough - if (this[ENCODING] && enc !== this[ENCODING] && - (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) - throw new Error('cannot change encoding') - if (this[ENCODING] !== enc) { - this[DECODER] = enc ? new SD(enc) : null - if (this.buffer.length) - this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) - } +/***/ }), - this[ENCODING] = enc +/***/ 57442: +/***/ ((module) => { + +"use strict"; + +class AbortError extends Error { + constructor (message) { + super(message) + this.code = 'FETCH_ABORTED' + this.type = 'aborted' + Error.captureStackTrace(this, this.constructor) } - setEncoding (enc) { - this.encoding = enc + get name () { + return 'AbortError' } - get objectMode () { return this[OBJECTMODE] } - set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } + // don't allow name to be overridden, but don't throw either + set name (s) {} +} +module.exports = AbortError + - get ['async'] () { return this[ASYNC] } - set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } +/***/ }), - write (chunk, encoding, cb) { - if (this[EOF]) - throw new Error('write after end') +/***/ 21256: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this[DESTROYED]) { - this.emit('error', Object.assign( - new Error('Cannot call write after a stream was destroyed'), - { code: 'ERR_STREAM_DESTROYED' } - )) - return true - } +"use strict"; - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' +const { Minipass } = __nccwpck_require__(78275) +const TYPE = Symbol('type') +const BUFFER = Symbol('buffer') - if (!encoding) - encoding = 'utf8' +class Blob { + constructor (blobParts, options) { + this[TYPE] = '' - const fn = this[ASYNC] ? defer : f => f() + const buffers = [] + let size = 0 - // convert array buffers and typed array views into buffers - // at some point in the future, we may want to do the opposite! - // leave strings and buffers as-is - // anything else switches us into object mode - if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { - if (isArrayBufferView(chunk)) - chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) - else if (isArrayBuffer(chunk)) - chunk = Buffer.from(chunk) - else if (typeof chunk !== 'string') - // use the setter so we throw if we have encoding set - this.objectMode = true + if (blobParts) { + const a = blobParts + const length = Number(a.length) + for (let i = 0; i < length; i++) { + const element = a[i] + const buffer = element instanceof Buffer ? element + : ArrayBuffer.isView(element) + ? Buffer.from(element.buffer, element.byteOffset, element.byteLength) + : element instanceof ArrayBuffer ? Buffer.from(element) + : element instanceof Blob ? element[BUFFER] + : typeof element === 'string' ? Buffer.from(element) + : Buffer.from(String(element)) + size += buffer.length + buffers.push(buffer) + } } - // handle object mode up front, since it's simpler - // this yields better performance, fewer checks later. - if (this[OBJECTMODE]) { - /* istanbul ignore if - maybe impossible? */ - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) + this[BUFFER] = Buffer.concat(buffers, size) - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) + const type = options && options.type !== undefined + && String(options.type).toLowerCase() + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type + } + } - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') + get size () { + return this[BUFFER].length + } - if (cb) - fn(cb) + get type () { + return this[TYPE] + } - return this.flowing - } + text () { + return Promise.resolve(this[BUFFER].toString()) + } - // at this point the chunk is a buffer or string - // don't buffer it up or send it to the decoder - if (!chunk.length) { - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') - if (cb) - fn(cb) - return this.flowing - } + arrayBuffer () { + const buf = this[BUFFER] + const off = buf.byteOffset + const len = buf.byteLength + const ab = buf.buffer.slice(off, off + len) + return Promise.resolve(ab) + } - // fast-path writing strings of same encoding to a stream with - // an empty buffer, skipping the buffer/decoder dance - if (typeof chunk === 'string' && - // unless it is a string already ready for us to use - !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { - chunk = Buffer.from(chunk, encoding) - } + stream () { + return new Minipass().end(this[BUFFER]) + } - if (Buffer.isBuffer(chunk) && this[ENCODING]) - chunk = this[DECODER].write(chunk) + slice (start, end, type) { + const size = this.size + const relativeStart = start === undefined ? 0 + : start < 0 ? Math.max(size + start, 0) + : Math.min(start, size) + const relativeEnd = end === undefined ? size + : end < 0 ? Math.max(size + end, 0) + : Math.min(end, size) + const span = Math.max(relativeEnd - relativeStart, 0) - // Note: flushing CAN potentially switch us into not-flowing mode - if (this.flowing && this[BUFFERLENGTH] !== 0) - this[FLUSH](true) + const buffer = this[BUFFER] + const slicedBuffer = buffer.slice( + relativeStart, + relativeStart + span + ) + const blob = new Blob([], { type }) + blob[BUFFER] = slicedBuffer + return blob + } - if (this.flowing) - this.emit('data', chunk) - else - this[BUFFERPUSH](chunk) + get [Symbol.toStringTag] () { + return 'Blob' + } - if (this[BUFFERLENGTH] !== 0) - this.emit('readable') + static get BUFFER () { + return BUFFER + } +} - if (cb) - fn(cb) +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, +}) - return this.flowing - } +module.exports = Blob - read (n) { - if (this[DESTROYED]) - return null - if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { - this[MAYBE_EMIT_END]() - return null - } +/***/ }), - if (this[OBJECTMODE]) - n = null +/***/ 28515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.buffer.length > 1 && !this[OBJECTMODE]) { - if (this.encoding) - this.buffer = [this.buffer.join('')] - else - this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] - } +"use strict"; - const ret = this[READ](n || null, this.buffer[0]) - this[MAYBE_EMIT_END]() - return ret - } +const { Minipass } = __nccwpck_require__(78275) +const MinipassSized = __nccwpck_require__(48484) - [READ] (n, chunk) { - if (n === chunk.length || n === null) - this[BUFFERSHIFT]() - else { - this.buffer[0] = chunk.slice(n) - chunk = chunk.slice(0, n) - this[BUFFERLENGTH] -= n - } +const Blob = __nccwpck_require__(21256) +const { BUFFER } = Blob +const FetchError = __nccwpck_require__(22644) - this.emit('data', chunk) +// optional dependency on 'encoding' +let convert +try { + convert = (__nccwpck_require__(24056)/* .convert */ .C) +} catch (e) { + // defer error until textConverted is called +} - if (!this.buffer.length && !this[EOF]) - this.emit('drain') +const INTERNALS = Symbol('Body internals') +const CONSUME_BODY = Symbol('consumeBody') - return chunk - } +class Body { + constructor (bodyArg, options = {}) { + const { size = 0, timeout = 0 } = options + const body = bodyArg === undefined || bodyArg === null ? null + : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString()) + : isBlob(bodyArg) ? bodyArg + : Buffer.isBuffer(bodyArg) ? bodyArg + : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]' + ? Buffer.from(bodyArg) + : ArrayBuffer.isView(bodyArg) + ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength) + : Minipass.isStream(bodyArg) ? bodyArg + : Buffer.from(String(bodyArg)) - end (chunk, encoding, cb) { - if (typeof chunk === 'function') - cb = chunk, chunk = null - if (typeof encoding === 'function') - cb = encoding, encoding = 'utf8' - if (chunk) - this.write(chunk, encoding) - if (cb) - this.once('end', cb) - this[EOF] = true - this.writable = false + this[INTERNALS] = { + body, + disturbed: false, + error: null, + } - // if we haven't written anything, then go ahead and emit, - // even if we're not reading. - // we'll re-emit if a new 'end' listener is added anyway. - // This makes MP more suitable to write-only use cases. - if (this.flowing || !this[PAUSED]) - this[MAYBE_EMIT_END]() - return this + this.size = size + this.timeout = timeout + + if (Minipass.isStream(body)) { + body.on('error', er => { + const error = er.name === 'AbortError' ? er + : new FetchError(`Invalid response while trying to fetch ${ + this.url}: ${er.message}`, 'system', er) + this[INTERNALS].error = error + }) + } } - // don't let the internal resume be overwritten - [RESUME] () { - if (this[DESTROYED]) - return + get body () { + return this[INTERNALS].body + } - this[PAUSED] = false - this[FLOWING] = true - this.emit('resume') - if (this.buffer.length) - this[FLUSH]() - else if (this[EOF]) - this[MAYBE_EMIT_END]() - else - this.emit('drain') + get bodyUsed () { + return this[INTERNALS].disturbed } - resume () { - return this[RESUME]() + arrayBuffer () { + return this[CONSUME_BODY]().then(buf => + buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)) } - pause () { - this[FLOWING] = false - this[PAUSED] = true + blob () { + const ct = this.headers && this.headers.get('content-type') || '' + return this[CONSUME_BODY]().then(buf => Object.assign( + new Blob([], { type: ct.toLowerCase() }), + { [BUFFER]: buf } + )) } - get destroyed () { - return this[DESTROYED] + async json () { + const buf = await this[CONSUME_BODY]() + try { + return JSON.parse(buf.toString()) + } catch (er) { + throw new FetchError( + `invalid json response body at ${this.url} reason: ${er.message}`, + 'invalid-json' + ) + } } - get flowing () { - return this[FLOWING] + text () { + return this[CONSUME_BODY]().then(buf => buf.toString()) } - get paused () { - return this[PAUSED] + buffer () { + return this[CONSUME_BODY]() } - [BUFFERPUSH] (chunk) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] += 1 - else - this[BUFFERLENGTH] += chunk.length - this.buffer.push(chunk) + textConverted () { + return this[CONSUME_BODY]().then(buf => convertBody(buf, this.headers)) } - [BUFFERSHIFT] () { - if (this.buffer.length) { - if (this[OBJECTMODE]) - this[BUFFERLENGTH] -= 1 - else - this[BUFFERLENGTH] -= this.buffer[0].length + [CONSUME_BODY] () { + if (this[INTERNALS].disturbed) { + return Promise.reject(new TypeError(`body used already for: ${ + this.url}`)) } - return this.buffer.shift() - } - [FLUSH] (noDrain) { - do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) + this[INTERNALS].disturbed = true - if (!noDrain && !this.buffer.length && !this[EOF]) - this.emit('drain') - } + if (this[INTERNALS].error) { + return Promise.reject(this[INTERNALS].error) + } - [FLUSHCHUNK] (chunk) { - return chunk ? (this.emit('data', chunk), this.flowing) : false - } + // body is null + if (this.body === null) { + return Promise.resolve(Buffer.alloc(0)) + } - pipe (dest, opts) { - if (this[DESTROYED]) - return + if (Buffer.isBuffer(this.body)) { + return Promise.resolve(this.body) + } - const ended = this[EMITTED_END] - opts = opts || {} - if (dest === proc.stdout || dest === proc.stderr) - opts.end = false - else - opts.end = opts.end !== false - opts.proxyErrors = !!opts.proxyErrors + const upstream = isBlob(this.body) ? this.body.stream() : this.body - // piping an ended stream ends immediately - if (ended) { - if (opts.end) - dest.end() - } else { - this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) - : new PipeProxyErrors(this, dest, opts)) - if (this[ASYNC]) - defer(() => this[RESUME]()) - else - this[RESUME]() + /* istanbul ignore if: should never happen */ + if (!Minipass.isStream(upstream)) { + return Promise.resolve(Buffer.alloc(0)) } - return dest + const stream = this.size && upstream instanceof MinipassSized ? upstream + : !this.size && upstream instanceof Minipass && + !(upstream instanceof MinipassSized) ? upstream + : this.size ? new MinipassSized({ size: this.size }) + : new Minipass() + + // allow timeout on slow response body, but only if the stream is still writable. this + // makes the timeout center on the socket stream from lib/index.js rather than the + // intermediary minipass stream we create to receive the data + const resTimeout = this.timeout && stream.writable ? setTimeout(() => { + stream.emit('error', new FetchError( + `Response timeout while trying to fetch ${ + this.url} (over ${this.timeout}ms)`, 'body-timeout')) + }, this.timeout) : null + + // do not keep the process open just for this timeout, even + // though we expect it'll get cleared eventually. + if (resTimeout && resTimeout.unref) { + resTimeout.unref() + } + + // do the pipe in the promise, because the pipe() can send too much + // data through right away and upset the MP Sized object + return new Promise((resolve) => { + // if the stream is some other kind of stream, then pipe through a MP + // so we can collect it more easily. + if (stream !== upstream) { + upstream.on('error', er => stream.emit('error', er)) + upstream.pipe(stream) + } + resolve() + }).then(() => stream.concat()).then(buf => { + clearTimeout(resTimeout) + return buf + }).catch(er => { + clearTimeout(resTimeout) + // request was aborted, reject with this Error + if (er.name === 'AbortError' || er.name === 'FetchError') { + throw er + } else if (er.name === 'RangeError') { + throw new FetchError(`Could not create Buffer from response body for ${ + this.url}: ${er.message}`, 'system', er) + } else { + // other errors, such as incorrect content-encoding or content-length + throw new FetchError(`Invalid response body while trying to fetch ${ + this.url}: ${er.message}`, 'system', er) + } + }) } - unpipe (dest) { - const p = this.pipes.find(p => p.dest === dest) - if (p) { - this.pipes.splice(this.pipes.indexOf(p), 1) - p.unpipe() + static clone (instance) { + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used') + } + + const body = instance.body + + // check that body is a stream and not form-data object + // NB: can't clone the form-data object without having it as a dependency + if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') { + // create a dedicated tee stream so that we don't lose data + // potentially sitting in the body stream's buffer by writing it + // immediately to p1 and not having it for p2. + const tee = new Minipass() + const p1 = new Minipass() + const p2 = new Minipass() + tee.on('error', er => { + p1.emit('error', er) + p2.emit('error', er) + }) + body.on('error', er => tee.emit('error', er)) + tee.pipe(p1) + tee.pipe(p2) + body.pipe(tee) + // set instance body to one fork, return the other + instance[INTERNALS].body = p1 + return p2 + } else { + return instance.body } } - addListener (ev, fn) { - return this.on(ev, fn) + static extractContentType (body) { + return body === null || body === undefined ? null + : typeof body === 'string' ? 'text/plain;charset=UTF-8' + : isURLSearchParams(body) + ? 'application/x-www-form-urlencoded;charset=UTF-8' + : isBlob(body) ? body.type || null + : Buffer.isBuffer(body) ? null + : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null + : ArrayBuffer.isView(body) ? null + : typeof body.getBoundary === 'function' + ? `multipart/form-data;boundary=${body.getBoundary()}` + : Minipass.isStream(body) ? null + : 'text/plain;charset=UTF-8' } - on (ev, fn) { - const ret = super.on(ev, fn) - if (ev === 'data' && !this.pipes.length && !this.flowing) - this[RESUME]() - else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) - super.emit('readable') - else if (isEndish(ev) && this[EMITTED_END]) { - super.emit(ev) - this.removeAllListeners(ev) - } else if (ev === 'error' && this[EMITTED_ERROR]) { - if (this[ASYNC]) - defer(() => fn.call(this, this[EMITTED_ERROR])) - else - fn.call(this, this[EMITTED_ERROR]) - } - return ret + static getTotalBytes (instance) { + const { body } = instance + return (body === null || body === undefined) ? 0 + : isBlob(body) ? body.size + : Buffer.isBuffer(body) ? body.length + : body && typeof body.getLengthSync === 'function' && ( + // detect form data input from form-data module + body._lengthRetrievers && + /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) // 2.x + ? body.getLengthSync() + : null } - get emittedEnd () { - return this[EMITTED_END] + static writeToStream (dest, instance) { + const { body } = instance + + if (body === null || body === undefined) { + dest.end() + } else if (Buffer.isBuffer(body) || typeof body === 'string') { + dest.end(body) + } else { + // body is stream or blob + const stream = isBlob(body) ? body.stream() : body + stream.on('error', er => dest.emit('error', er)).pipe(dest) + } + + return dest } +} - [MAYBE_EMIT_END] () { - if (!this[EMITTING_END] && - !this[EMITTED_END] && - !this[DESTROYED] && - this.buffer.length === 0 && - this[EOF]) { - this[EMITTING_END] = true - this.emit('end') - this.emit('prefinish') - this.emit('finish') - if (this[CLOSED]) - this.emit('close') - this[EMITTING_END] = false - } - } +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, +}) - emit (ev, data, ...extra) { - // error and close are only events allowed after calling destroy() - if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) - return - else if (ev === 'data') { - return !data ? false - : this[ASYNC] ? defer(() => this[EMITDATA](data)) - : this[EMITDATA](data) - } else if (ev === 'end') { - return this[EMITEND]() - } else if (ev === 'close') { - this[CLOSED] = true - // don't emit close before 'end' and 'finish' - if (!this[EMITTED_END] && !this[DESTROYED]) - return - const ret = super.emit('close') - this.removeAllListeners('close') - return ret - } else if (ev === 'error') { - this[EMITTED_ERROR] = data - const ret = super.emit('error', data) - this[MAYBE_EMIT_END]() - return ret - } else if (ev === 'resume') { - const ret = super.emit('resume') - this[MAYBE_EMIT_END]() - return ret - } else if (ev === 'finish' || ev === 'prefinish') { - const ret = super.emit(ev) - this.removeAllListeners(ev) - return ret - } +const isURLSearchParams = obj => + // Duck-typing as a necessary condition. + (typeof obj !== 'object' || + typeof obj.append !== 'function' || + typeof obj.delete !== 'function' || + typeof obj.get !== 'function' || + typeof obj.getAll !== 'function' || + typeof obj.has !== 'function' || + typeof obj.set !== 'function') ? false + // Brand-checking and more duck-typing as optional condition. + : obj.constructor.name === 'URLSearchParams' || + Object.prototype.toString.call(obj) === '[object URLSearchParams]' || + typeof obj.sort === 'function' - // Some other unknown event - const ret = super.emit(ev, data, ...extra) - this[MAYBE_EMIT_END]() - return ret +const isBlob = obj => + typeof obj === 'object' && + typeof obj.arrayBuffer === 'function' && + typeof obj.type === 'string' && + typeof obj.stream === 'function' && + typeof obj.constructor === 'function' && + typeof obj.constructor.name === 'string' && + /^(Blob|File)$/.test(obj.constructor.name) && + /^(Blob|File)$/.test(obj[Symbol.toStringTag]) + +const convertBody = (buffer, headers) => { + /* istanbul ignore if */ + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function') } - [EMITDATA] (data) { - for (const p of this.pipes) { - if (p.dest.write(data) === false) - this.pause() - } - const ret = super.emit('data', data) - this[MAYBE_EMIT_END]() - return ret + const ct = headers && headers.get('content-type') + let charset = 'utf-8' + let res + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct) } - [EMITEND] () { - if (this[EMITTED_END]) - return + // no charset in content type, peek at response body for at most 1024 bytes + const str = buffer.slice(0, 1024).toString() - this[EMITTED_END] = true - this.readable = false - if (this[ASYNC]) - defer(() => this[EMITEND2]()) - else - this[EMITEND2]() + // html5 + if (!res && str) { + res = / { - buf.push(c) - if (!this[OBJECTMODE]) - buf.dataLength += c.length - }) - return p.then(() => buf) + // xml + if (!res && str) { + res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str) } - // const data = await stream.concat() - concat () { - return this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this.collect().then(buf => - this[OBJECTMODE] - ? Promise.reject(new Error('cannot concat in objectMode')) - : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) - } + // found charset + if (res) { + charset = res.pop() - // stream.promise().then(() => done, er => emitted error) - promise () { - return new Promise((resolve, reject) => { - this.on(DESTROYED, () => reject(new Error('stream destroyed'))) - this.on('error', er => reject(er)) - this.on('end', () => resolve()) - }) + // prevent decode issues when sites use incorrect encoding + // ref: https://hsivonen.fi/encoding-menu/ + if (charset === 'gb2312' || charset === 'gbk') { + charset = 'gb18030' + } } - // for await (let chunk of stream) - [ASYNCITERATOR] () { - const next = () => { - const res = this.read() - if (res !== null) - return Promise.resolve({ done: false, value: res }) + // turn raw buffers into a single utf-8 buffer + return convert( + buffer, + 'UTF-8', + charset + ).toString() +} - if (this[EOF]) - return Promise.resolve({ done: true }) +module.exports = Body - let resolve = null - let reject = null - const onerr = er => { - this.removeListener('data', ondata) - this.removeListener('end', onend) - reject(er) - } - const ondata = value => { - this.removeListener('error', onerr) - this.removeListener('end', onend) - this.pause() - resolve({ value: value, done: !!this[EOF] }) - } - const onend = () => { - this.removeListener('error', onerr) - this.removeListener('data', ondata) - resolve({ done: true }) - } - const ondestroy = () => onerr(new Error('stream destroyed')) - return new Promise((res, rej) => { - reject = rej - resolve = res - this.once(DESTROYED, ondestroy) - this.once('error', onerr) - this.once('end', onend) - this.once('data', ondata) - }) - } - return { next } - } +/***/ }), - // for (let chunk of stream) - [ITERATOR] () { - const next = () => { - const value = this.read() - const done = value === null - return { value, done } - } - return { next } - } +/***/ 22644: +/***/ ((module) => { - destroy (er) { - if (this[DESTROYED]) { - if (er) - this.emit('error', er) - else - this.emit(DESTROYED) - return this - } +"use strict"; - this[DESTROYED] = true +class FetchError extends Error { + constructor (message, type, systemError) { + super(message) + this.code = 'FETCH_ERROR' - // throw away all buffered data, it's never coming out - this.buffer.length = 0 - this[BUFFERLENGTH] = 0 + // pick up code, expected, path, ... + if (systemError) { + Object.assign(this, systemError) + } - if (typeof this.close === 'function' && !this[CLOSED]) - this.close() + this.errno = this.code - if (er) - this.emit('error', er) - else // if no error to emit, still reject pending promises - this.emit(DESTROYED) + // override anything the system error might've clobbered + this.type = this.code === 'EBADSIZE' && this.found > this.expect + ? 'max-size' : type + this.message = message + Error.captureStackTrace(this, this.constructor) + } - return this + get name () { + return 'FetchError' } - static isStream (s) { - return !!s && (s instanceof Minipass || s instanceof Stream || - s instanceof EE && ( - typeof s.pipe === 'function' || // readable - (typeof s.write === 'function' && typeof s.end === 'function') // writable - )) + // don't allow name to be overwritten + set name (n) {} + + get [Symbol.toStringTag] () { + return 'FetchError' } } +module.exports = FetchError /***/ }), -/***/ 70744: +/***/ 98645: /***/ ((module) => { -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; +"use strict"; -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +const invalidTokenRegex = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/ +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); +const validateName = name => { + name = `${name}` + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`) } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +} -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; +const validateValue = value => { + value = `${value}` + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`) } } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; +const find = (map, name) => { + name = name.toLowerCase() + for (const key in map) { + if (key.toLowerCase() === name) { + return key + } } - return ms + 'ms'; + return undefined } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +const MAP = Symbol('map') +class Headers { + constructor (init = undefined) { + this[MAP] = Object.create(null) + if (init instanceof Headers) { + const rawHeaders = init.raw() + const headerNames = Object.keys(rawHeaders) + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value) + } + } + return + } -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); + // no-op + if (init === undefined || init === null) { + return + } + + if (typeof init === 'object') { + const method = init[Symbol.iterator] + if (method !== null && method !== undefined) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable') + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = [] + for (const pair of init) { + if (typeof pair !== 'object' || + typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable') + } + const arrPair = Array.from(pair) + if (arrPair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple') + } + pairs.push(arrPair) + } + + for (const pair of pairs) { + this.append(pair[0], pair[1]) + } + } else { + // record + for (const key of Object.keys(init)) { + this.append(key, init[key]) + } + } + } else { + throw new TypeError('Provided initializer must be an object') + } } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); + + get (name) { + name = `${name}` + validateName(name) + const key = find(this[MAP], name) + if (key === undefined) { + return null + } + + return this[MAP][key].join(', ') } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); + + forEach (callback, thisArg = undefined) { + let pairs = getHeaders(this) + for (let i = 0; i < pairs.length; i++) { + const [name, value] = pairs[i] + callback.call(thisArg, value, name, this) + // refresh in case the callback added more headers + pairs = getHeaders(this) + } } - return ms + ' ms'; -} -/** - * Pluralization helper. - */ + set (name, value) { + name = `${name}` + value = `${value}` + validateName(name) + validateValue(value) + const key = find(this[MAP], name) + this[MAP][key !== undefined ? key : name] = [value] + } -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} + append (name, value) { + name = `${name}` + value = `${value}` + validateName(name) + validateValue(value) + const key = find(this[MAP], name) + if (key !== undefined) { + this[MAP][key].push(value) + } else { + this[MAP][name] = [value] + } + } + has (name) { + name = `${name}` + validateName(name) + return find(this[MAP], name) !== undefined + } -/***/ }), + delete (name) { + name = `${name}` + validateName(name) + const key = find(this[MAP], name) + if (key !== undefined) { + delete this[MAP][key] + } + } -/***/ 60668: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + raw () { + return this[MAP] + } -"use strict"; -/*! - * negotiator - * Copyright(c) 2012 Federico Romero - * Copyright(c) 2012-2014 Isaac Z. Schlueter - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + keys () { + return new HeadersIterator(this, 'key') + } + values () { + return new HeadersIterator(this, 'value') + } + [Symbol.iterator] () { + return new HeadersIterator(this, 'key+value') + } -var preferredCharsets = __nccwpck_require__(79168) -var preferredEncodings = __nccwpck_require__(25111) -var preferredLanguages = __nccwpck_require__(56008) -var preferredMediaTypes = __nccwpck_require__(53672) + entries () { + return new HeadersIterator(this, 'key+value') + } -/** - * Module exports. - * @public - */ + get [Symbol.toStringTag] () { + return 'Headers' + } -module.exports = Negotiator; -module.exports.Negotiator = Negotiator; + static exportNodeCompatibleHeaders (headers) { + const obj = Object.assign(Object.create(null), headers[MAP]) -/** - * Create a Negotiator instance from a request. - * @param {object} request - * @public - */ + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host') + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0] + } -function Negotiator(request) { - if (!(this instanceof Negotiator)) { - return new Negotiator(request); + return obj } - this.request = request; -} - -Negotiator.prototype.charset = function charset(available) { - var set = this.charsets(available); - return set && set[0]; -}; + static createHeadersLenient (obj) { + const headers = new Headers() + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue + } -Negotiator.prototype.charsets = function charsets(available) { - return preferredCharsets(this.request.headers['accept-charset'], available); -}; + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue + } -Negotiator.prototype.encoding = function encoding(available, opts) { - var set = this.encodings(available, opts); - return set && set[0]; -}; + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val] + } else { + headers[MAP][name].push(val) + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]] + } + } + return headers + } +} -Negotiator.prototype.encodings = function encodings(available, options) { - var opts = options || {}; - return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); -}; +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true }, +}) -Negotiator.prototype.language = function language(available) { - var set = this.languages(available); - return set && set[0]; -}; +const getHeaders = (headers, kind = 'key+value') => + Object.keys(headers[MAP]).sort().map( + kind === 'key' ? k => k.toLowerCase() + : kind === 'value' ? k => headers[MAP][k].join(', ') + : k => [k.toLowerCase(), headers[MAP][k].join(', ')] + ) -Negotiator.prototype.languages = function languages(available) { - return preferredLanguages(this.request.headers['accept-language'], available); -}; +const INTERNAL = Symbol('internal') -Negotiator.prototype.mediaType = function mediaType(available) { - var set = this.mediaTypes(available); - return set && set[0]; -}; +class HeadersIterator { + constructor (target, kind) { + this[INTERNAL] = { + target, + kind, + index: 0, + } + } -Negotiator.prototype.mediaTypes = function mediaTypes(available) { - return preferredMediaTypes(this.request.headers.accept, available); -}; + get [Symbol.toStringTag] () { + return 'HeadersIterator' + } -// Backwards compatibility -Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; -Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; -Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; -Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; -Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; -Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; -Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; -Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; + next () { + /* istanbul ignore if: should be impossible */ + if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) { + throw new TypeError('Value of `this` is not a HeadersIterator') + } + const { target, kind, index } = this[INTERNAL] + const values = getHeaders(target, kind) + const len = values.length + if (index >= len) { + return { + value: undefined, + done: true, + } + } -/***/ }), + this[INTERNAL].index++ -/***/ 79168: -/***/ ((module) => { + return { value: values[index], done: false } + } +} -"use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +// manually extend because 'extends' requires a ctor +Object.setPrototypeOf(HeadersIterator.prototype, + Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))) +module.exports = Headers -/** - * Module exports. - * @public - */ +/***/ }), -module.exports = preferredCharsets; -module.exports.preferredCharsets = preferredCharsets; +/***/ 88483: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Module variables. - * @private - */ +"use strict"; -var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; +const { URL } = __nccwpck_require__(87016) +const http = __nccwpck_require__(58611) +const https = __nccwpck_require__(65692) +const zlib = __nccwpck_require__(37119) +const { Minipass } = __nccwpck_require__(78275) -/** - * Parse the Accept-Charset header. - * @private - */ +const Body = __nccwpck_require__(28515) +const { writeToStream, getTotalBytes } = Body +const Response = __nccwpck_require__(43852) +const Headers = __nccwpck_require__(98645) +const { createHeadersLenient } = Headers +const Request = __nccwpck_require__(99586) +const { getNodeRequestOptions } = Request +const FetchError = __nccwpck_require__(22644) +const AbortError = __nccwpck_require__(57442) -function parseAcceptCharset(accept) { - var accepts = accept.split(','); +// XXX this should really be split up and unit-ized for easier testing +// and better DRY implementation of data/http request aborting +const fetch = async (url, opts) => { + if (/^data:/.test(url)) { + const request = new Request(url, opts) + // delay 1 promise tick so that the consumer can abort right away + return Promise.resolve().then(() => new Promise((resolve, reject) => { + let type, data + try { + const { pathname, search } = new URL(url) + const split = pathname.split(',') + if (split.length < 2) { + throw new Error('invalid data: URI') + } + const mime = split.shift() + const base64 = /;base64$/.test(mime) + type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime + const rawData = decodeURIComponent(split.join(',') + search) + data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData) + } catch (er) { + return reject(new FetchError(`[${request.method}] ${ + request.url} invalid URL, ${er.message}`, 'system', er)) + } - for (var i = 0, j = 0; i < accepts.length; i++) { - var charset = parseCharset(accepts[i].trim(), i); + const { signal } = request + if (signal && signal.aborted) { + return reject(new AbortError('The user aborted a request.')) + } - if (charset) { - accepts[j++] = charset; - } + const headers = { 'Content-Length': data.length } + if (type) { + headers['Content-Type'] = type + } + return resolve(new Response(data, { headers })) + })) } - // trim accepts - accepts.length = j; + return new Promise((resolve, reject) => { + // build request object + const request = new Request(url, opts) + let options + try { + options = getNodeRequestOptions(request) + } catch (er) { + return reject(er) + } - return accepts; -} + const send = (options.protocol === 'https:' ? https : http).request + const { signal } = request + let response = null + const abort = () => { + const error = new AbortError('The user aborted a request.') + reject(error) + if (Minipass.isStream(request.body) && + typeof request.body.destroy === 'function') { + request.body.destroy(error) + } + if (response && response.body) { + response.body.emit('error', error) + } + } -/** - * Parse a charset from the Accept-Charset header. - * @private - */ + if (signal && signal.aborted) { + return abort() + } -function parseCharset(str, i) { - var match = simpleCharsetRegExp.exec(str); - if (!match) return null; + const abortAndFinalize = () => { + abort() + finalize() + } - var charset = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';') - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; + const finalize = () => { + req.abort() + if (signal) { + signal.removeEventListener('abort', abortAndFinalize) } + clearTimeout(reqTimeout) } - } - - return { - charset: charset, - q: q, - i: i - }; -} - -/** - * Get the priority of a charset. - * @private - */ -function getCharsetPriority(charset, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; + // send request + const req = send(options) - for (var i = 0; i < accepted.length; i++) { - var spec = specify(charset, accepted[i], index); + if (signal) { + signal.addEventListener('abort', abortAndFinalize) + } - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; + let reqTimeout = null + if (request.timeout) { + req.once('socket', () => { + reqTimeout = setTimeout(() => { + reject(new FetchError(`network timeout at: ${ + request.url}`, 'request-timeout')) + finalize() + }, request.timeout) + }) } - } - return priority; -} + req.on('error', er => { + // if a 'response' event is emitted before the 'error' event, then by the + // time this handler is run it's too late to reject the Promise for the + // response. instead, we forward the error event to the response stream + // so that the error will surface to the user when they try to consume + // the body. this is done as a side effect of aborting the request except + // for in windows, where we must forward the event manually, otherwise + // there is no longer a ref'd socket attached to the request and the + // stream never ends so the event loop runs out of work and the process + // exits without warning. + // coverage skipped here due to the difficulty in testing + // istanbul ignore next + if (req.res) { + req.res.emit('error', er) + } + reject(new FetchError(`request to ${request.url} failed, reason: ${ + er.message}`, 'system', er)) + finalize() + }) -/** - * Get the specificity of the charset. - * @private - */ + req.on('response', res => { + clearTimeout(reqTimeout) -function specify(charset, spec, index) { - var s = 0; - if(spec.charset.toLowerCase() === charset.toLowerCase()){ - s |= 1; - } else if (spec.charset !== '*' ) { - return null - } + const headers = createHeadersLenient(res.headers) - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -} + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location') -/** - * Get the preferred charsets from an Accept-Charset header. - * @public - */ + // HTTP fetch step 5.3 + let locationURL = null + try { + locationURL = location === null ? null : new URL(location, request.url).toString() + } catch { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + /* eslint-disable-next-line max-len */ + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')) + finalize() + return + } + } -function preferredCharsets(accept, provided) { - // RFC 2616 sec 14.2: no header = * - var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + // HTTP fetch step 5.5 + if (request.redirect === 'error') { + reject(new FetchError('uri requested responds with a redirect, ' + + `redirect mode is set to error: ${request.url}`, 'no-redirect')) + finalize() + return + } else if (request.redirect === 'manual') { + // node-fetch-specific step: make manual redirect a bit easier to + // use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL) + } catch (err) { + /* istanbul ignore next: nodejs server prevent invalid + response headers, we can't test this through normal + request */ + reject(err) + } + } + } else if (request.redirect === 'follow' && locationURL !== null) { + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${ + request.url}`, 'max-redirect')) + finalize() + return + } - if (!provided) { - // sorted list of all charsets - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullCharset); - } + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && + request.body && + getTotalBytes(request) === null) { + reject(new FetchError( + 'Cannot follow redirect with body being a readable stream', + 'unsupported-redirect' + )) + finalize() + return + } - var priorities = provided.map(function getPriority(type, index) { - return getCharsetPriority(type, accepts, index); - }); + // Update host due to redirection + request.headers.set('host', (new URL(locationURL)).host) - // sorted list of accepted charsets - return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { - return provided[priorities.indexOf(priority)]; - }); -} + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + } -/** - * Compare two specs. - * @private - */ + // if the redirect is to a new hostname, strip the authorization and cookie headers + const parsedOriginal = new URL(request.url) + const parsedRedirect = new URL(locationURL) + if (parsedOriginal.hostname !== parsedRedirect.hostname) { + requestOpts.headers.delete('authorization') + requestOpts.headers.delete('cookie') + } -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || ( + (res.statusCode === 301 || res.statusCode === 302) && + request.method === 'POST' + )) { + requestOpts.method = 'GET' + requestOpts.body = undefined + requestOpts.headers.delete('content-length') + } -/** - * Get full charset string. - * @private - */ + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))) + finalize() + return + } + } // end if(isRedirect) -function getFullCharset(spec) { - return spec.charset; -} + // prepare response + res.once('end', () => + signal && signal.removeEventListener('abort', abortAndFinalize)) -/** - * Check if a spec has any quality. - * @private - */ + const body = new Minipass() + // if an error occurs, either on the response stream itself, on one of the + // decoder streams, or a response length timeout from the Body class, we + // forward the error through to our internal body stream. If we see an + // error event on that, we call finalize to abort the request and ensure + // we don't leave a socket believing a request is in flight. + // this is difficult to test, so lacks specific coverage. + body.on('error', finalize) + // exceedingly rare that the stream would have an error, + // but just in case we proxy it to the stream in use. + res.on('error', /* istanbul ignore next */ er => body.emit('error', er)) + res.on('data', (chunk) => body.write(chunk)) + res.on('end', () => body.end()) -function isQuality(spec) { - return spec.q > 0; -} + const responseOptions = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter, + trailer: new Promise(resolveTrailer => + res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))), + } + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding') -/***/ }), + // HTTP-network fetch step 12.1.1.4: handle content codings -/***/ 25111: -/***/ ((module) => { + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || + request.method === 'HEAD' || + codings === null || + res.statusCode === 204 || + res.statusCode === 304) { + response = new Response(body, responseOptions) + resolve(response) + return + } -"use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH, + } + // for gzip + if (codings === 'gzip' || codings === 'x-gzip') { + const unzip = new zlib.Gunzip(zlibOptions) + response = new Response( + // exceedingly rare that the stream would have an error, + // but just in case we proxy it to the stream in use. + body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip), + responseOptions + ) + resolve(response) + return + } + // for deflate + if (codings === 'deflate' || codings === 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new Minipass()) + raw.once('data', chunk => { + // see http://stackoverflow.com/questions/37519828 + const decoder = (chunk[0] & 0x0F) === 0x08 + ? new zlib.Inflate() + : new zlib.InflateRaw() + // exceedingly rare that the stream would have an error, + // but just in case we proxy it to the stream in use. + body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) + response = new Response(decoder, responseOptions) + resolve(response) + }) + return + } -/** - * Module exports. - * @public - */ + // for br + if (codings === 'br') { + // ignoring coverage so tests don't have to fake support (or lack of) for brotli + // istanbul ignore next + try { + var decoder = new zlib.BrotliDecompress() + } catch (err) { + reject(err) + finalize() + return + } + // exceedingly rare that the stream would have an error, + // but just in case we proxy it to the stream in use. + body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder) + response = new Response(decoder, responseOptions) + resolve(response) + return + } -module.exports = preferredEncodings; -module.exports.preferredEncodings = preferredEncodings; + // otherwise, use response as-is + response = new Response(body, responseOptions) + resolve(response) + }) -/** - * Module variables. - * @private - */ + writeToStream(req, request) + }) +} -var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; +module.exports = fetch -/** - * Parse the Accept-Encoding header. - * @private - */ +fetch.isRedirect = code => + code === 301 || + code === 302 || + code === 303 || + code === 307 || + code === 308 -function parseAcceptEncoding(accept) { - var accepts = accept.split(','); - var hasIdentity = false; - var minQuality = 1; +fetch.Headers = Headers +fetch.Request = Request +fetch.Response = Response +fetch.FetchError = FetchError +fetch.AbortError = AbortError - for (var i = 0, j = 0; i < accepts.length; i++) { - var encoding = parseEncoding(accepts[i].trim(), i); - if (encoding) { - accepts[j++] = encoding; - hasIdentity = hasIdentity || specify('identity', encoding); - minQuality = Math.min(minQuality, encoding.q || 1); - } - } +/***/ }), - if (!hasIdentity) { - /* - * If identity doesn't explicitly appear in the accept-encoding header, - * it's added to the list of acceptable encoding with the lowest q - */ - accepts[j++] = { - encoding: 'identity', - q: minQuality, - i: i - }; - } +/***/ 99586: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // trim accepts - accepts.length = j; +"use strict"; - return accepts; -} +const { URL } = __nccwpck_require__(87016) +const { Minipass } = __nccwpck_require__(78275) +const Headers = __nccwpck_require__(98645) +const { exportNodeCompatibleHeaders } = Headers +const Body = __nccwpck_require__(28515) +const { clone, extractContentType, getTotalBytes } = Body -/** - * Parse an encoding from the Accept-Encoding header. - * @private - */ +const version = (__nccwpck_require__(27573)/* .version */ .rE) +const defaultUserAgent = + `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)` -function parseEncoding(str, i) { - var match = simpleEncodingRegExp.exec(str); - if (!match) return null; +const INTERNALS = Symbol('Request internals') - var encoding = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';'); - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } +const isRequest = input => + typeof input === 'object' && typeof input[INTERNALS] === 'object' - return { - encoding: encoding, - q: q, - i: i - }; +const isAbortSignal = signal => { + const proto = ( + signal + && typeof signal === 'object' + && Object.getPrototypeOf(signal) + ) + return !!(proto && proto.constructor.name === 'AbortSignal') } -/** - * Get the priority of an encoding. - * @private - */ - -function getEncodingPriority(encoding, accepted, index) { - var priority = {encoding: encoding, o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(encoding, accepted[i], index); +class Request extends Body { + constructor (input, init = {}) { + const parsedURL = isRequest(input) ? new URL(input.url) + : input && input.href ? new URL(input.href) + : new URL(`${input}`) - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; + if (isRequest(input)) { + init = { ...input[INTERNALS], ...init } + } else if (!input || typeof input === 'string') { + input = {} } - } - return priority; -} - -/** - * Get the specificity of the encoding. - * @private - */ + const method = (init.method || input.method || 'GET').toUpperCase() + const isGETHEAD = method === 'GET' || method === 'HEAD' -function specify(encoding, spec, index) { - var s = 0; - if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ - s |= 1; - } else if (spec.encoding !== '*' ) { - return null - } + if ((init.body !== null && init.body !== undefined || + isRequest(input) && input.body !== null) && isGETHEAD) { + throw new TypeError('Request with GET/HEAD method cannot have body') + } - return { - encoding: encoding, - i: index, - o: spec.i, - q: spec.q, - s: s - } -}; + const inputBody = init.body !== null && init.body !== undefined ? init.body + : isRequest(input) && input.body !== null ? clone(input) + : null -/** - * Get the preferred encodings from an Accept-Encoding header. - * @public - */ + super(inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0, + }) -function preferredEncodings(accept, provided, preferred) { - var accepts = parseAcceptEncoding(accept || ''); + const headers = new Headers(init.headers || input.headers || {}) - var comparator = preferred ? function comparator (a, b) { - if (a.q !== b.q) { - return b.q - a.q // higher quality first + if (inputBody !== null && inputBody !== undefined && + !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody) + if (contentType) { + headers.append('Content-Type', contentType) + } } - var aPreferred = preferred.indexOf(a.encoding) - var bPreferred = preferred.indexOf(b.encoding) + const signal = 'signal' in init ? init.signal + : null - if (aPreferred === -1 && bPreferred === -1) { - // consider the original specifity/order - return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) + if (signal !== null && signal !== undefined && !isAbortSignal(signal)) { + throw new TypeError('Expected signal must be an instanceof AbortSignal') } - if (aPreferred !== -1 && bPreferred !== -1) { - return aPreferred - bPreferred // consider the preferred order - } + // TLS specific options that are handled by node + const { + ca, + cert, + ciphers, + clientCertEngine, + crl, + dhparam, + ecdhCurve, + family, + honorCipherOrder, + key, + passphrase, + pfx, + rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0', + secureOptions, + secureProtocol, + servername, + sessionIdContext, + } = init - return aPreferred === -1 ? 1 : -1 // preferred first - } : compareSpecs; + this[INTERNALS] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal, + ca, + cert, + ciphers, + clientCertEngine, + crl, + dhparam, + ecdhCurve, + family, + honorCipherOrder, + key, + passphrase, + pfx, + rejectUnauthorized, + secureOptions, + secureProtocol, + servername, + sessionIdContext, + } - if (!provided) { - // sorted list of all encodings - return accepts - .filter(isQuality) - .sort(comparator) - .map(getFullEncoding); + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow + : input.follow !== undefined ? input.follow + : 20 + this.compress = init.compress !== undefined ? init.compress + : input.compress !== undefined ? input.compress + : true + this.counter = init.counter || input.counter || 0 + this.agent = init.agent || input.agent } - var priorities = provided.map(function getPriority(type, index) { - return getEncodingPriority(type, accepts, index); - }); - - // sorted list of accepted encodings - return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { - return provided[priorities.indexOf(priority)]; - }); -} + get method () { + return this[INTERNALS].method + } -/** - * Compare two specs. - * @private - */ + get url () { + return this[INTERNALS].parsedURL.toString() + } -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); -} + get headers () { + return this[INTERNALS].headers + } -/** - * Get full encoding string. - * @private - */ + get redirect () { + return this[INTERNALS].redirect + } -function getFullEncoding(spec) { - return spec.encoding; -} + get signal () { + return this[INTERNALS].signal + } -/** - * Check if a spec has any quality. - * @private - */ + clone () { + return new Request(this) + } -function isQuality(spec) { - return spec.q > 0; -} + get [Symbol.toStringTag] () { + return 'Request' + } + static getNodeRequestOptions (request) { + const parsedURL = request[INTERNALS].parsedURL + const headers = new Headers(request[INTERNALS].headers) -/***/ }), + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*') + } -/***/ 56008: -/***/ ((module) => { + // Basic fetch + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported') + } -"use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + if (request.signal && + Minipass.isStream(request.body) && + typeof request.body.destroy !== 'function') { + throw new Error( + 'Cancellation of streamed requests with AbortSignal is not supported') + } + // HTTP-network-or-cache fetch steps 2.4-2.7 + const contentLengthValue = + (request.body === null || request.body === undefined) && + /^(POST|PUT)$/i.test(request.method) ? '0' + : request.body !== null && request.body !== undefined + ? getTotalBytes(request) + : null + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue + '') + } -/** - * Module exports. - * @public - */ + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', defaultUserAgent) + } -module.exports = preferredLanguages; -module.exports.preferredLanguages = preferredLanguages; + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate') + } -/** - * Module variables. - * @private - */ + const agent = typeof request.agent === 'function' + ? request.agent(parsedURL) + : request.agent -var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close') + } -/** - * Parse the Accept-Language header. - * @private - */ + // TLS specific options that are handled by node + const { + ca, + cert, + ciphers, + clientCertEngine, + crl, + dhparam, + ecdhCurve, + family, + honorCipherOrder, + key, + passphrase, + pfx, + rejectUnauthorized, + secureOptions, + secureProtocol, + servername, + sessionIdContext, + } = request[INTERNALS] -function parseAcceptLanguage(accept) { - var accepts = accept.split(','); + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js - for (var i = 0, j = 0; i < accepts.length; i++) { - var language = parseLanguage(accepts[i].trim(), i); + // we cannot spread parsedURL directly, so we have to read each property one-by-one + // and map them to the equivalent https?.request() method options + const urlProps = { + auth: parsedURL.username || parsedURL.password + ? `${parsedURL.username}:${parsedURL.password}` + : '', + host: parsedURL.host, + hostname: parsedURL.hostname, + path: `${parsedURL.pathname}${parsedURL.search}`, + port: parsedURL.port, + protocol: parsedURL.protocol, + } - if (language) { - accepts[j++] = language; + return { + ...urlProps, + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent, + ca, + cert, + ciphers, + clientCertEngine, + crl, + dhparam, + ecdhCurve, + family, + honorCipherOrder, + key, + passphrase, + pfx, + rejectUnauthorized, + secureOptions, + secureProtocol, + servername, + sessionIdContext, + timeout: request.timeout, } } +} - // trim accepts - accepts.length = j; +module.exports = Request - return accepts; -} +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, +}) -/** - * Parse a language from the Accept-Language header. - * @private - */ -function parseLanguage(str, i) { - var match = simpleLanguageRegExp.exec(str); - if (!match) return null; +/***/ }), - var prefix = match[1] - var suffix = match[2] - var full = prefix +/***/ 43852: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (suffix) full += "-" + suffix; +"use strict"; - var q = 1; - if (match[3]) { - var params = match[3].split(';') - for (var j = 0; j < params.length; j++) { - var p = params[j].split('='); - if (p[0] === 'q') q = parseFloat(p[1]); - } - } +const http = __nccwpck_require__(58611) +const { STATUS_CODES } = http - return { - prefix: prefix, - suffix: suffix, - q: q, - i: i, - full: full - }; -} +const Headers = __nccwpck_require__(98645) +const Body = __nccwpck_require__(28515) +const { clone, extractContentType } = Body -/** - * Get the priority of a language. - * @private - */ +const INTERNALS = Symbol('Response internals') -function getLanguagePriority(language, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; +class Response extends Body { + constructor (body = null, opts = {}) { + super(body, opts) - for (var i = 0; i < accepted.length; i++) { - var spec = specify(language, accepted[i], index); + const status = opts.status || 200 + const headers = new Headers(opts.headers) - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; + if (body !== null && body !== undefined && !headers.has('Content-Type')) { + const contentType = extractContentType(body) + if (contentType) { + headers.append('Content-Type', contentType) + } } - } - - return priority; -} -/** - * Get the specificity of the language. - * @private - */ + this[INTERNALS] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter, + trailer: Promise.resolve(opts.trailer || new Headers()), + } + } -function specify(language, spec, index) { - var p = parseLanguage(language) - if (!p) return null; - var s = 0; - if(spec.full.toLowerCase() === p.full.toLowerCase()){ - s |= 4; - } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { - s |= 2; - } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { - s |= 1; - } else if (spec.full !== '*' ) { - return null + get trailer () { + return this[INTERNALS].trailer } - return { - i: index, - o: spec.i, - q: spec.q, - s: s + get url () { + return this[INTERNALS].url || '' } -}; -/** - * Get the preferred languages from an Accept-Language header. - * @public - */ + get status () { + return this[INTERNALS].status + } -function preferredLanguages(accept, provided) { - // RFC 2616 sec 14.4: no header = * - var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + get ok () { + return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300 + } - if (!provided) { - // sorted list of all languages - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullLanguage); + get redirected () { + return this[INTERNALS].counter > 0 } - var priorities = provided.map(function getPriority(type, index) { - return getLanguagePriority(type, accepts, index); - }); + get statusText () { + return this[INTERNALS].statusText + } - // sorted list of accepted languages - return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { - return provided[priorities.indexOf(priority)]; - }); -} + get headers () { + return this[INTERNALS].headers + } -/** - * Compare two specs. - * @private - */ + clone () { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + trailer: this.trailer, + }) + } -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; + get [Symbol.toStringTag] () { + return 'Response' + } } -/** - * Get full language string. - * @private - */ +module.exports = Response -function getFullLanguage(spec) { - return spec.full; -} +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true }, +}) -/** - * Check if a spec has any quality. - * @private - */ -function isQuality(spec) { - return spec.q > 0; -} +/***/ }), +/***/ 37633: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), +const Minipass = __nccwpck_require__(64387) +const _flush = Symbol('_flush') +const _flushed = Symbol('_flushed') +const _flushing = Symbol('_flushing') +class Flush extends Minipass { + constructor (opt = {}) { + if (typeof opt === 'function') + opt = { flush: opt } -/***/ 53672: -/***/ ((module) => { + super(opt) -"use strict"; -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // or extend this class and provide a 'flush' method in your subclass + if (typeof opt.flush !== 'function' && typeof this.flush !== 'function') + throw new TypeError('must provide flush function in options') + this[_flush] = opt.flush || this.flush + } + emit (ev, ...data) { + if ((ev !== 'end' && ev !== 'finish') || this[_flushed]) + return super.emit(ev, ...data) -/** - * Module exports. - * @public - */ + if (this[_flushing]) + return -module.exports = preferredMediaTypes; -module.exports.preferredMediaTypes = preferredMediaTypes; + this[_flushing] = true -/** - * Module variables. - * @private - */ + const afterFlush = er => { + this[_flushed] = true + er ? super.emit('error', er) : super.emit('end') + } -var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + const ret = this[_flush](afterFlush) + if (ret && ret.then) + ret.then(() => afterFlush(), er => afterFlush(er)) + } +} -/** - * Parse the Accept header. - * @private - */ +module.exports = Flush -function parseAccept(accept) { - var accepts = splitMediaTypes(accept); - for (var i = 0, j = 0; i < accepts.length; i++) { - var mediaType = parseMediaType(accepts[i].trim(), i); +/***/ }), - if (mediaType) { - accepts[j++] = mediaType; - } - } +/***/ 64387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // trim accepts - accepts.length = j; +"use strict"; - return accepts; +const proc = typeof process === 'object' && process ? process : { + stdout: null, + stderr: null, } +const EE = __nccwpck_require__(24434) +const Stream = __nccwpck_require__(2203) +const SD = (__nccwpck_require__(13193).StringDecoder) -/** - * Parse a media type from the Accept header. - * @private - */ - -function parseMediaType(str, i) { - var match = simpleMediaTypeRegExp.exec(str); - if (!match) return null; +const EOF = Symbol('EOF') +const MAYBE_EMIT_END = Symbol('maybeEmitEnd') +const EMITTED_END = Symbol('emittedEnd') +const EMITTING_END = Symbol('emittingEnd') +const EMITTED_ERROR = Symbol('emittedError') +const CLOSED = Symbol('closed') +const READ = Symbol('read') +const FLUSH = Symbol('flush') +const FLUSHCHUNK = Symbol('flushChunk') +const ENCODING = Symbol('encoding') +const DECODER = Symbol('decoder') +const FLOWING = Symbol('flowing') +const PAUSED = Symbol('paused') +const RESUME = Symbol('resume') +const BUFFERLENGTH = Symbol('bufferLength') +const BUFFERPUSH = Symbol('bufferPush') +const BUFFERSHIFT = Symbol('bufferShift') +const OBJECTMODE = Symbol('objectMode') +const DESTROYED = Symbol('destroyed') +const EMITDATA = Symbol('emitData') +const EMITEND = Symbol('emitEnd') +const EMITEND2 = Symbol('emitEnd2') +const ASYNC = Symbol('async') - var params = Object.create(null); - var q = 1; - var subtype = match[2]; - var type = match[1]; +const defer = fn => Promise.resolve().then(fn) - if (match[3]) { - var kvps = splitParameters(match[3]).map(splitKeyValuePair); +// TODO remove when Node v8 support drops +const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' +const ASYNCITERATOR = doIter && Symbol.asyncIterator + || Symbol('asyncIterator not implemented') +const ITERATOR = doIter && Symbol.iterator + || Symbol('iterator not implemented') - for (var j = 0; j < kvps.length; j++) { - var pair = kvps[j]; - var key = pair[0].toLowerCase(); - var val = pair[1]; +// events that mean 'the stream is over' +// these are treated specially, and re-emitted +// if they are listened for after emitting. +const isEndish = ev => + ev === 'end' || + ev === 'finish' || + ev === 'prefinish' - // get the value, unwrapping quotes - var value = val && val[0] === '"' && val[val.length - 1] === '"' - ? val.slice(1, -1) - : val; +const isArrayBuffer = b => b instanceof ArrayBuffer || + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0 - if (key === 'q') { - q = parseFloat(value); - break; - } +const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) - // store parameter - params[key] = value; - } +class Pipe { + constructor (src, dest, opts) { + this.src = src + this.dest = dest + this.opts = opts + this.ondrain = () => src[RESUME]() + dest.on('drain', this.ondrain) + } + unpipe () { + this.dest.removeListener('drain', this.ondrain) + } + // istanbul ignore next - only here for the prototype + proxyErrors () {} + end () { + this.unpipe() + if (this.opts.end) + this.dest.end() } - - return { - type: type, - subtype: subtype, - params: params, - q: q, - i: i - }; } -/** - * Get the priority of a media type. - * @private - */ - -function getMediaTypePriority(type, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(type, accepted[i], index); +class PipeProxyErrors extends Pipe { + unpipe () { + this.src.removeListener('error', this.proxyErrors) + super.unpipe() + } + constructor (src, dest, opts) { + super(src, dest, opts) + this.proxyErrors = er => dest.emit('error', er) + src.on('error', this.proxyErrors) + } +} - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } +module.exports = class Minipass extends Stream { + constructor (options) { + super() + this[FLOWING] = false + // whether we're explicitly paused + this[PAUSED] = false + this.pipes = [] + this.buffer = [] + this[OBJECTMODE] = options && options.objectMode || false + if (this[OBJECTMODE]) + this[ENCODING] = null + else + this[ENCODING] = options && options.encoding || null + if (this[ENCODING] === 'buffer') + this[ENCODING] = null + this[ASYNC] = options && !!options.async || false + this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null + this[EOF] = false + this[EMITTED_END] = false + this[EMITTING_END] = false + this[CLOSED] = false + this[EMITTED_ERROR] = null + this.writable = true + this.readable = true + this[BUFFERLENGTH] = 0 + this[DESTROYED] = false } - return priority; -} - -/** - * Get the specificity of the media type. - * @private - */ - -function specify(type, spec, index) { - var p = parseMediaType(type); - var s = 0; - - if (!p) { - return null; - } + get bufferLength () { return this[BUFFERLENGTH] } - if(spec.type.toLowerCase() == p.type.toLowerCase()) { - s |= 4 - } else if(spec.type != '*') { - return null; - } + get encoding () { return this[ENCODING] } + set encoding (enc) { + if (this[OBJECTMODE]) + throw new Error('cannot set encoding in objectMode') - if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { - s |= 2 - } else if(spec.subtype != '*') { - return null; - } + if (this[ENCODING] && enc !== this[ENCODING] && + (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) + throw new Error('cannot change encoding') - var keys = Object.keys(spec.params); - if (keys.length > 0) { - if (keys.every(function (k) { - return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); - })) { - s |= 1 - } else { - return null + if (this[ENCODING] !== enc) { + this[DECODER] = enc ? new SD(enc) : null + if (this.buffer.length) + this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } - } - return { - i: index, - o: spec.i, - q: spec.q, - s: s, + this[ENCODING] = enc } -} -/** - * Get the preferred media types from an Accept header. - * @public - */ + setEncoding (enc) { + this.encoding = enc + } -function preferredMediaTypes(accept, provided) { - // RFC 2616 sec 14.2: no header = */* - var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + get objectMode () { return this[OBJECTMODE] } + set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } - if (!provided) { - // sorted list of all types - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullType); - } + get ['async'] () { return this[ASYNC] } + set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } - var priorities = provided.map(function getPriority(type, index) { - return getMediaTypePriority(type, accepts, index); - }); + write (chunk, encoding, cb) { + if (this[EOF]) + throw new Error('write after end') - // sorted list of accepted types - return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { - return provided[priorities.indexOf(priority)]; - }); -} + if (this[DESTROYED]) { + this.emit('error', Object.assign( + new Error('Cannot call write after a stream was destroyed'), + { code: 'ERR_STREAM_DESTROYED' } + )) + return true + } -/** - * Compare two specs. - * @private - */ + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} + if (!encoding) + encoding = 'utf8' -/** - * Get full type string. - * @private - */ + const fn = this[ASYNC] ? defer : f => f() -function getFullType(spec) { - return spec.type + '/' + spec.subtype; -} + // convert array buffers and typed array views into buffers + // at some point in the future, we may want to do the opposite! + // leave strings and buffers as-is + // anything else switches us into object mode + if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { + if (isArrayBufferView(chunk)) + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + else if (isArrayBuffer(chunk)) + chunk = Buffer.from(chunk) + else if (typeof chunk !== 'string') + // use the setter so we throw if we have encoding set + this.objectMode = true + } -/** - * Check if a spec has any quality. - * @private - */ + // handle object mode up front, since it's simpler + // this yields better performance, fewer checks later. + if (this[OBJECTMODE]) { + /* istanbul ignore if - maybe impossible? */ + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) -function isQuality(spec) { - return spec.q > 0; -} + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) -/** - * Count the number of quotes in a string. - * @private - */ + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') -function quoteCount(string) { - var count = 0; - var index = 0; + if (cb) + fn(cb) - while ((index = string.indexOf('"', index)) !== -1) { - count++; - index++; - } + return this.flowing + } - return count; -} + // at this point the chunk is a buffer or string + // don't buffer it up or send it to the decoder + if (!chunk.length) { + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + if (cb) + fn(cb) + return this.flowing + } -/** - * Split a key value pair. - * @private - */ + // fast-path writing strings of same encoding to a stream with + // an empty buffer, skipping the buffer/decoder dance + if (typeof chunk === 'string' && + // unless it is a string already ready for us to use + !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { + chunk = Buffer.from(chunk, encoding) + } -function splitKeyValuePair(str) { - var index = str.indexOf('='); - var key; - var val; + if (Buffer.isBuffer(chunk) && this[ENCODING]) + chunk = this[DECODER].write(chunk) - if (index === -1) { - key = str; - } else { - key = str.slice(0, index); - val = str.slice(index + 1); - } + // Note: flushing CAN potentially switch us into not-flowing mode + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) - return [key, val]; -} + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) -/** - * Split an Accept header into media types. - * @private - */ + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') -function splitMediaTypes(accept) { - var accepts = accept.split(','); + if (cb) + fn(cb) - for (var i = 1, j = 0; i < accepts.length; i++) { - if (quoteCount(accepts[j]) % 2 == 0) { - accepts[++j] = accepts[i]; - } else { - accepts[j] += ',' + accepts[i]; - } + return this.flowing } - // trim accepts - accepts.length = j + 1; - - return accepts; -} + read (n) { + if (this[DESTROYED]) + return null -/** - * Split a string of parameters. - * @private - */ + if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { + this[MAYBE_EMIT_END]() + return null + } -function splitParameters(str) { - var parameters = str.split(';'); + if (this[OBJECTMODE]) + n = null - for (var i = 1, j = 0; i < parameters.length; i++) { - if (quoteCount(parameters[j]) % 2 == 0) { - parameters[++j] = parameters[i]; - } else { - parameters[j] += ';' + parameters[i]; + if (this.buffer.length > 1 && !this[OBJECTMODE]) { + if (this.encoding) + this.buffer = [this.buffer.join('')] + else + this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } - } - - // trim parameters - parameters.length = j + 1; - for (var i = 0; i < parameters.length; i++) { - parameters[i] = parameters[i].trim(); + const ret = this[READ](n || null, this.buffer[0]) + this[MAYBE_EMIT_END]() + return ret } - return parameters; -} + [READ] (n, chunk) { + if (n === chunk.length || n === null) + this[BUFFERSHIFT]() + else { + this.buffer[0] = chunk.slice(n) + chunk = chunk.slice(0, n) + this[BUFFERLENGTH] -= n + } + this.emit('data', chunk) -/***/ }), + if (!this.buffer.length && !this[EOF]) + this.emit('drain') -/***/ 55560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return chunk + } -var wrappy = __nccwpck_require__(58264) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + if (cb) + this.once('end', cb) + this[EOF] = true + this.writable = false -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) + // if we haven't written anything, then go ahead and emit, + // even if we're not reading. + // we'll re-emit if a new 'end' listener is added anyway. + // This makes MP more suitable to write-only use cases. + if (this.flowing || !this[PAUSED]) + this[MAYBE_EMIT_END]() + return this + } - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) + // don't let the internal resume be overwritten + [RESUME] () { + if (this[DESTROYED]) + return -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) + this[PAUSED] = false + this[FLOWING] = true + this.emit('resume') + if (this.buffer.length) + this[FLUSH]() + else if (this[EOF]) + this[MAYBE_EMIT_END]() + else + this.emit('drain') } - f.called = false - return f -} -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) + resume () { + return this[RESUME]() } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), -/***/ 26687: -/***/ ((module) => { + pause () { + this[FLOWING] = false + this[PAUSED] = true + } -const META = Symbol('proc-log.meta') -module.exports = { - META: META, - output: { - LEVELS: [ - 'standard', - 'error', - 'buffer', - 'flush', - ], - KEYS: { - standard: 'standard', - error: 'error', - buffer: 'buffer', - flush: 'flush', - }, - standard: function (...args) { - return process.emit('output', 'standard', ...args) - }, - error: function (...args) { - return process.emit('output', 'error', ...args) - }, - buffer: function (...args) { - return process.emit('output', 'buffer', ...args) - }, - flush: function (...args) { - return process.emit('output', 'flush', ...args) - }, - }, - log: { - LEVELS: [ - 'notice', - 'error', - 'warn', - 'info', - 'verbose', - 'http', - 'silly', - 'timing', - 'pause', - 'resume', - ], - KEYS: { - notice: 'notice', - error: 'error', - warn: 'warn', - info: 'info', - verbose: 'verbose', - http: 'http', - silly: 'silly', - timing: 'timing', - pause: 'pause', - resume: 'resume', - }, - error: function (...args) { - return process.emit('log', 'error', ...args) - }, - notice: function (...args) { - return process.emit('log', 'notice', ...args) - }, - warn: function (...args) { - return process.emit('log', 'warn', ...args) - }, - info: function (...args) { - return process.emit('log', 'info', ...args) - }, - verbose: function (...args) { - return process.emit('log', 'verbose', ...args) - }, - http: function (...args) { - return process.emit('log', 'http', ...args) - }, - silly: function (...args) { - return process.emit('log', 'silly', ...args) - }, - timing: function (...args) { - return process.emit('log', 'timing', ...args) - }, - pause: function () { - return process.emit('log', 'pause') - }, - resume: function () { - return process.emit('log', 'resume') - }, - }, - time: { - LEVELS: [ - 'start', - 'end', - ], - KEYS: { - start: 'start', - end: 'end', - }, - start: function (name, fn) { - process.emit('time', 'start', name) - function end () { - return process.emit('time', 'end', name) - } - if (typeof fn === 'function') { - const res = fn() - if (res && res.finally) { - return res.finally(end) - } - end() - return res - } - return end - }, - end: function (name) { - return process.emit('time', 'end', name) - }, - }, - input: { - LEVELS: [ - 'start', - 'end', - 'read', - ], - KEYS: { - start: 'start', - end: 'end', - read: 'read', - }, - start: function (fn) { - process.emit('input', 'start') - function end () { - return process.emit('input', 'end') - } - if (typeof fn === 'function') { - const res = fn() - if (res && res.finally) { - return res.finally(end) - } - end() - return res - } - return end - }, - end: function () { - return process.emit('input', 'end') - }, - read: function (...args) { - let resolve, reject - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve - reject = _reject - }) - process.emit('input', 'read', resolve, reject, ...args) - return promise - }, - }, -} + get destroyed () { + return this[DESTROYED] + } + get flowing () { + return this[FLOWING] + } -/***/ }), + get paused () { + return this[PAUSED] + } -/***/ 90390: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + [BUFFERPUSH] (chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1 + else + this[BUFFERLENGTH] += chunk.length + this.buffer.push(chunk) + } -"use strict"; + [BUFFERSHIFT] () { + if (this.buffer.length) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1 + else + this[BUFFERLENGTH] -= this.buffer[0].length + } + return this.buffer.shift() + } + [FLUSH] (noDrain) { + do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) -var errcode = __nccwpck_require__(14339); -var retry = __nccwpck_require__(5546); + if (!noDrain && !this.buffer.length && !this[EOF]) + this.emit('drain') + } -var hasOwn = Object.prototype.hasOwnProperty; + [FLUSHCHUNK] (chunk) { + return chunk ? (this.emit('data', chunk), this.flowing) : false + } -function isRetryError(err) { - return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried'); -} + pipe (dest, opts) { + if (this[DESTROYED]) + return -function promiseRetry(fn, options) { - var temp; - var operation; + const ended = this[EMITTED_END] + opts = opts || {} + if (dest === proc.stdout || dest === proc.stderr) + opts.end = false + else + opts.end = opts.end !== false + opts.proxyErrors = !!opts.proxyErrors - if (typeof fn === 'object' && typeof options === 'function') { - // Swap options and fn when using alternate signature (options, fn) - temp = options; - options = fn; - fn = temp; + // piping an ended stream ends immediately + if (ended) { + if (opts.end) + dest.end() + } else { + this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) + : new PipeProxyErrors(this, dest, opts)) + if (this[ASYNC]) + defer(() => this[RESUME]()) + else + this[RESUME]() } - operation = retry.operation(options); - - return new Promise(function (resolve, reject) { - operation.attempt(function (number) { - Promise.resolve() - .then(function () { - return fn(function (err) { - if (isRetryError(err)) { - err = err.retried; - } + return dest + } - throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err }); - }, number); - }) - .then(resolve, function (err) { - if (isRetryError(err)) { - err = err.retried; + unpipe (dest) { + const p = this.pipes.find(p => p.dest === dest) + if (p) { + this.pipes.splice(this.pipes.indexOf(p), 1) + p.unpipe() + } + } - if (operation.retry(err || new Error())) { - return; - } - } + addListener (ev, fn) { + return this.on(ev, fn) + } - reject(err); - }); - }); - }); -} + on (ev, fn) { + const ret = super.on(ev, fn) + if (ev === 'data' && !this.pipes.length && !this.flowing) + this[RESUME]() + else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) + super.emit('readable') + else if (isEndish(ev) && this[EMITTED_END]) { + super.emit(ev) + this.removeAllListeners(ev) + } else if (ev === 'error' && this[EMITTED_ERROR]) { + if (this[ASYNC]) + defer(() => fn.call(this, this[EMITTED_ERROR])) + else + fn.call(this, this[EMITTED_ERROR]) + } + return ret + } -module.exports = promiseRetry; + get emittedEnd () { + return this[EMITTED_END] + } + [MAYBE_EMIT_END] () { + if (!this[EMITTING_END] && + !this[EMITTED_END] && + !this[DESTROYED] && + this.buffer.length === 0 && + this[EOF]) { + this[EMITTING_END] = true + this.emit('end') + this.emit('prefinish') + this.emit('finish') + if (this[CLOSED]) + this.emit('close') + this[EMITTING_END] = false + } + } -/***/ }), + emit (ev, data, ...extra) { + // error and close are only events allowed after calling destroy() + if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) + return + else if (ev === 'data') { + return !data ? false + : this[ASYNC] ? defer(() => this[EMITDATA](data)) + : this[EMITDATA](data) + } else if (ev === 'end') { + return this[EMITEND]() + } else if (ev === 'close') { + this[CLOSED] = true + // don't emit close before 'end' and 'finish' + if (!this[EMITTED_END] && !this[DESTROYED]) + return + const ret = super.emit('close') + this.removeAllListeners('close') + return ret + } else if (ev === 'error') { + this[EMITTED_ERROR] = data + const ret = super.emit('error', data) + this[MAYBE_EMIT_END]() + return ret + } else if (ev === 'resume') { + const ret = super.emit('resume') + this[MAYBE_EMIT_END]() + return ret + } else if (ev === 'finish' || ev === 'prefinish') { + const ret = super.emit(ev) + this.removeAllListeners(ev) + return ret + } -/***/ 5546: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Some other unknown event + const ret = super.emit(ev, data, ...extra) + this[MAYBE_EMIT_END]() + return ret + } -module.exports = __nccwpck_require__(67084); + [EMITDATA] (data) { + for (const p of this.pipes) { + if (p.dest.write(data) === false) + this.pause() + } + const ret = super.emit('data', data) + this[MAYBE_EMIT_END]() + return ret + } -/***/ }), + [EMITEND] () { + if (this[EMITTED_END]) + return -/***/ 67084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this[EMITTED_END] = true + this.readable = false + if (this[ASYNC]) + defer(() => this[EMITEND2]()) + else + this[EMITEND2]() + } -var RetryOperation = __nccwpck_require__(39538); + [EMITEND2] () { + if (this[DECODER]) { + const data = this[DECODER].end() + if (data) { + for (const p of this.pipes) { + p.dest.write(data) + } + super.emit('data', data) + } + } -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && options.forever, - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; + for (const p of this.pipes) { + p.end() + } + const ret = super.emit('end') + this.removeAllListeners('end') + return ret + } -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); + // const all = await stream.collect() + collect () { + const buf = [] + if (!this[OBJECTMODE]) + buf.dataLength = 0 + // set the promise first, in case an error is raised + // by triggering the flow here. + const p = this.promise() + this.on('data', c => { + buf.push(c) + if (!this[OBJECTMODE]) + buf.dataLength += c.length + }) + return p.then(() => buf) } - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; + // const data = await stream.concat() + concat () { + return this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this.collect().then(buf => + this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) } - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); + // stream.promise().then(() => done, er => emitted error) + promise () { + return new Promise((resolve, reject) => { + this.on(DESTROYED, () => reject(new Error('stream destroyed'))) + this.on('error', er => reject(er)) + this.on('end', () => resolve()) + }) } - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); + // for await (let chunk of stream) + [ASYNCITERATOR] () { + const next = () => { + const res = this.read() + if (res !== null) + return Promise.resolve({ done: false, value: res }) + + if (this[EOF]) + return Promise.resolve({ done: true }) + + let resolve = null + let reject = null + const onerr = er => { + this.removeListener('data', ondata) + this.removeListener('end', onend) + reject(er) + } + const ondata = value => { + this.removeListener('error', onerr) + this.removeListener('end', onend) + this.pause() + resolve({ value: value, done: !!this[EOF] }) + } + const onend = () => { + this.removeListener('error', onerr) + this.removeListener('data', ondata) + resolve({ done: true }) + } + const ondestroy = () => onerr(new Error('stream destroyed')) + return new Promise((res, rej) => { + reject = rej + resolve = res + this.once(DESTROYED, ondestroy) + this.once('error', onerr) + this.once('end', onend) + this.once('data', ondata) + }) + } + + return { next } } - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); + // for (let chunk of stream) + [ITERATOR] () { + const next = () => { + const value = this.read() + const done = value === null + return { value, done } + } + return { next } } - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); + destroy (er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er) + else + this.emit(DESTROYED) + return this + } - return timeouts; -}; + this[DESTROYED] = true -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; + // throw away all buffered data, it's never coming out + this.buffer.length = 0 + this[BUFFERLENGTH] = 0 - var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); + if (typeof this.close === 'function' && !this[CLOSED]) + this.close() - return timeout; -}; + if (er) + this.emit('error', er) + else // if no error to emit, still reject pending promises + this.emit(DESTROYED) -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; + return this } - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } + static isStream (s) { + return !!s && (s instanceof Minipass || s instanceof Stream || + s instanceof EE && ( + typeof s.pipe === 'function' || // readable + (typeof s.write === 'function' && typeof s.end === 'function') // writable + )) + } +} + + +/***/ }), + +/***/ 52899: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const Minipass = __nccwpck_require__(45485) +const EE = __nccwpck_require__(24434) +const isStream = s => s && s instanceof EE && ( + typeof s.pipe === 'function' || // readable + (typeof s.write === 'function' && typeof s.end === 'function') // writable +) + +const _head = Symbol('_head') +const _tail = Symbol('_tail') +const _linkStreams = Symbol('_linkStreams') +const _setHead = Symbol('_setHead') +const _setTail = Symbol('_setTail') +const _onError = Symbol('_onError') +const _onData = Symbol('_onData') +const _onEnd = Symbol('_onEnd') +const _onDrain = Symbol('_onDrain') +const _streams = Symbol('_streams') +class Pipeline extends Minipass { + constructor (opts, ...streams) { + if (isStream(opts)) { + streams.unshift(opts) + opts = {} } + + super(opts) + this[_streams] = [] + if (streams.length) + this.push(...streams) } - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; + [_linkStreams] (streams) { + // reduce takes (left,right), and we return right to make it the + // new left value. + return streams.reduce((src, dest) => { + src.on('error', er => dest.emit('error', er)) + src.pipe(dest) + return dest + }) + } - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); + push (...streams) { + this[_streams].push(...streams) + if (this[_tail]) + streams.unshift(this[_tail]) - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); + const linkRet = this[_linkStreams](streams) - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; + this[_setTail](linkRet) + if (!this[_head]) + this[_setHead](streams[0]) + } + + unshift (...streams) { + this[_streams].unshift(...streams) + if (this[_head]) + streams.push(this[_head]) + + const linkRet = this[_linkStreams](streams) + this[_setHead](streams[0]) + if (!this[_tail]) + this[_setTail](linkRet) + } + + destroy (er) { + // set fire to the whole thing. + this[_streams].forEach(s => + typeof s.destroy === 'function' && s.destroy()) + return super.destroy(er) + } + + // readable interface -> tail + [_setTail] (stream) { + this[_tail] = stream + stream.on('error', er => this[_onError](stream, er)) + stream.on('data', chunk => this[_onData](stream, chunk)) + stream.on('end', () => this[_onEnd](stream)) + stream.on('finish', () => this[_onEnd](stream)) + } + + // errors proxied down the pipeline + // they're considered part of the "read" interface + [_onError] (stream, er) { + if (stream === this[_tail]) + this.emit('error', er) + } + [_onData] (stream, chunk) { + if (stream === this[_tail]) + super.write(chunk) + } + [_onEnd] (stream) { + if (stream === this[_tail]) + super.end() + } + pause () { + super.pause() + return this[_tail] && this[_tail].pause && this[_tail].pause() + } + + // NB: Minipass calls its internal private [RESUME] method during + // pipe drains, to avoid hazards where stream.resume() is overridden. + // Thus, we need to listen to the resume *event*, not override the + // resume() method, and proxy *that* to the tail. + emit (ev, ...args) { + if (ev === 'resume' && this[_tail] && this[_tail].resume) + this[_tail].resume() + return super.emit(ev, ...args) + } + + // writable interface -> head + [_setHead] (stream) { + this[_head] = stream + stream.on('drain', () => this[_onDrain](stream)) } -}; + [_onDrain] (stream) { + if (stream === this[_head]) + this.emit('drain') + } + write (chunk, enc, cb) { + return this[_head].write(chunk, enc, cb) && + (this.flowing || this.buffer.length === 0) + } + end (chunk, enc, cb) { + this[_head].end(chunk, enc, cb) + return this + } +} +module.exports = Pipeline -/***/ }), -/***/ 39538: -/***/ ((module) => { +/***/ }), -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } +/***/ 45485: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; +"use strict"; - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } +const proc = typeof process === 'object' && process ? process : { + stdout: null, + stderr: null, } -module.exports = RetryOperation; +const EE = __nccwpck_require__(24434) +const Stream = __nccwpck_require__(2203) +const SD = (__nccwpck_require__(13193).StringDecoder) -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts; -} +const EOF = Symbol('EOF') +const MAYBE_EMIT_END = Symbol('maybeEmitEnd') +const EMITTED_END = Symbol('emittedEnd') +const EMITTING_END = Symbol('emittingEnd') +const EMITTED_ERROR = Symbol('emittedError') +const CLOSED = Symbol('closed') +const READ = Symbol('read') +const FLUSH = Symbol('flush') +const FLUSHCHUNK = Symbol('flushChunk') +const ENCODING = Symbol('encoding') +const DECODER = Symbol('decoder') +const FLOWING = Symbol('flowing') +const PAUSED = Symbol('paused') +const RESUME = Symbol('resume') +const BUFFERLENGTH = Symbol('bufferLength') +const BUFFERPUSH = Symbol('bufferPush') +const BUFFERSHIFT = Symbol('bufferShift') +const OBJECTMODE = Symbol('objectMode') +const DESTROYED = Symbol('destroyed') +const EMITDATA = Symbol('emitData') +const EMITEND = Symbol('emitEnd') +const EMITEND2 = Symbol('emitEnd2') +const ASYNC = Symbol('async') -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } +const defer = fn => Promise.resolve().then(fn) - this._timeouts = []; - this._cachedTimeouts = null; -}; +// TODO remove when Node v8 support drops +const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' +const ASYNCITERATOR = doIter && Symbol.asyncIterator + || Symbol('asyncIterator not implemented') +const ITERATOR = doIter && Symbol.iterator + || Symbol('iterator not implemented') -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } +// events that mean 'the stream is over' +// these are treated specially, and re-emitted +// if they are listened for after emitting. +const isEndish = ev => + ev === 'end' || + ev === 'finish' || + ev === 'prefinish' - if (!err) { - return false; +const isArrayBuffer = b => b instanceof ArrayBuffer || + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0 + +const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) + +class Pipe { + constructor (src, dest, opts) { + this.src = src + this.dest = dest + this.opts = opts + this.ondrain = () => src[RESUME]() + dest.on('drain', this.ondrain) } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; + unpipe () { + this.dest.removeListener('drain', this.ondrain) + } + // istanbul ignore next - only here for the prototype + proxyErrors () {} + end () { + this.unpipe() + if (this.opts.end) + this.dest.end() } +} - this._errors.push(err); +class PipeProxyErrors extends Pipe { + unpipe () { + this.src.removeListener('error', this.proxyErrors) + super.unpipe() + } + constructor (src, dest, opts) { + super(src, dest, opts) + this.proxyErrors = er => dest.emit('error', er) + src.on('error', this.proxyErrors) + } +} - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(this._errors.length - 1, this._errors.length); - this._timeouts = this._cachedTimeouts.slice(0); - timeout = this._timeouts.shift(); - } else { - return false; - } +module.exports = class Minipass extends Stream { + constructor (options) { + super() + this[FLOWING] = false + // whether we're explicitly paused + this[PAUSED] = false + this.pipes = [] + this.buffer = [] + this[OBJECTMODE] = options && options.objectMode || false + if (this[OBJECTMODE]) + this[ENCODING] = null + else + this[ENCODING] = options && options.encoding || null + if (this[ENCODING] === 'buffer') + this[ENCODING] = null + this[ASYNC] = options && !!options.async || false + this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null + this[EOF] = false + this[EMITTED_END] = false + this[EMITTING_END] = false + this[CLOSED] = false + this[EMITTED_ERROR] = null + this.writable = true + this.readable = true + this[BUFFERLENGTH] = 0 + this[DESTROYED] = false } - var self = this; - var timer = setTimeout(function() { - self._attempts++; + get bufferLength () { return this[BUFFERLENGTH] } - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); + get encoding () { return this[ENCODING] } + set encoding (enc) { + if (this[OBJECTMODE]) + throw new Error('cannot set encoding in objectMode') - if (self._options.unref) { - self._timeout.unref(); - } - } + if (this[ENCODING] && enc !== this[ENCODING] && + (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) + throw new Error('cannot change encoding') - self._fn(self._attempts); - }, timeout); + if (this[ENCODING] !== enc) { + this[DECODER] = enc ? new SD(enc) : null + if (this.buffer.length) + this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) + } - if (this._options.unref) { - timer.unref(); + this[ENCODING] = enc } - return true; -}; - -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } + setEncoding (enc) { + this.encoding = enc } - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } + get objectMode () { return this[OBJECTMODE] } + set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } - this._operationStart = new Date().getTime(); + get ['async'] () { return this[ASYNC] } + set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } - this._fn(this._attempts); -}; + write (chunk, encoding, cb) { + if (this[EOF]) + throw new Error('write after end') -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; + if (this[DESTROYED]) { + this.emit('error', Object.assign( + new Error('Cannot call write after a stream was destroyed'), + { code: 'ERR_STREAM_DESTROYED' } + )) + return true + } -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' -RetryOperation.prototype.start = RetryOperation.prototype.try; + if (!encoding) + encoding = 'utf8' -RetryOperation.prototype.errors = function() { - return this._errors; -}; + const fn = this[ASYNC] ? defer : f => f() -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; + // convert array buffers and typed array views into buffers + // at some point in the future, we may want to do the opposite! + // leave strings and buffers as-is + // anything else switches us into object mode + if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { + if (isArrayBufferView(chunk)) + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + else if (isArrayBuffer(chunk)) + chunk = Buffer.from(chunk) + else if (typeof chunk !== 'string') + // use the setter so we throw if we have encoding set + this.objectMode = true + } -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } + // handle object mode up front, since it's simpler + // this yields better performance, fewer checks later. + if (this[OBJECTMODE]) { + /* istanbul ignore if - maybe impossible? */ + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) - var counts = {}; - var mainError = null; - var mainErrorCount = 0; + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') - counts[message] = count; + if (cb) + fn(cb) - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; + return this.flowing } - } - return mainError; -}; + // at this point the chunk is a buffer or string + // don't buffer it up or send it to the decoder + if (!chunk.length) { + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + if (cb) + fn(cb) + return this.flowing + } + // fast-path writing strings of same encoding to a stream with + // an empty buffer, skipping the buffer/decoder dance + if (typeof chunk === 'string' && + // unless it is a string already ready for us to use + !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { + chunk = Buffer.from(chunk, encoding) + } -/***/ }), + if (Buffer.isBuffer(chunk) && this[ENCODING]) + chunk = this[DECODER].write(chunk) -/***/ 12803: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Note: flushing CAN potentially switch us into not-flowing mode + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) -"use strict"; -/* eslint-disable node/no-deprecated-api */ + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + if (cb) + fn(cb) -var buffer = __nccwpck_require__(20181) -var Buffer = buffer.Buffer + return this.flowing + } -var safer = {} + read (n) { + if (this[DESTROYED]) + return null -var key + if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { + this[MAYBE_EMIT_END]() + return null + } -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} + if (this[OBJECTMODE]) + n = null -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} + if (this.buffer.length > 1 && !this[OBJECTMODE]) { + if (this.encoding) + this.buffer = [this.buffer.join('')] + else + this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] + } -safer.Buffer.prototype = Buffer.prototype + const ret = this[READ](n || null, this.buffer[0]) + this[MAYBE_EMIT_END]() + return ret + } -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + [READ] (n, chunk) { + if (n === chunk.length || n === null) + this[BUFFERSHIFT]() + else { + this.buffer[0] = chunk.slice(n) + chunk = chunk.slice(0, n) + this[BUFFERLENGTH] -= n } - return Buffer(value, encodingOrOffset, length) + + this.emit('data', chunk) + + if (!this.buffer.length && !this[EOF]) + this.emit('drain') + + return chunk } -} -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + if (cb) + this.once('end', cb) + this[EOF] = true + this.writable = false + + // if we haven't written anything, then go ahead and emit, + // even if we're not reading. + // we'll re-emit if a new 'end' listener is added anyway. + // This makes MP more suitable to write-only use cases. + if (this.flowing || !this[PAUSED]) + this[MAYBE_EMIT_END]() + return this } -} -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it + // don't let the internal resume be overwritten + [RESUME] () { + if (this[DESTROYED]) + return + + this[PAUSED] = false + this[FLOWING] = true + this.emit('resume') + if (this.buffer.length) + this[FLUSH]() + else if (this[EOF]) + this[MAYBE_EMIT_END]() + else + this.emit('drain') } -} -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength + resume () { + return this[RESUME]() } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + + pause () { + this[FLOWING] = false + this[PAUSED] = true } -} -module.exports = safer + get destroyed () { + return this[DESTROYED] + } + get flowing () { + return this[FLOWING] + } -/***/ }), + get paused () { + return this[PAUSED] + } -/***/ 89379: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + [BUFFERPUSH] (chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1 + else + this[BUFFERLENGTH] += chunk.length + this.buffer.push(chunk) + } -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY + [BUFFERSHIFT] () { + if (this.buffer.length) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1 + else + this[BUFFERLENGTH] -= this.buffer[0].length + } + return this.buffer.shift() + } + + [FLUSH] (noDrain) { + do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) + + if (!noDrain && !this.buffer.length && !this[EOF]) + this.emit('drain') } - constructor (comp, options) { - options = parseOptions(options) + [FLUSHCHUNK] (chunk) { + return chunk ? (this.emit('data', chunk), this.flowing) : false + } - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } + pipe (dest, opts) { + if (this[DESTROYED]) + return - comp = comp.trim().split(/\s+/).join(' ') - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) + const ended = this[EMITTED_END] + opts = opts || {} + if (dest === proc.stdout || dest === proc.stderr) + opts.end = false + else + opts.end = opts.end !== false + opts.proxyErrors = !!opts.proxyErrors - if (this.semver === ANY) { - this.value = '' + // piping an ended stream ends immediately + if (ended) { + if (opts.end) + dest.end() } else { - this.value = this.operator + this.semver.version + this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) + : new PipeProxyErrors(this, dest, opts)) + if (this[ASYNC]) + defer(() => this[RESUME]()) + else + this[RESUME]() } - debug('comp', this) + return dest } - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) + unpipe (dest) { + const p = this.pipes.find(p => p.dest === dest) + if (p) { + this.pipes.splice(this.pipes.indexOf(p), 1) + p.unpipe() } + } - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } + addListener (ev, fn) { + return this.on(ev, fn) + } - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) + on (ev, fn) { + const ret = super.on(ev, fn) + if (ev === 'data' && !this.pipes.length && !this.flowing) + this[RESUME]() + else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) + super.emit('readable') + else if (isEndish(ev) && this[EMITTED_END]) { + super.emit(ev) + this.removeAllListeners(ev) + } else if (ev === 'error' && this[EMITTED_ERROR]) { + if (this[ASYNC]) + defer(() => fn.call(this, this[EMITTED_ERROR])) + else + fn.call(this, this[EMITTED_ERROR]) } + return ret } - toString () { - return this.value + get emittedEnd () { + return this[EMITTED_END] } - test (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true + [MAYBE_EMIT_END] () { + if (!this[EMITTING_END] && + !this[EMITTED_END] && + !this[DESTROYED] && + this.buffer.length === 0 && + this[EOF]) { + this[EMITTING_END] = true + this.emit('end') + this.emit('prefinish') + this.emit('finish') + if (this[CLOSED]) + this.emit('close') + this[EMITTING_END] = false } + } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } + emit (ev, data, ...extra) { + // error and close are only events allowed after calling destroy() + if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) + return + else if (ev === 'data') { + return !data ? false + : this[ASYNC] ? defer(() => this[EMITDATA](data)) + : this[EMITDATA](data) + } else if (ev === 'end') { + return this[EMITEND]() + } else if (ev === 'close') { + this[CLOSED] = true + // don't emit close before 'end' and 'finish' + if (!this[EMITTED_END] && !this[DESTROYED]) + return + const ret = super.emit('close') + this.removeAllListeners('close') + return ret + } else if (ev === 'error') { + this[EMITTED_ERROR] = data + const ret = super.emit('error', data) + this[MAYBE_EMIT_END]() + return ret + } else if (ev === 'resume') { + const ret = super.emit('resume') + this[MAYBE_EMIT_END]() + return ret + } else if (ev === 'finish' || ev === 'prefinish') { + const ret = super.emit(ev) + this.removeAllListeners(ev) + return ret } - return cmp(version, this.operator, this.semver, this.options) + // Some other unknown event + const ret = super.emit(ev, data, ...extra) + this[MAYBE_EMIT_END]() + return ret } - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') + [EMITDATA] (data) { + for (const p of this.pipes) { + if (p.dest.write(data) === false) + this.pause() } + const ret = super.emit('data', data) + this[MAYBE_EMIT_END]() + return ret + } - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } + [EMITEND] () { + if (this[EMITTED_END]) + return - options = parseOptions(options) + this[EMITTED_END] = true + this.readable = false + if (this[ASYNC]) + defer(() => this[EMITEND2]()) + else + this[EMITEND2]() + } - // Special cases where nothing can possibly be lower - if (options.includePrerelease && - (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { - return false - } - if (!options.includePrerelease && - (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { - return false + [EMITEND2] () { + if (this[DECODER]) { + const data = this[DECODER].end() + if (data) { + for (const p of this.pipes) { + p.dest.write(data) + } + super.emit('data', data) + } } - // Same direction increasing (> or >=) - if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { - return true - } - // Same direction decreasing (< or <=) - if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { - return true - } - // same SemVer and both sides are inclusive (<= or >=) - if ( - (this.semver.version === comp.semver.version) && - this.operator.includes('=') && comp.operator.includes('=')) { - return true - } - // opposite directions less than - if (cmp(this.semver, '<', comp.semver, options) && - this.operator.startsWith('>') && comp.operator.startsWith('<')) { - return true - } - // opposite directions greater than - if (cmp(this.semver, '>', comp.semver, options) && - this.operator.startsWith('<') && comp.operator.startsWith('>')) { - return true + for (const p of this.pipes) { + p.end() } - return false + const ret = super.emit('end') + this.removeAllListeners('end') + return ret } -} -module.exports = Comparator + // const all = await stream.collect() + collect () { + const buf = [] + if (!this[OBJECTMODE]) + buf.dataLength = 0 + // set the promise first, in case an error is raised + // by triggering the flow here. + const p = this.promise() + this.on('data', c => { + buf.push(c) + if (!this[OBJECTMODE]) + buf.dataLength += c.length + }) + return p.then(() => buf) + } -const parseOptions = __nccwpck_require__(70356) -const { safeRe: re, t } = __nccwpck_require__(95471) -const cmp = __nccwpck_require__(28646) -const debug = __nccwpck_require__(1159) -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(96782) + // const data = await stream.concat() + concat () { + return this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this.collect().then(buf => + this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) + } + // stream.promise().then(() => done, er => emitted error) + promise () { + return new Promise((resolve, reject) => { + this.on(DESTROYED, () => reject(new Error('stream destroyed'))) + this.on('error', er => reject(er)) + this.on('end', () => resolve()) + }) + } -/***/ }), + // for await (let chunk of stream) + [ASYNCITERATOR] () { + const next = () => { + const res = this.read() + if (res !== null) + return Promise.resolve({ done: false, value: res }) -/***/ 96782: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this[EOF]) + return Promise.resolve({ done: true }) -const SPACE_CHARACTERS = /\s+/g + let resolve = null + let reject = null + const onerr = er => { + this.removeListener('data', ondata) + this.removeListener('end', onend) + reject(er) + } + const ondata = value => { + this.removeListener('error', onerr) + this.removeListener('end', onend) + this.pause() + resolve({ value: value, done: !!this[EOF] }) + } + const onend = () => { + this.removeListener('error', onerr) + this.removeListener('data', ondata) + resolve({ done: true }) + } + const ondestroy = () => onerr(new Error('stream destroyed')) + return new Promise((res, rej) => { + reject = rej + resolve = res + this.once(DESTROYED, ondestroy) + this.once('error', onerr) + this.once('end', onend) + this.once('data', ondata) + }) + } -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - options = parseOptions(options) + return { next } + } - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } + // for (let chunk of stream) + [ITERATOR] () { + const next = () => { + const value = this.read() + const done = value === null + return { value, done } } + return { next } + } - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.formatted = undefined + destroy (er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er) + else + this.emit(DESTROYED) return this } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First reduce all whitespace as much as possible so we do not have to rely - // on potentially slow regexes like \s*. This is then stored and used for - // future error messages as well. - this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') - - // First, split on || - this.set = this.raw - .split('||') - // map the range to a 2d array of comparators - .map(r => this.parseRange(r.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`) - } + this[DESTROYED] = true - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0] - this.set = this.set.filter(c => !isNullSet(c[0])) - if (this.set.length === 0) { - this.set = [first] - } else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c] - break - } - } - } - } + // throw away all buffered data, it's never coming out + this.buffer.length = 0 + this[BUFFERLENGTH] = 0 - this.formatted = undefined - } + if (typeof this.close === 'function' && !this[CLOSED]) + this.close() - get range () { - if (this.formatted === undefined) { - this.formatted = '' - for (let i = 0; i < this.set.length; i++) { - if (i > 0) { - this.formatted += '||' - } - const comps = this.set[i] - for (let k = 0; k < comps.length; k++) { - if (k > 0) { - this.formatted += ' ' - } - this.formatted += comps[k].toString().trim() - } - } - } - return this.formatted - } + if (er) + this.emit('error', er) + else // if no error to emit, still reject pending promises + this.emit(DESTROYED) - format () { - return this.range + return this } - toString () { - return this.range + static isStream (s) { + return !!s && (s instanceof Minipass || s instanceof Stream || + s instanceof EE && ( + typeof s.pipe === 'function' || // readable + (typeof s.write === 'function' && typeof s.end === 'function') // writable + )) } +} - parseRange (range) { - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = - (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | - (this.options.loose && FLAG_LOOSE) - const memoKey = memoOpts + ':' + range - const cached = cache.get(memoKey) - if (cached) { - return cached - } - const loose = this.options.loose - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) - debug('hyphen replace', range) +/***/ }), - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range) +/***/ 48484: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - debug('tilde trim', range) +const Minipass = __nccwpck_require__(56670) - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - debug('caret trim', range) +class SizeError extends Error { + constructor (found, expect) { + super(`Bad data size: expected ${expect} bytes, but got ${found}`) + this.expect = expect + this.found = found + this.code = 'EBADSIZE' + Error.captureStackTrace(this, this.constructor) + } + get name () { + return 'SizeError' + } +} - // At this point, the range is completely trimmed and - // ready to be split into comparators. +class MinipassSized extends Minipass { + constructor (options = {}) { + super(options) - let rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) + if (options.objectMode) + throw new TypeError(`${ + this.constructor.name + } streams only work with string and buffer data`) - if (loose) { - // in loose mode, throw out any that are not valid comparators - rangeList = rangeList.filter(comp => { - debug('loose invalid filter', comp, this.options) - return !!comp.match(re[t.COMPARATORLOOSE]) - }) - } - debug('range list', rangeList) + this.found = 0 + this.expect = options.size + if (typeof this.expect !== 'number' || + this.expect > Number.MAX_SAFE_INTEGER || + isNaN(this.expect) || + this.expect < 0 || + !isFinite(this.expect) || + this.expect !== Math.floor(this.expect)) + throw new Error('invalid expected size: ' + this.expect) + } - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - const rangeMap = new Map() - const comparators = rangeList.map(comp => new Comparator(comp, this.options)) - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp] - } - rangeMap.set(comp.value, comp) - } - if (rangeMap.size > 1 && rangeMap.has('')) { - rangeMap.delete('') + write (chunk, encoding, cb) { + const buffer = Buffer.isBuffer(chunk) ? chunk + : typeof chunk === 'string' ? + Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8') + : chunk + + if (!Buffer.isBuffer(buffer)) { + this.emit('error', new TypeError(`${ + this.constructor.name + } streams only work with string and buffer data`)) + return false } - const result = [...rangeMap.values()] - cache.set(memoKey, result) - return result + this.found += buffer.length + if (this.found > this.expect) + this.emit('error', new SizeError(this.found, this.expect)) + + return super.write(chunk, encoding, cb) } - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') + emit (ev, ...data) { + if (ev === 'end') { + if (this.found !== this.expect) + this.emit('error', new SizeError(this.found, this.expect)) } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) + return super.emit(ev, ...data) } +} - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } +MinipassSized.SizeError = SizeError - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } +module.exports = MinipassSized - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } + +/***/ }), + +/***/ 56670: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +const proc = typeof process === 'object' && process ? process : { + stdout: null, + stderr: null, } +const EE = __nccwpck_require__(24434) +const Stream = __nccwpck_require__(2203) +const SD = (__nccwpck_require__(13193).StringDecoder) -module.exports = Range +const EOF = Symbol('EOF') +const MAYBE_EMIT_END = Symbol('maybeEmitEnd') +const EMITTED_END = Symbol('emittedEnd') +const EMITTING_END = Symbol('emittingEnd') +const EMITTED_ERROR = Symbol('emittedError') +const CLOSED = Symbol('closed') +const READ = Symbol('read') +const FLUSH = Symbol('flush') +const FLUSHCHUNK = Symbol('flushChunk') +const ENCODING = Symbol('encoding') +const DECODER = Symbol('decoder') +const FLOWING = Symbol('flowing') +const PAUSED = Symbol('paused') +const RESUME = Symbol('resume') +const BUFFERLENGTH = Symbol('bufferLength') +const BUFFERPUSH = Symbol('bufferPush') +const BUFFERSHIFT = Symbol('bufferShift') +const OBJECTMODE = Symbol('objectMode') +const DESTROYED = Symbol('destroyed') +const EMITDATA = Symbol('emitData') +const EMITEND = Symbol('emitEnd') +const EMITEND2 = Symbol('emitEnd2') +const ASYNC = Symbol('async') -const LRU = __nccwpck_require__(61383) -const cache = new LRU() +const defer = fn => Promise.resolve().then(fn) -const parseOptions = __nccwpck_require__(70356) -const Comparator = __nccwpck_require__(89379) -const debug = __nccwpck_require__(1159) -const SemVer = __nccwpck_require__(7163) -const { - safeRe: re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace, -} = __nccwpck_require__(95471) -const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(45101) +// TODO remove when Node v8 support drops +const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1' +const ASYNCITERATOR = doIter && Symbol.asyncIterator + || Symbol('asyncIterator not implemented') +const ITERATOR = doIter && Symbol.iterator + || Symbol('iterator not implemented') -const isNullSet = c => c.value === '<0.0.0-0' -const isAny = c => c.value === '' +// events that mean 'the stream is over' +// these are treated specially, and re-emitted +// if they are listened for after emitting. +const isEndish = ev => + ev === 'end' || + ev === 'finish' || + ev === 'prefinish' -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() +const isArrayBuffer = b => b instanceof ArrayBuffer || + typeof b === 'object' && + b.constructor && + b.constructor.name === 'ArrayBuffer' && + b.byteLength >= 0 - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) +const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b) - testComparator = remainingComparators.pop() +class Pipe { + constructor (src, dest, opts) { + this.src = src + this.dest = dest + this.opts = opts + this.ondrain = () => src[RESUME]() + dest.on('drain', this.ondrain) + } + unpipe () { + this.dest.removeListener('drain', this.ondrain) + } + // istanbul ignore next - only here for the prototype + proxyErrors () {} + end () { + this.unpipe() + if (this.opts.end) + this.dest.end() } - - return result } -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp +class PipeProxyErrors extends Pipe { + unpipe () { + this.src.removeListener('error', this.proxyErrors) + super.unpipe() + } + constructor (src, dest, opts) { + super(src, dest, opts) + this.proxyErrors = er => dest.emit('error', er) + src.on('error', this.proxyErrors) + } } -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' +module.exports = class Minipass extends Stream { + constructor (options) { + super() + this[FLOWING] = false + // whether we're explicitly paused + this[PAUSED] = false + this.pipes = [] + this.buffer = [] + this[OBJECTMODE] = options && options.objectMode || false + if (this[OBJECTMODE]) + this[ENCODING] = null + else + this[ENCODING] = options && options.encoding || null + if (this[ENCODING] === 'buffer') + this[ENCODING] = null + this[ASYNC] = options && !!options.async || false + this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null + this[EOF] = false + this[EMITTED_END] = false + this[EMITTING_END] = false + this[CLOSED] = false + this[EMITTED_ERROR] = null + this.writable = true + this.readable = true + this[BUFFERLENGTH] = 0 + this[DESTROYED] = false + } -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 -// ~0.0.1 --> >=0.0.1 <0.1.0-0 -const replaceTildes = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceTilde(c, options)) - .join(' ') -} + get bufferLength () { return this[BUFFERLENGTH] } -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret + get encoding () { return this[ENCODING] } + set encoding (enc) { + if (this[OBJECTMODE]) + throw new Error('cannot set encoding in objectMode') - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0` + if (this[ENCODING] && enc !== this[ENCODING] && + (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH])) + throw new Error('cannot change encoding') + + if (this[ENCODING] !== enc) { + this[DECODER] = enc ? new SD(enc) : null + if (this.buffer.length) + this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk)) } - debug('tilde return', ret) - return ret - }) -} + this[ENCODING] = enc + } -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 -// ^1.2.3 --> >=1.2.3 <2.0.0-0 -// ^1.2.0 --> >=1.2.0 <2.0.0-0 -// ^0.0.1 --> >=0.0.1 <0.0.2-0 -// ^0.1.0 --> >=0.1.0 <0.2.0-0 -const replaceCarets = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceCaret(c, options)) - .join(' ') -} + setEncoding (enc) { + this.encoding = enc + } -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - const z = options.includePrerelease ? '-0' : '' - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret + get objectMode () { return this[OBJECTMODE] } + set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om } - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0` - } + get ['async'] () { return this[ASYNC] } + set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a } + + write (chunk, encoding, cb) { + if (this[EOF]) + throw new Error('write after end') + + if (this[DESTROYED]) { + this.emit('error', Object.assign( + new Error('Cannot call write after a stream was destroyed'), + { code: 'ERR_STREAM_DESTROYED' } + )) + return true } - debug('caret return', ret) - return ret - }) -} + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp - .split(/\s+/) - .map((c) => replaceXRange(c, options)) - .join(' ') -} + if (!encoding) + encoding = 'utf8' -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp + const fn = this[ASYNC] ? defer : f => f() - if (gtlt === '=' && anyX) { - gtlt = '' + // convert array buffers and typed array views into buffers + // at some point in the future, we may want to do the opposite! + // leave strings and buffers as-is + // anything else switches us into object mode + if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) { + if (isArrayBufferView(chunk)) + chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + else if (isArrayBuffer(chunk)) + chunk = Buffer.from(chunk) + else if (typeof chunk !== 'string') + // use the setter so we throw if we have encoding set + this.objectMode = true } - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' + // handle object mode up front, since it's simpler + // this yields better performance, fewer checks later. + if (this[OBJECTMODE]) { + /* istanbul ignore if - maybe impossible? */ + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') - if (gtlt === '<') { - pr = '-0' - } + if (cb) + fn(cb) - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0` + return this.flowing } - debug('xRange return', ret) + // at this point the chunk is a buffer or string + // don't buffer it up or send it to the decoder + if (!chunk.length) { + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + if (cb) + fn(cb) + return this.flowing + } - return ret - }) -} + // fast-path writing strings of same encoding to a stream with + // an empty buffer, skipping the buffer/decoder dance + if (typeof chunk === 'string' && + // unless it is a string already ready for us to use + !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) { + chunk = Buffer.from(chunk, encoding) + } -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp - .trim() - .replace(re[t.STAR], '') -} + if (Buffer.isBuffer(chunk) && this[ENCODING]) + chunk = this[DECODER].write(chunk) -const replaceGTE0 = (comp, options) => { - debug('replaceGTE0', comp, options) - return comp - .trim() - .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') -} + // Note: flushing CAN potentially switch us into not-flowing mode + if (this.flowing && this[BUFFERLENGTH] !== 0) + this[FLUSH](true) -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 -// TODO build? -const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` - } else if (fpr) { - from = `>=${from}` - } else { - from = `>=${from}${incPr ? '-0' : ''}` - } + if (this.flowing) + this.emit('data', chunk) + else + this[BUFFERPUSH](chunk) + + if (this[BUFFERLENGTH] !== 0) + this.emit('readable') + + if (cb) + fn(cb) - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0` - } else { - to = `<=${to}` + return this.flowing } - return `${from} ${to}`.trim() -} + read (n) { + if (this[DESTROYED]) + return null -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) { + this[MAYBE_EMIT_END]() + return null } - } - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } + if (this[OBJECTMODE]) + n = null - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } + if (this.buffer.length > 1 && !this[OBJECTMODE]) { + if (this.encoding) + this.buffer = [this.buffer.join('')] + else + this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])] } - // Version has a -pre, but it's not one of the ones we like. - return false + const ret = this[READ](n || null, this.buffer[0]) + this[MAYBE_EMIT_END]() + return ret } - return true -} - + [READ] (n, chunk) { + if (n === chunk.length || n === null) + this[BUFFERSHIFT]() + else { + this.buffer[0] = chunk.slice(n) + chunk = chunk.slice(0, n) + this[BUFFERLENGTH] -= n + } -/***/ }), + this.emit('data', chunk) -/***/ 7163: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!this.buffer.length && !this[EOF]) + this.emit('drain') -const debug = __nccwpck_require__(1159) -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(45101) -const { safeRe: re, safeSrc: src, t } = __nccwpck_require__(95471) + return chunk + } -const parseOptions = __nccwpck_require__(70356) -const { compareIdentifiers } = __nccwpck_require__(73348) -class SemVer { - constructor (version, options) { - options = parseOptions(options) + end (chunk, encoding, cb) { + if (typeof chunk === 'function') + cb = chunk, chunk = null + if (typeof encoding === 'function') + cb = encoding, encoding = 'utf8' + if (chunk) + this.write(chunk, encoding) + if (cb) + this.once('end', cb) + this[EOF] = true + this.writable = false - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) - } + // if we haven't written anything, then go ahead and emit, + // even if we're not reading. + // we'll re-emit if a new 'end' listener is added anyway. + // This makes MP more suitable to write-only use cases. + if (this.flowing || !this[PAUSED]) + this[MAYBE_EMIT_END]() + return this + } - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } + // don't let the internal resume be overwritten + [RESUME] () { + if (this[DESTROYED]) + return - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease + this[PAUSED] = false + this[FLOWING] = true + this.emit('resume') + if (this.buffer.length) + this[FLUSH]() + else if (this[EOF]) + this[MAYBE_EMIT_END]() + else + this.emit('drain') + } - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + resume () { + return this[RESUME]() + } - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } + pause () { + this[FLOWING] = false + this[PAUSED] = true + } - this.raw = version + get destroyed () { + return this[DESTROYED] + } - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] + get flowing () { + return this[FLOWING] + } - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + get paused () { + return this[PAUSED] + } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } + [BUFFERPUSH] (chunk) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] += 1 + else + this[BUFFERLENGTH] += chunk.length + this.buffer.push(chunk) + } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') + [BUFFERSHIFT] () { + if (this.buffer.length) { + if (this[OBJECTMODE]) + this[BUFFERLENGTH] -= 1 + else + this[BUFFERLENGTH] -= this.buffer[0].length } + return this.buffer.shift() + } - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } + [FLUSH] (noDrain) { + do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]())) - this.build = m[5] ? m[5].split('.') : [] - this.format() + if (!noDrain && !this.buffer.length && !this[EOF]) + this.emit('drain') } - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version + [FLUSHCHUNK] (chunk) { + return chunk ? (this.emit('data', chunk), this.flowing) : false } - toString () { - return this.version - } + pipe (dest, opts) { + if (this[DESTROYED]) + return - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer(other, this.options) - } + const ended = this[EMITTED_END] + opts = opts || {} + if (dest === proc.stdout || dest === proc.stderr) + opts.end = false + else + opts.end = opts.end !== false + opts.proxyErrors = !!opts.proxyErrors - if (other.version === this.version) { - return 0 + // piping an ended stream ends immediately + if (ended) { + if (opts.end) + dest.end() + } else { + this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts) + : new PipeProxyErrors(this, dest, opts)) + if (this[ASYNC]) + defer(() => this[RESUME]()) + else + this[RESUME]() } - return this.compareMain(other) || this.comparePre(other) + return dest } - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + unpipe (dest) { + const p = this.pipes.find(p => p.dest === dest) + if (p) { + this.pipes.splice(this.pipes.indexOf(p), 1) + p.unpipe() } - - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) } - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } + addListener (ev, fn) { + return this.on(ev, fn) + } - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + on (ev, fn) { + const ret = super.on(ev, fn) + if (ev === 'data' && !this.pipes.length && !this.flowing) + this[RESUME]() + else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) + super.emit('readable') + else if (isEndish(ev) && this[EMITTED_END]) { + super.emit(ev) + this.removeAllListeners(ev) + } else if (ev === 'error' && this[EMITTED_ERROR]) { + if (this[ASYNC]) + defer(() => fn.call(this, this[EMITTED_ERROR])) + else + fn.call(this, this[EMITTED_ERROR]) } + return ret + } - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) + get emittedEnd () { + return this[EMITTED_END] } - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + [MAYBE_EMIT_END] () { + if (!this[EMITTING_END] && + !this[EMITTED_END] && + !this[DESTROYED] && + this.buffer.length === 0 && + this[EOF]) { + this[EMITTING_END] = true + this.emit('end') + this.emit('prefinish') + this.emit('finish') + if (this[CLOSED]) + this.emit('close') + this[EMITTING_END] = false } - - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('build compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) } - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier, identifierBase) { - if (release.startsWith('pre')) { - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } - // Avoid an invalid semver results - if (identifier) { - const r = new RegExp(`^${this.options.loose ? src[t.PRERELEASELOOSE] : src[t.PRERELEASE]}$`) - const match = `-${identifier}`.match(r) - if (!match || match[1] !== identifier) { - throw new Error(`invalid identifier: ${identifier}`) - } - } + emit (ev, data, ...extra) { + // error and close are only events allowed after calling destroy() + if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED]) + return + else if (ev === 'data') { + return !data ? false + : this[ASYNC] ? defer(() => this[EMITDATA](data)) + : this[EMITDATA](data) + } else if (ev === 'end') { + return this[EMITEND]() + } else if (ev === 'close') { + this[CLOSED] = true + // don't emit close before 'end' and 'finish' + if (!this[EMITTED_END] && !this[DESTROYED]) + return + const ret = super.emit('close') + this.removeAllListeners('close') + return ret + } else if (ev === 'error') { + this[EMITTED_ERROR] = data + const ret = super.emit('error', data) + this[MAYBE_EMIT_END]() + return ret + } else if (ev === 'resume') { + const ret = super.emit('resume') + this[MAYBE_EMIT_END]() + return ret + } else if (ev === 'finish' || ev === 'prefinish') { + const ret = super.emit(ev) + this.removeAllListeners(ev) + return ret } - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier, identifierBase) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier, identifierBase) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier, identifierBase) - this.inc('pre', identifier, identifierBase) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier, identifierBase) - } - this.inc('pre', identifier, identifierBase) - break - case 'release': - if (this.prerelease.length === 0) { - throw new Error(`version ${this.raw} is not a prerelease`) - } - this.prerelease.length = 0 - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': { - const base = Number(identifierBase) ? 1 : 0 + // Some other unknown event + const ret = super.emit(ev, data, ...extra) + this[MAYBE_EMIT_END]() + return ret + } - if (this.prerelease.length === 0) { - this.prerelease = [base] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - if (identifier === this.prerelease.join('.') && identifierBase === false) { - throw new Error('invalid increment argument: identifier already exists') - } - this.prerelease.push(base) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - let prerelease = [identifier, base] - if (identifierBase === false) { - prerelease = [identifier] - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease - } - } else { - this.prerelease = prerelease - } - } - break - } - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.raw = this.format() - if (this.build.length) { - this.raw += `+${this.build.join('.')}` + [EMITDATA] (data) { + for (const p of this.pipes) { + if (p.dest.write(data) === false) + this.pause() } - return this + const ret = super.emit('data', data) + this[MAYBE_EMIT_END]() + return ret } -} -module.exports = SemVer + [EMITEND] () { + if (this[EMITTED_END]) + return + this[EMITTED_END] = true + this.readable = false + if (this[ASYNC]) + defer(() => this[EMITEND2]()) + else + this[EMITEND2]() + } -/***/ }), + [EMITEND2] () { + if (this[DECODER]) { + const data = this[DECODER].end() + if (data) { + for (const p of this.pipes) { + p.dest.write(data) + } + super.emit('data', data) + } + } -/***/ 1799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (const p of this.pipes) { + p.end() + } + const ret = super.emit('end') + this.removeAllListeners('end') + return ret + } -const parse = __nccwpck_require__(16353) -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean + // const all = await stream.collect() + collect () { + const buf = [] + if (!this[OBJECTMODE]) + buf.dataLength = 0 + // set the promise first, in case an error is raised + // by triggering the flow here. + const p = this.promise() + this.on('data', c => { + buf.push(c) + if (!this[OBJECTMODE]) + buf.dataLength += c.length + }) + return p.then(() => buf) + } + // const data = await stream.concat() + concat () { + return this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this.collect().then(buf => + this[OBJECTMODE] + ? Promise.reject(new Error('cannot concat in objectMode')) + : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength)) + } -/***/ }), + // stream.promise().then(() => done, er => emitted error) + promise () { + return new Promise((resolve, reject) => { + this.on(DESTROYED, () => reject(new Error('stream destroyed'))) + this.on('error', er => reject(er)) + this.on('end', () => resolve()) + }) + } -/***/ 28646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // for await (let chunk of stream) + [ASYNCITERATOR] () { + const next = () => { + const res = this.read() + if (res !== null) + return Promise.resolve({ done: false, value: res }) -const eq = __nccwpck_require__(55082) -const neq = __nccwpck_require__(4974) -const gt = __nccwpck_require__(16599) -const gte = __nccwpck_require__(41236) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(56717) + if (this[EOF]) + return Promise.resolve({ done: true }) -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version + let resolve = null + let reject = null + const onerr = er => { + this.removeListener('data', ondata) + this.removeListener('end', onend) + reject(er) } - return a === b - - case '!==': - if (typeof a === 'object') { - a = a.version + const ondata = value => { + this.removeListener('error', onerr) + this.removeListener('end', onend) + this.pause() + resolve({ value: value, done: !!this[EOF] }) } - if (typeof b === 'object') { - b = b.version + const onend = () => { + this.removeListener('error', onerr) + this.removeListener('data', ondata) + resolve({ done: true }) } - return a !== b + const ondestroy = () => onerr(new Error('stream destroyed')) + return new Promise((res, rej) => { + reject = rej + resolve = res + this.once(DESTROYED, ondestroy) + this.once('error', onerr) + this.once('end', onend) + this.once('data', ondata) + }) + } - case '': - case '=': - case '==': - return eq(a, b, loose) + return { next } + } - case '!=': - return neq(a, b, loose) + // for (let chunk of stream) + [ITERATOR] () { + const next = () => { + const value = this.read() + const done = value === null + return { value, done } + } + return { next } + } - case '>': - return gt(a, b, loose) + destroy (er) { + if (this[DESTROYED]) { + if (er) + this.emit('error', er) + else + this.emit(DESTROYED) + return this + } - case '>=': - return gte(a, b, loose) + this[DESTROYED] = true - case '<': - return lt(a, b, loose) + // throw away all buffered data, it's never coming out + this.buffer.length = 0 + this[BUFFERLENGTH] = 0 - case '<=': - return lte(a, b, loose) + if (typeof this.close === 'function' && !this[CLOSED]) + this.close() - default: - throw new TypeError(`Invalid operator: ${op}`) + if (er) + this.emit('error', er) + else // if no error to emit, still reject pending promises + this.emit(DESTROYED) + + return this + } + + static isStream (s) { + return !!s && (s instanceof Minipass || s instanceof Stream || + s instanceof EE && ( + typeof s.pipe === 'function' || // readable + (typeof s.write === 'function' && typeof s.end === 'function') // writable + )) } } -module.exports = cmp /***/ }), -/***/ 35385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 70744: +/***/ ((module) => { -const SemVer = __nccwpck_require__(7163) -const parse = __nccwpck_require__(16353) -const { safeRe: re, t } = __nccwpck_require__(95471) +/** + * Helpers. + */ -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - if (typeof version === 'number') { - version = String(version) - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - if (typeof version !== 'string') { - return null +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - options = options || {} +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - let match = null - if (!options.rtl) { - match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] - let next - while ((next = coerceRtlRegex.exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - coerceRtlRegex.lastIndex = -1 +function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - - if (match === null) { - return null + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; } +} - const major = match[2] - const minor = match[3] || '0' - const patch = match[4] || '0' - const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' - const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } -module.exports = coerce +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -/***/ }), +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} -/***/ 37648: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Pluralization helper. + */ -const SemVer = __nccwpck_require__(7163) -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } -module.exports = compareBuild /***/ }), -/***/ 56874: +/***/ 60668: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const compare = __nccwpck_require__(78469) -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose +"use strict"; +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 78469: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var preferredCharsets = __nccwpck_require__(79168) +var preferredEncodings = __nccwpck_require__(25111) +var preferredLanguages = __nccwpck_require__(56008) +var preferredMediaTypes = __nccwpck_require__(53672) -const SemVer = __nccwpck_require__(7163) -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) +/** + * Module exports. + * @public + */ -module.exports = compare +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ -/***/ }), +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } -/***/ 70711: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.request = request; +} -const parse = __nccwpck_require__(16353) +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; -const diff = (version1, version2) => { - const v1 = parse(version1, null, true) - const v2 = parse(version2, null, true) - const comparison = v1.compare(v2) +Negotiator.prototype.charsets = function charsets(available) { + return preferredCharsets(this.request.headers['accept-charset'], available); +}; - if (comparison === 0) { - return null - } +Negotiator.prototype.encoding = function encoding(available, opts) { + var set = this.encodings(available, opts); + return set && set[0]; +}; - const v1Higher = comparison > 0 - const highVersion = v1Higher ? v1 : v2 - const lowVersion = v1Higher ? v2 : v1 - const highHasPre = !!highVersion.prerelease.length - const lowHasPre = !!lowVersion.prerelease.length +Negotiator.prototype.encodings = function encodings(available, options) { + var opts = options || {}; + return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred); +}; - if (lowHasPre && !highHasPre) { - // Going from prerelease -> no prerelease requires some special casing +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; - // If the low version has only a major, then it will always be a major - // Some examples: - // 1.0.0-1 -> 1.0.0 - // 1.0.0-1 -> 1.1.1 - // 1.0.0-1 -> 2.0.0 - if (!lowVersion.patch && !lowVersion.minor) { - return 'major' - } +Negotiator.prototype.languages = function languages(available) { + return preferredLanguages(this.request.headers['accept-language'], available); +}; - // If the main part has no difference - if (lowVersion.compareMain(highVersion) === 0) { - if (lowVersion.minor && !lowVersion.patch) { - return 'minor' - } - return 'patch' - } - } +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; - // add the `pre` prefix if we are going to a prerelease version - const prefix = highHasPre ? 'pre' : '' +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + return preferredMediaTypes(this.request.headers.accept, available); +}; - if (v1.major !== v2.major) { - return prefix + 'major' - } +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; - if (v1.minor !== v2.minor) { - return prefix + 'minor' - } - if (v1.patch !== v2.patch) { - return prefix + 'patch' - } +/***/ }), + +/***/ 79168: +/***/ ((module) => { + +"use strict"; +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + - // high and low are preleases - return 'prerelease' -} -module.exports = diff +/** + * Module exports. + * @public + */ +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; -/***/ }), +/** + * Module variables. + * @private + */ -/***/ 55082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; -const compare = __nccwpck_require__(78469) -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq +/** + * Parse the Accept-Charset header. + * @private + */ +function parseAcceptCharset(accept) { + var accepts = accept.split(','); -/***/ }), + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); -/***/ 16599: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (charset) { + accepts[j++] = charset; + } + } -const compare = __nccwpck_require__(78469) -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt + // trim accepts + accepts.length = j; + return accepts; +} -/***/ }), +/** + * Parse a charset from the Accept-Charset header. + * @private + */ -/***/ 41236: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; -const compare = __nccwpck_require__(78469) -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + return { + charset: charset, + q: q, + i: i + }; +} -/***/ }), +/** + * Get the priority of a charset. + * @private + */ -/***/ 62338: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; -const SemVer = __nccwpck_require__(7163) + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); -const inc = (version, release, options, identifier, identifierBase) => { - if (typeof (options) === 'string') { - identifierBase = identifier - identifier = options - options = undefined + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } } - try { - return new SemVer( - version instanceof SemVer ? version.version : version, - options - ).inc(release, identifier, identifierBase).version - } catch (er) { + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { return null } -} -module.exports = inc + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} -/***/ }), +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ -/***/ 3872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); -const compare = __nccwpck_require__(78469) -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); -/***/ }), + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} -/***/ 56717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Compare two specs. + * @private + */ -const compare = __nccwpck_require__(78469) -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} +/** + * Get full charset string. + * @private + */ -/***/ }), +function getFullCharset(spec) { + return spec.charset; +} -/***/ 68511: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Check if a spec has any quality. + * @private + */ -const SemVer = __nccwpck_require__(7163) -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major +function isQuality(spec) { + return spec.q > 0; +} /***/ }), -/***/ 32603: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 25111: +/***/ ((module) => { -const SemVer = __nccwpck_require__(7163) -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor +"use strict"; +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 4974: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Module exports. + * @public + */ -const compare = __nccwpck_require__(78469) -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; +/** + * Module variables. + * @private + */ -/***/ }), +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; -/***/ 16353: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Parse the Accept-Encoding header. + * @private + */ -const SemVer = __nccwpck_require__(7163) -const parse = (version, options, throwErrors = false) => { - if (version instanceof SemVer) { - return version - } - try { - return new SemVer(version, options) - } catch (er) { - if (!throwErrors) { - return null +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); } - throw er } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; } -module.exports = parse +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; -/***/ }), + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var j = 0; j < params.length; j++) { + var p = params[j].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } -/***/ 48756: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return { + encoding: encoding, + q: q, + i: i + }; +} -const SemVer = __nccwpck_require__(7163) -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch +/** + * Get the priority of an encoding. + * @private + */ +function getEncodingPriority(encoding, accepted, index) { + var priority = {encoding: encoding, o: -1, q: 0, s: 0}; -/***/ }), + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); -/***/ 15714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } -const parse = __nccwpck_require__(16353) -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + return priority; } -module.exports = prerelease +/** + * Get the specificity of the encoding. + * @private + */ -/***/ }), - -/***/ 32173: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } -const compare = __nccwpck_require__(78469) -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare + return { + encoding: encoding, + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ -/***/ }), +function preferredEncodings(accept, provided, preferred) { + var accepts = parseAcceptEncoding(accept || ''); -/***/ 87192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var comparator = preferred ? function comparator (a, b) { + if (a.q !== b.q) { + return b.q - a.q // higher quality first + } -const compareBuild = __nccwpck_require__(37648) -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort + var aPreferred = preferred.indexOf(a.encoding) + var bPreferred = preferred.indexOf(b.encoding) + if (aPreferred === -1 && bPreferred === -1) { + // consider the original specifity/order + return (b.s - a.s) || (a.o - b.o) || (a.i - b.i) + } -/***/ }), + if (aPreferred !== -1 && bPreferred !== -1) { + return aPreferred - bPreferred // consider the preferred order + } -/***/ 68011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return aPreferred === -1 ? 1 : -1 // preferred first + } : compareSpecs; -const Range = __nccwpck_require__(96782) -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(comparator) + .map(getFullEncoding); } - return range.test(version) -} -module.exports = satisfies + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); -/***/ }), + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} -/***/ 29872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Compare two specs. + * @private + */ -const compareBuild = __nccwpck_require__(37648) -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i); +} +/** + * Get full encoding string. + * @private + */ -/***/ }), +function getFullEncoding(spec) { + return spec.encoding; +} -/***/ 58780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Check if a spec has any quality. + * @private + */ -const parse = __nccwpck_require__(16353) -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null +function isQuality(spec) { + return spec.q > 0; } -module.exports = valid /***/ }), -/***/ 62088: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 56008: +/***/ ((module) => { -// just pre-load all the stuff that index.js lazily exports -const internalRe = __nccwpck_require__(95471) -const constants = __nccwpck_require__(45101) -const SemVer = __nccwpck_require__(7163) -const identifiers = __nccwpck_require__(73348) -const parse = __nccwpck_require__(16353) -const valid = __nccwpck_require__(58780) -const clean = __nccwpck_require__(1799) -const inc = __nccwpck_require__(62338) -const diff = __nccwpck_require__(70711) -const major = __nccwpck_require__(68511) -const minor = __nccwpck_require__(32603) -const patch = __nccwpck_require__(48756) -const prerelease = __nccwpck_require__(15714) -const compare = __nccwpck_require__(78469) -const rcompare = __nccwpck_require__(32173) -const compareLoose = __nccwpck_require__(56874) -const compareBuild = __nccwpck_require__(37648) -const sort = __nccwpck_require__(29872) -const rsort = __nccwpck_require__(87192) -const gt = __nccwpck_require__(16599) -const lt = __nccwpck_require__(3872) -const eq = __nccwpck_require__(55082) -const neq = __nccwpck_require__(4974) -const gte = __nccwpck_require__(41236) -const lte = __nccwpck_require__(56717) -const cmp = __nccwpck_require__(28646) -const coerce = __nccwpck_require__(35385) -const Comparator = __nccwpck_require__(89379) -const Range = __nccwpck_require__(96782) -const satisfies = __nccwpck_require__(68011) -const toComparators = __nccwpck_require__(54750) -const maxSatisfying = __nccwpck_require__(73193) -const minSatisfying = __nccwpck_require__(68595) -const minVersion = __nccwpck_require__(51866) -const validRange = __nccwpck_require__(64737) -const outside = __nccwpck_require__(10280) -const gtr = __nccwpck_require__(12276) -const ltr = __nccwpck_require__(15213) -const intersects = __nccwpck_require__(23465) -const simplifyRange = __nccwpck_require__(82028) -const subset = __nccwpck_require__(61489) -module.exports = { - parse, - valid, - clean, - inc, - diff, - major, - minor, - patch, - prerelease, - compare, - rcompare, - compareLoose, - compareBuild, - sort, - rsort, - gt, - lt, - eq, - neq, - gte, - lte, - cmp, - coerce, - Comparator, - Range, - satisfies, - toComparators, - maxSatisfying, - minSatisfying, - minVersion, - validRange, - outside, - gtr, - ltr, - intersects, - simplifyRange, - subset, - SemVer, - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - RELEASE_TYPES: constants.RELEASE_TYPES, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, -} +"use strict"; +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 45101: -/***/ ((module) => { +/** + * Module exports. + * @public + */ -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -const SEMVER_SPEC_VERSION = '2.0.0' +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; -const MAX_LENGTH = 256 -const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || -/* istanbul ignore next */ 9007199254740991 +/** + * Module variables. + * @private + */ -// Max safe segment length for coercion. -const MAX_SAFE_COMPONENT_LENGTH = 16 +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; -// Max safe length for a build identifier. The max length minus 6 characters for -// the shortest version with a build 0.0.0+BUILD. -const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 +/** + * Parse the Accept-Language header. + * @private + */ -const RELEASE_TYPES = [ - 'major', - 'premajor', - 'minor', - 'preminor', - 'patch', - 'prepatch', - 'prerelease', -] +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); -module.exports = { - MAX_LENGTH, - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_SAFE_INTEGER, - RELEASE_TYPES, - SEMVER_SPEC_VERSION, - FLAG_INCLUDE_PRERELEASE: 0b001, - FLAG_LOOSE: 0b010, + for (var i = 0, j = 0; i < accepts.length; i++) { + var language = parseLanguage(accepts[i].trim(), i); + + if (language) { + accepts[j++] = language; + } + } + + // trim accepts + accepts.length = j; + + return accepts; } +/** + * Parse a language from the Accept-Language header. + * @private + */ -/***/ }), +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; -/***/ 1159: -/***/ ((module) => { + var prefix = match[1] + var suffix = match[2] + var full = prefix -const debug = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) -) ? (...args) => console.error('SEMVER', ...args) - : () => {} + if (suffix) full += "-" + suffix; -module.exports = debug + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var j = 0; j < params.length; j++) { + var p = params[j].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} -/***/ }), +/** + * Get the priority of a language. + * @private + */ -/***/ 73348: -/***/ ((module) => { +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; -const numeric = /^[0-9]+$/ -const compareIdentifiers = (a, b) => { - const anum = numeric.test(a) - const bnum = numeric.test(b) + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); - if (anum && bnum) { - a = +a - b = +b + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 + return priority; } -const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) +/** + * Get the specificity of the language. + * @private + */ -module.exports = { - compareIdentifiers, - rcompareIdentifiers, -} +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; -/***/ }), +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ -/***/ 61383: -/***/ ((module) => { +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); -class LRUCache { - constructor () { - this.max = 1000 - this.map = new Map() + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); } - get (key) { - const value = this.map.get(key) - if (value === undefined) { - return undefined - } else { - // Remove the key from the map and add it to the end - this.map.delete(key) - this.map.set(key, value) - return value - } - } + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); - delete (key) { - return this.map.delete(key) - } + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} - set (key, value) { - const deleted = this.delete(key) +/** + * Compare two specs. + * @private + */ - if (!deleted && value !== undefined) { - // If cache is full, delete the least recently used item - if (this.map.size >= this.max) { - const firstKey = this.map.keys().next().value - this.delete(firstKey) - } +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} - this.map.set(key, value) - } +/** + * Get full language string. + * @private + */ - return this - } +function getFullLanguage(spec) { + return spec.full; } -module.exports = LRUCache +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} /***/ }), -/***/ 70356: +/***/ 53672: /***/ ((module) => { -// parse out just the options we care about -const looseOption = Object.freeze({ loose: true }) -const emptyOpts = Object.freeze({ }) -const parseOptions = options => { - if (!options) { - return emptyOpts - } +"use strict"; +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - if (typeof options !== 'object') { - return looseOption - } - return options -} -module.exports = parseOptions +/** + * Module exports. + * @public + */ -/***/ }), +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; -/***/ 95471: -/***/ ((module, exports, __nccwpck_require__) => { +/** + * Module variables. + * @private + */ -const { - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_LENGTH, -} = __nccwpck_require__(45101) -const debug = __nccwpck_require__(1159) -exports = module.exports = {} +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; -// The actual regexps go on exports.re -const re = exports.re = [] -const safeRe = exports.safeRe = [] -const src = exports.src = [] -const safeSrc = exports.safeSrc = [] -const t = exports.t = {} -let R = 0 +/** + * Parse the Accept header. + * @private + */ -const LETTERDASHNUMBER = '[a-zA-Z0-9-]' +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); -// Replace some greedy regex tokens to prevent regex dos issues. These regex are -// used internally via the safeRe object since all inputs in this library get -// normalized first to trim and collapse all extra whitespace. The original -// regexes are exported for userland consumption and lower level usage. A -// future breaking change could export the safer regex only with a note that -// all input should have extra whitespace removed. -const safeRegexReplacements = [ - ['\\s', 1], - ['\\d', MAX_LENGTH], - [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], -] + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); -const makeSafeRegex = (value) => { - for (const [token, max] of safeRegexReplacements) { - value = value - .split(`${token}*`).join(`${token}{0,${max}}`) - .split(`${token}+`).join(`${token}{1,${max}}`) + if (mediaType) { + accepts[j++] = mediaType; + } } - return value -} -const createToken = (name, value, isGlobal) => { - const safe = makeSafeRegex(value) - const index = R++ - debug(name, index, value) - t[name] = index - src[index] = value - safeSrc[index] = safe - re[index] = new RegExp(value, isGlobal ? 'g' : undefined) - safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) + // trim accepts + accepts.length = j; + + return accepts; } -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. +/** + * Parse a media type from the Accept header. + * @private + */ -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; -createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') -createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); -createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; -// ## Main Version -// Three dot-separated numeric identifiers. + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.slice(1, -1) + : val; -createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`) + if (key === 'q') { + q = parseFloat(value); + break; + } -createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + // store parameter + params[key] = value; + } + } -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`) +/** + * Get the priority of a media type. + * @private + */ -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`) +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); -createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } -createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + return priority; +} -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +/** + * Get the specificity of the media type. + * @private + */ -createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + if (!p) { + return null; + } -createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } -createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`) + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} -createToken('FULL', `^${src[t.FULLPLAIN]}$`) +/** + * Get the preferred media types from an Accept header. + * @public + */ -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`) +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); -createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } -createToken('GTLT', '((?:<|>)?=?)') + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) -createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} -createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`) +/** + * Compare two specs. + * @private + */ -createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`) +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} -createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) -createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) +/** + * Get full type string. + * @private + */ -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -createToken('COERCEPLAIN', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) -createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) -createToken('COERCEFULL', src[t.COERCEPLAIN] + - `(?:${src[t.PRERELEASE]})?` + - `(?:${src[t.BUILD]})?` + - `(?:$|[^\\d])`) -createToken('COERCERTL', src[t.COERCE], true) -createToken('COERCERTLFULL', src[t.COERCEFULL], true) +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} -// Tilde ranges. -// Meaning is "reasonably at or greater than" -createToken('LONETILDE', '(?:~>?)') +/** + * Check if a spec has any quality. + * @private + */ -createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) -exports.tildeTrimReplace = '$1~' +function isQuality(spec) { + return spec.q > 0; +} -createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) -createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) +/** + * Count the number of quotes in a string. + * @private + */ -// Caret ranges. -// Meaning is "at least and backwards compatible with" -createToken('LONECARET', '(?:\\^)') +function quoteCount(string) { + var count = 0; + var index = 0; -createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) -exports.caretTrimReplace = '$1^' + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ -createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) -createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; -// A simple gt/lt/eq thing, or just "" to indicate "any version" -createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) -createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + if (index === -1) { + key = str; + } else { + key = str.slice(0, index); + val = str.slice(index + 1); + } -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) -exports.comparatorTrimReplace = '$1$2$3' + return [key, val]; +} -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`) +/** + * Split an Accept header into media types. + * @private + */ -createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`) +function splitMediaTypes(accept) { + var accepts = accept.split(','); -// Star ranges basically just allow anything at all. -createToken('STAR', '(<|>)?=?\\s*\\*') -// >=0.0.0 is like a star -createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') -createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + // trim accepts + accepts.length = j + 1; -/***/ }), + return accepts; +} -/***/ 12276: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Split a string of parameters. + * @private + */ -// Determine if version is greater than all the versions possible in the range. -const outside = __nccwpck_require__(10280) -const gtr = (version, range, options) => outside(version, range, '>', options) -module.exports = gtr +function splitParameters(str) { + var parameters = str.split(';'); + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } -/***/ }), + // trim parameters + parameters.length = j + 1; -/***/ 23465: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } -const Range = __nccwpck_require__(96782) -const intersects = (r1, r2, options) => { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2, options) + return parameters; } -module.exports = intersects /***/ }), -/***/ 15213: +/***/ 55560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const outside = __nccwpck_require__(10280) -// Determine if version is less than all the versions possible in the range -const ltr = (version, range, options) => outside(version, range, '<', options) -module.exports = ltr - +var wrappy = __nccwpck_require__(58264) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -/***/ }), +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -/***/ 73193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(96782) +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f } -module.exports = maxSatisfying /***/ }), -/***/ 68595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 26687: +/***/ ((module) => { -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(96782) -const minSatisfying = (versions, range, options) => { - let min = null - let minSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) +const META = Symbol('proc-log.meta') +module.exports = { + META: META, + output: { + LEVELS: [ + 'standard', + 'error', + 'buffer', + 'flush', + ], + KEYS: { + standard: 'standard', + error: 'error', + buffer: 'buffer', + flush: 'flush', + }, + standard: function (...args) { + return process.emit('output', 'standard', ...args) + }, + error: function (...args) { + return process.emit('output', 'error', ...args) + }, + buffer: function (...args) { + return process.emit('output', 'buffer', ...args) + }, + flush: function (...args) { + return process.emit('output', 'flush', ...args) + }, + }, + log: { + LEVELS: [ + 'notice', + 'error', + 'warn', + 'info', + 'verbose', + 'http', + 'silly', + 'timing', + 'pause', + 'resume', + ], + KEYS: { + notice: 'notice', + error: 'error', + warn: 'warn', + info: 'info', + verbose: 'verbose', + http: 'http', + silly: 'silly', + timing: 'timing', + pause: 'pause', + resume: 'resume', + }, + error: function (...args) { + return process.emit('log', 'error', ...args) + }, + notice: function (...args) { + return process.emit('log', 'notice', ...args) + }, + warn: function (...args) { + return process.emit('log', 'warn', ...args) + }, + info: function (...args) { + return process.emit('log', 'info', ...args) + }, + verbose: function (...args) { + return process.emit('log', 'verbose', ...args) + }, + http: function (...args) { + return process.emit('log', 'http', ...args) + }, + silly: function (...args) { + return process.emit('log', 'silly', ...args) + }, + timing: function (...args) { + return process.emit('log', 'timing', ...args) + }, + pause: function () { + return process.emit('log', 'pause') + }, + resume: function () { + return process.emit('log', 'resume') + }, + }, + time: { + LEVELS: [ + 'start', + 'end', + ], + KEYS: { + start: 'start', + end: 'end', + }, + start: function (name, fn) { + process.emit('time', 'start', name) + function end () { + return process.emit('time', 'end', name) } - } - }) - return min + if (typeof fn === 'function') { + const res = fn() + if (res && res.finally) { + return res.finally(end) + } + end() + return res + } + return end + }, + end: function (name) { + return process.emit('time', 'end', name) + }, + }, + input: { + LEVELS: [ + 'start', + 'end', + 'read', + ], + KEYS: { + start: 'start', + end: 'end', + read: 'read', + }, + start: function (fn) { + process.emit('input', 'start') + function end () { + return process.emit('input', 'end') + } + if (typeof fn === 'function') { + const res = fn() + if (res && res.finally) { + return res.finally(end) + } + end() + return res + } + return end + }, + end: function () { + return process.emit('input', 'end') + }, + read: function (...args) { + let resolve, reject + const promise = new Promise((_resolve, _reject) => { + resolve = _resolve + reject = _reject + }) + process.emit('input', 'read', resolve, reject, ...args) + return promise + }, + }, } -module.exports = minSatisfying /***/ }), -/***/ 51866: +/***/ 90390: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(96782) -const gt = __nccwpck_require__(16599) +"use strict"; -const minVersion = (range, loose) => { - range = new Range(range, loose) - let minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } +var errcode = __nccwpck_require__(14339); +var retry = __nccwpck_require__(5546); - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } +var hasOwn = Object.prototype.hasOwnProperty; - minver = null - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] +function isRetryError(err) { + return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried'); +} - let setMin = null - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt(compver, setMin)) { - setMin = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }) - if (setMin && (!minver || gt(minver, setMin))) { - minver = setMin +function promiseRetry(fn, options) { + var temp; + var operation; + + if (typeof fn === 'object' && typeof options === 'function') { + // Swap options and fn when using alternate signature (options, fn) + temp = options; + options = fn; + fn = temp; } - } - if (minver && range.test(minver)) { - return minver - } + operation = retry.operation(options); - return null + return new Promise(function (resolve, reject) { + operation.attempt(function (number) { + Promise.resolve() + .then(function () { + return fn(function (err) { + if (isRetryError(err)) { + err = err.retried; + } + + throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err }); + }, number); + }) + .then(resolve, function (err) { + if (isRetryError(err)) { + err = err.retried; + + if (operation.retry(err || new Error())) { + return; + } + } + + reject(err); + }); + }); + }); } -module.exports = minVersion + +module.exports = promiseRetry; /***/ }), -/***/ 10280: +/***/ 5546: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const SemVer = __nccwpck_require__(7163) -const Comparator = __nccwpck_require__(89379) -const { ANY } = Comparator -const Range = __nccwpck_require__(96782) -const satisfies = __nccwpck_require__(68011) -const gt = __nccwpck_require__(16599) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(56717) -const gte = __nccwpck_require__(41236) - -const outside = (version, range, hilo, options) => { - version = new SemVer(version, options) - range = new Range(range, options) +module.exports = __nccwpck_require__(67084); - let gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } +/***/ }), - // If it satisfies the range it is not outside - if (satisfies(version, range, options)) { - return false - } +/***/ 67084: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. +var RetryOperation = __nccwpck_require__(39538); - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] +exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && options.forever, + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); +}; - let high = null - let low = null +exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); } - return true -} -module.exports = outside + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); -/***/ }), + return timeouts; +}; -/***/ 82028: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; -// given a set of versions and a range, create a "simplified" range -// that includes the same versions that the original range does -// If the original range is shorter than the simplified one, return that. -const satisfies = __nccwpck_require__(68011) -const compare = __nccwpck_require__(78469) -module.exports = (versions, range, options) => { - const set = [] - let first = null - let prev = null - const v = versions.sort((a, b) => compare(a, b, options)) - for (const version of v) { - const included = satisfies(version, range, options) - if (included) { - prev = version - if (!first) { - first = version - } - } else { - if (prev) { - set.push([first, prev]) - } - prev = null - first = null - } - } - if (first) { - set.push([first, null]) + var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + + return timeout; +}; + +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; } - const ranges = [] - for (const [min, max] of set) { - if (min === max) { - ranges.push(min) - } else if (!max && min === v[0]) { - ranges.push('*') - } else if (!max) { - ranges.push(`>=${min}`) - } else if (min === v[0]) { - ranges.push(`<=${max}`) - } else { - ranges.push(`${min} - ${max}`) + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); + } } } - const simplified = ranges.join(' || ') - const original = typeof range.raw === 'string' ? range.raw : String(range) - return simplified.length < original.length ? simplified : range -} + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; -/***/ }), + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); -/***/ 61489: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); -const Range = __nccwpck_require__(96782) -const Comparator = __nccwpck_require__(89379) -const { ANY } = Comparator -const satisfies = __nccwpck_require__(68011) -const compare = __nccwpck_require__(78469) + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; -// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: -// - Every simple range `r1, r2, ...` is a null set, OR -// - Every simple range `r1, r2, ...` which is not a null set is a subset of -// some `R1, R2, ...` -// -// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: -// - If c is only the ANY comparator -// - If C is only the ANY comparator, return true -// - Else if in prerelease mode, return false -// - else replace c with `[>=0.0.0]` -// - If C is only the ANY comparator -// - if in prerelease mode, return true -// - else replace C with `[>=0.0.0]` -// - Let EQ be the set of = comparators in c -// - If EQ is more than one, return true (null set) -// - Let GT be the highest > or >= comparator in c -// - Let LT be the lowest < or <= comparator in c -// - If GT and LT, and GT.semver > LT.semver, return true (null set) -// - If any C is a = range, and GT or LT are set, return false -// - If EQ -// - If GT, and EQ does not satisfy GT, return true (null set) -// - If LT, and EQ does not satisfy LT, return true (null set) -// - If EQ satisfies every C, return true -// - Else return false -// - If GT -// - If GT.semver is lower than any > or >= comp in C, return false -// - If GT is >=, and GT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the GT.semver tuple, return false -// - If LT -// - If LT.semver is greater than any < or <= comp in C, return false -// - If LT is <=, and LT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the LT.semver tuple, return false -// - Else return true -const subset = (sub, dom, options = {}) => { - if (sub === dom) { - return true +/***/ }), + +/***/ 39538: +/***/ ((module) => { + +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; } - sub = new Range(sub, options) - dom = new Range(dom, options) - let sawNonNull = false + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options) - sawNonNull = sawNonNull || isSub !== null - if (isSub) { - continue OUTER - } - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) { - return false - } + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); } - return true } +module.exports = RetryOperation; -const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] -const minimumVersion = [new Comparator('>=0.0.0')] +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts; +} -const simpleSubset = (sub, dom, options) => { - if (sub === dom) { - return true +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); } - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) { - return true - } else if (options.includePrerelease) { - sub = minimumVersionWithPreRelease - } else { - sub = minimumVersion - } - } + this._timeouts = []; + this._cachedTimeouts = null; +}; - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) { - return true - } else { - dom = minimumVersion - } +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); } - const eqSet = new Set() - let gt, lt - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') { - gt = higherGT(gt, c, options) - } else if (c.operator === '<' || c.operator === '<=') { - lt = lowerLT(lt, c, options) - } else { - eqSet.add(c.semver) - } + if (!err) { + return false; } - - if (eqSet.size > 1) { - return null + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; } - let gtltComp - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options) - if (gtltComp > 0) { - return null - } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { - return null + this._errors.push(err); + + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(this._errors.length - 1, this._errors.length); + this._timeouts = this._cachedTimeouts.slice(0); + timeout = this._timeouts.shift(); + } else { + return false; } } - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) { - return null - } + var self = this; + var timer = setTimeout(function() { + self._attempts++; - if (lt && !satisfies(eq, String(lt), options)) { - return null - } + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); - for (const c of dom) { - if (!satisfies(eq, String(c), options)) { - return false + if (self._options.unref) { + self._timeout.unref(); } } - return true - } + self._fn(self._attempts); + }, timeout); - let higher, lower - let hasDomLT, hasDomGT - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false + if (this._options.unref) { + timer.unref(); } - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options) - if (higher === c && higher !== gt) { - return false - } - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { - return false - } - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options) - if (lower === c && lower !== lt) { - return false - } - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { - return false - } + return true; +}; + +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; } - if (!c.operator && (lt || gt) && gtltComp !== 0) { - return false + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; } } - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) { - return false + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); } - if (lt && hasDomGT && !gt && gtltComp !== 0) { - return false - } + this._operationStart = new Date().getTime(); - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) { - return false - } + this._fn(this._attempts); +}; - return true -} +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; -// >=1.2.3 is lower than >1.2.3 -const higherGT = (a, b, options) => { - if (!a) { - return b +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = RetryOperation.prototype.try; + +RetryOperation.prototype.errors = function() { + return this._errors; +}; + +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; + +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; } - const comp = compare(a.semver, b.semver, options) - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a -} -// <=1.2.3 is higher than <1.2.3 -const lowerLT = (a, b, options) => { - if (!a) { - return b + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } } - const comp = compare(a.semver, b.semver, options) - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a -} -module.exports = subset + return mainError; +}; /***/ }), -/***/ 54750: +/***/ 12803: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Range = __nccwpck_require__(96782) +"use strict"; +/* eslint-disable node/no-deprecated-api */ -// Mostly just for testing and legacy API reasons -const toComparators = (range, options) => - new Range(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) -module.exports = toComparators +var buffer = __nccwpck_require__(20181) +var Buffer = buffer.Buffer -/***/ }), +var safer = {} -/***/ 64737: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var key -const Range = __nccwpck_require__(96782) -const validRange = (range, options) => { +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it } } -module.exports = validRange + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer /***/ }), @@ -47467,6 +47229,244 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); __exportStar(__nccwpck_require__(57142), exports); //# sourceMappingURL=index.js.map +/***/ }), + +/***/ 19973: +/***/ ((__unused_webpack_module, exports) => { + +/* global window, exports, define */ + +!function() { + 'use strict' + + var re = { + not_string: /[^s]/, + not_bool: /[^t]/, + not_type: /[^T]/, + not_primitive: /[^v]/, + number: /[diefg]/, + numeric_arg: /[bcdiefguxX]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[+-]/ + } + + function sprintf(key) { + // `arguments` is not an array, but should be fine for this call + return sprintf_format(sprintf_parse(key), arguments) + } + + function vsprintf(fmt, argv) { + return sprintf.apply(null, [fmt].concat(argv || [])) + } + + function sprintf_format(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign + for (i = 0; i < tree_length; i++) { + if (typeof parse_tree[i] === 'string') { + output += parse_tree[i] + } + else if (typeof parse_tree[i] === 'object') { + ph = parse_tree[i] // convenience purposes only + if (ph.keys) { // keyword argument + arg = argv[cursor] + for (k = 0; k < ph.keys.length; k++) { + if (arg == undefined) { + throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1])) + } + arg = arg[ph.keys[k]] + } + } + else if (ph.param_no) { // positional argument (explicit) + arg = argv[ph.param_no] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) { + arg = arg() + } + + if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) { + throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) + } + + if (re.number.test(ph.type)) { + is_positive = arg >= 0 + } + + switch (ph.type) { + case 'b': + arg = parseInt(arg, 10).toString(2) + break + case 'c': + arg = String.fromCharCode(parseInt(arg, 10)) + break + case 'd': + case 'i': + arg = parseInt(arg, 10) + break + case 'j': + arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0) + break + case 'e': + arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential() + break + case 'f': + arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg) + break + case 'g': + arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg) + break + case 'o': + arg = (parseInt(arg, 10) >>> 0).toString(8) + break + case 's': + arg = String(arg) + arg = (ph.precision ? arg.substring(0, ph.precision) : arg) + break + case 't': + arg = String(!!arg) + arg = (ph.precision ? arg.substring(0, ph.precision) : arg) + break + case 'T': + arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() + arg = (ph.precision ? arg.substring(0, ph.precision) : arg) + break + case 'u': + arg = parseInt(arg, 10) >>> 0 + break + case 'v': + arg = arg.valueOf() + arg = (ph.precision ? arg.substring(0, ph.precision) : arg) + break + case 'x': + arg = (parseInt(arg, 10) >>> 0).toString(16) + break + case 'X': + arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() + break + } + if (re.json.test(ph.type)) { + output += arg + } + else { + if (re.number.test(ph.type) && (!is_positive || ph.sign)) { + sign = is_positive ? '+' : '-' + arg = arg.toString().replace(re.sign, '') + } + else { + sign = '' + } + pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ' + pad_length = ph.width - (sign + arg).length + pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' + output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) + } + } + } + return output + } + + var sprintf_cache = Object.create(null) + + function sprintf_parse(fmt) { + if (sprintf_cache[fmt]) { + return sprintf_cache[fmt] + } + + var _fmt = fmt, match, parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree.push(match[0]) + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree.push('%') + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + } + else { + throw new SyntaxError('[sprintf] failed to parse named argument key') + } + } + } + else { + throw new SyntaxError('[sprintf] failed to parse named argument key') + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') + } + + parse_tree.push( + { + placeholder: match[0], + param_no: match[1], + keys: match[2], + sign: match[3], + pad_char: match[4], + align: match[5], + width: match[6], + precision: match[7], + type: match[8] + } + ) + } + else { + throw new SyntaxError('[sprintf] unexpected placeholder') + } + _fmt = _fmt.substring(match[0].length) + } + return sprintf_cache[fmt] = parse_tree + } + + /** + * export to either browser or node.js + */ + /* eslint-disable quote-props */ + if (true) { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + if (typeof window !== 'undefined') { + window['sprintf'] = sprintf + window['vsprintf'] = vsprintf + + if (typeof define === 'function' && define['amd']) { + define(function() { + return { + 'sprintf': sprintf, + 'vsprintf': vsprintf + } + }) + } + } + /* eslint-enable quote-props */ +}(); // eslint-disable-line + + /***/ }), /***/ 68951: @@ -70768,7 +70768,10 @@ const createAttestation = async (subjects, predicate, opts) => { sigstore: opts.sigstoreInstance, token: opts.githubToken }); - const result = attestation; + const result = { + ...attestation, + attestationSubjects: subjects + }; if (subjects.length === 1 && opts.pushToRegistry) { const subject = subjects[0]; const credentials = (0, oci_1.getRegistryCredentials)(subject.name); @@ -70861,6 +70864,7 @@ const inputs = { pushToRegistry: core.getBooleanInput('push-to-registry'), showSummary: core.getBooleanInput('show-summary'), githubToken: core.getInput('github-token'), + singleSubjectAttestations: core.getBooleanInput('single-subject-attestations'), // undocumented -- not part of public interface privateSigning: ['true', 'True', 'TRUE', '1'].includes(core.getInput('private-signing')) }; @@ -70955,23 +70959,28 @@ async function run(inputs) { const predicate = (0, predicate_1.predicateFromInputs)(inputs); const outputPath = path_1.default.join(tempDir(), ATTESTATION_FILE_NAME); core.setOutput('bundle-path', outputPath); - const att = await (0, attest_1.createAttestation)(subjects, predicate, { + const opts = { sigstoreInstance, pushToRegistry: inputs.pushToRegistry, githubToken: inputs.githubToken - }); - logAttestation(subjects, att, sigstoreInstance); - // Write attestation bundle to output file - fs_1.default.writeFileSync(outputPath, JSON.stringify(att.bundle) + os_1.default.EOL, { - encoding: 'utf-8', - flag: 'a' - }); - if (att.attestationID) { - core.setOutput('attestation-id', att.attestationID); - core.setOutput('attestation-url', attestationURL(att.attestationID)); + }; + let atts; + if (inputs.singleSubjectAttestations) { + atts = await createSingleSubjectAttestations(subjects, predicate, opts); + } + else { + atts = await createMultiSubjectAttestation(subjects, predicate, opts); + } + for (const att of atts) { + logAttestation(att, sigstoreInstance); + // Write attestation bundle to output file + fs_1.default.writeFileSync(outputPath, JSON.stringify(att.bundle) + os_1.default.EOL, { + encoding: 'utf-8', + flag: 'a' + }); } if (inputs.showSummary) { - await logSummary(att); + await logSummary(atts); } } catch (err) { @@ -70988,8 +70997,26 @@ async function run(inputs) { process.removeListener('log', logHandler); } } +const createSingleSubjectAttestations = async (subjects, predicate, opts) => { + const atts = []; + // Generate one attestation for each subject + for (const subject of subjects) { + const att = await (0, attest_1.createAttestation)([subject], predicate, opts); + atts.push(att); + } + return atts; +}; +const createMultiSubjectAttestation = async (subjects, predicate, opts) => { + const att = await (0, attest_1.createAttestation)(subjects, predicate, opts); + if (att.attestationID) { + core.setOutput('attestation-id', att.attestationID); + core.setOutput('attestation-url', attestationURL(att.attestationID)); + } + return [att]; +}; // Log details about the attestation to the GitHub Actions run -const logAttestation = (subjects, attestation, sigstoreInstance) => { +const logAttestation = (attestation, sigstoreInstance) => { + const subjects = attestation.attestationSubjects; if (subjects.length === 1) { core.info(`Attestation created for ${subjects[0].name}@${(0, subject_1.formatSubjectDigest)(subjects[0])}`); } @@ -71014,12 +71041,24 @@ const logAttestation = (subjects, attestation, sigstoreInstance) => { } }; // Attach summary information to the GitHub Actions run -const logSummary = async (attestation) => { - const { attestationID } = attestation; - if (attestationID) { - const url = attestationURL(attestationID); - core.summary.addHeading('Attestation Created', 3); - core.summary.addList([`${url}`]); +const logSummary = async (attestations) => { + if (attestations.length > 0) { + core.summary.addHeading( + /* istanbul ignore next */ + attestations.length !== 1 + ? 'Attestations Created' + : 'Attestation Created', 3); + const listItems = []; + for (const attestation of attestations) { + if (attestation.attestationID) { + const url = attestationURL(attestation.attestationID); + for (const subject of attestation.attestationSubjects) { + const digest = (0, subject_1.formatSubjectDigest)(subject); + listItems.push(`${subject.name}@${digest}`); + } + } + } + core.summary.addList(listItems); await core.summary.write(); } }; @@ -73204,3065 +73243,3375 @@ const EncodedLookup = { } function encodedReplacer (match) { - return EncodedLookup[match] -} - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } - } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res -} - -module.exports = parseParams - - -/***/ }), - -/***/ 32638: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/** - * @module LRUCache - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LRUCache = void 0; -const perf = typeof performance === 'object' && - performance && - typeof performance.now === 'function' - ? performance - : Date; -const warned = new Set(); -/* c8 ignore start */ -const PROCESS = (typeof process === 'object' && !!process ? process : {}); -/* c8 ignore start */ -const emitWarning = (msg, type, code, fn) => { - typeof PROCESS.emitWarning === 'function' - ? PROCESS.emitWarning(msg, type, code, fn) - : console.error(`[${code}] ${type}: ${msg}`); -}; -let AC = globalThis.AbortController; -let AS = globalThis.AbortSignal; -/* c8 ignore start */ -if (typeof AC === 'undefined') { - //@ts-ignore - AS = class AbortSignal { - onabort; - _onabort = []; - reason; - aborted = false; - addEventListener(_, fn) { - this._onabort.push(fn); - } - }; - //@ts-ignore - AC = class AbortController { - constructor() { - warnACPolyfill(); - } - signal = new AS(); - abort(reason) { - if (this.signal.aborted) - return; - //@ts-ignore - this.signal.reason = reason; - //@ts-ignore - this.signal.aborted = true; - //@ts-ignore - for (const fn of this.signal._onabort) { - fn(reason); - } - this.signal.onabort?.(reason); - } - }; - let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'; - const warnACPolyfill = () => { - if (!printACPolyfillWarning) - return; - printACPolyfillWarning = false; - emitWarning('AbortController is not defined. If using lru-cache in ' + - 'node 14, load an AbortController polyfill from the ' + - '`node-abort-controller` package. A minimal polyfill is ' + - 'provided for use by LRUCache.fetch(), but it should not be ' + - 'relied upon in other contexts (eg, passing it to other APIs that ' + - 'use AbortController/AbortSignal might have undesirable effects). ' + - 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill); - }; -} -/* c8 ignore stop */ -const shouldWarn = (code) => !warned.has(code); -const TYPE = Symbol('type'); -const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n); -/* c8 ignore start */ -// This is a little bit ridiculous, tbh. -// The maximum array length is 2^32-1 or thereabouts on most JS impls. -// And well before that point, you're caching the entire world, I mean, -// that's ~32GB of just integers for the next/prev links, plus whatever -// else to hold that many keys and values. Just filling the memory with -// zeroes at init time is brutal when you get that big. -// But why not be complete? -// Maybe in the future, these limits will have expanded. -const getUintArray = (max) => !isPosInt(max) - ? null - : 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; -/* c8 ignore stop */ -class ZeroArray extends Array { - constructor(size) { - super(size); - this.fill(0); - } + return EncodedLookup[match] } -class Stack { - heap; - length; - // private constructor - static #constructing = false; - static create(max) { - const HeapCls = getUintArray(max); - if (!HeapCls) - return []; - Stack.#constructing = true; - const s = new Stack(max, HeapCls); - Stack.#constructing = false; - return s; - } - constructor(max, HeapCls) { - /* c8 ignore start */ - if (!Stack.#constructing) { - throw new TypeError('instantiate Stack using Stack.create(n)'); + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') } - /* c8 ignore stop */ - this.heap = new HeapCls(max); - this.length = 0; - } - push(n) { - this.heap[this.length++] = n; - } - pop() { - return this.heap[--this.length]; + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res } + +module.exports = parseParams + + +/***/ }), + +/***/ 81017: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Glob = void 0; +const minimatch_1 = __nccwpck_require__(45613); +const node_url_1 = __nccwpck_require__(73136); +const path_scurry_1 = __nccwpck_require__(16577); +const pattern_js_1 = __nccwpck_require__(4041); +const walker_js_1 = __nccwpck_require__(95049); +// if no process global, just call it linux. +// so we default to case-sensitive, / separators +const defaultPlatform = (typeof process === 'object' && + process && + typeof process.platform === 'string') ? + process.platform + : 'linux'; /** - * Default export, the thing you're using this module to get. - * - * The `K` and `V` types define the key and value types, respectively. The - * optional `FC` type defines the type of the `context` object passed to - * `cache.fetch()` and `cache.memo()`. - * - * Keys and values **must not** be `null` or `undefined`. - * - * All properties from the options object (with the exception of `max`, - * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are - * added as normal public members. (The listed options are read-only getters.) - * - * Changing any of these will alter the defaults for subsequent method calls. + * An object that can perform glob pattern traversals. */ -class LRUCache { - // options that cannot be changed without disaster - #max; - #maxSize; - #dispose; - #disposeAfter; - #fetchMethod; - #memoMethod; - /** - * {@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; +class Glob { + absolute; + cwd; + root; + dot; + dotRelative; + follow; + ignore; + magicalBraces; + mark; + matchBase; + maxDepth; + nobrace; + nocase; + nodir; + noext; + noglobstar; + pattern; + platform; + realpath; + scurry; + stat; + signal; + windowsPathsNoEscape; + withFileTypes; + includeChildMatches; /** - * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} + * The options provided to the constructor. */ - allowStaleOnFetchRejection; + opts; /** - * {@link LRUCache.OptionsBase.ignoreFetchAbort} + * An array of parsed immutable {@link Pattern} objects. */ - ignoreFetchAbort; - // computed properties - #size; - #calculatedSize; - #keyMap; - #keyList; - #valList; - #next; - #prev; - #head; - #tail; - #free; - #disposed; - #sizes; - #starts; - #ttls; - #hasDispose; - #hasFetchMethod; - #hasDisposeAfter; + patterns; /** - * 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. + * All options are stored as properties on the `Glob` object. * - * These fields are private for a reason! + * See {@link GlobOptions} for full options descriptions. * - * @internal + * Note that a previous `Glob` object can be passed as the + * `GlobOptions` to another `Glob` instantiation to re-use settings + * and caches with a new pattern. + * + * Traversal functions can be called multiple times to run the walk + * again. */ - 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), + constructor(pattern, opts) { + /* c8 ignore start */ + if (!opts) + throw new TypeError('glob options required'); + /* c8 ignore stop */ + this.withFileTypes = !!opts.withFileTypes; + this.signal = opts.signal; + this.follow = !!opts.follow; + this.dot = !!opts.dot; + this.dotRelative = !!opts.dotRelative; + this.nodir = !!opts.nodir; + this.mark = !!opts.mark; + if (!opts.cwd) { + this.cwd = ''; + } + else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { + opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd); + } + this.cwd = opts.cwd || ''; + this.root = opts.root; + this.magicalBraces = !!opts.magicalBraces; + this.nobrace = !!opts.nobrace; + this.noext = !!opts.noext; + this.realpath = !!opts.realpath; + this.absolute = opts.absolute; + this.includeChildMatches = opts.includeChildMatches !== false; + this.noglobstar = !!opts.noglobstar; + this.matchBase = !!opts.matchBase; + this.maxDepth = + typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; + this.stat = !!opts.stat; + this.ignore = opts.ignore; + if (this.withFileTypes && this.absolute !== undefined) { + throw new Error('cannot set absolute and withFileTypes:true'); + } + if (typeof pattern === 'string') { + pattern = [pattern]; + } + this.windowsPathsNoEscape = + !!opts.windowsPathsNoEscape || + opts.allowWindowsEscape === + false; + if (this.windowsPathsNoEscape) { + pattern = pattern.map(p => p.replace(/\\/g, '/')); + } + if (this.matchBase) { + if (opts.noglobstar) { + throw new TypeError('base matching requires globstar'); + } + pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); + } + this.pattern = pattern; + this.platform = opts.platform || defaultPlatform; + this.opts = { ...opts, platform: this.platform }; + if (opts.scurry) { + this.scurry = opts.scurry; + if (opts.nocase !== undefined && + opts.nocase !== opts.scurry.nocase) { + throw new Error('nocase option contradicts provided scurry option'); + } + } + else { + const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32 + : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin + : opts.platform ? path_scurry_1.PathScurryPosix + : path_scurry_1.PathScurry; + this.scurry = new Scurry(this.cwd, { + nocase: opts.nocase, + fs: opts.fs, + }); + } + this.nocase = this.scurry.nocase; + // If you do nocase:true on a case-sensitive file system, then + // we need to use regexps instead of strings for non-magic + // path portions, because statting `aBc` won't return results + // for the file `AbC` for example. + const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; + const mmo = { + // default nocase based on platform + ...opts, + dot: this.dot, + matchBase: this.matchBase, + nobrace: this.nobrace, + nocase: this.nocase, + nocaseMagicOnly, + nocomment: true, + noext: this.noext, + nonegate: true, + optimizationLevel: 2, + platform: this.platform, + windowsPathsNoEscape: this.windowsPathsNoEscape, + debug: !!this.opts.debug, }; + const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo)); + const [matchSet, globParts] = mms.reduce((set, m) => { + set[0].push(...m.set); + set[1].push(...m.globParts); + return set; + }, [[], []]); + this.patterns = matchSet.map((set, i) => { + const g = globParts[i]; + /* c8 ignore start */ + if (!g) + throw new Error('invalid pattern object'); + /* c8 ignore stop */ + return new pattern_js_1.Pattern(set, g, 0, this.platform); + }); } - // Protected read-only members - /** - * {@link LRUCache.OptionsBase.max} (read-only) - */ - get max() { - return this.#max; + async walk() { + // Walkers always return array of Path objects, so we just have to + // coerce them into the right shape. It will have already called + // realpath() if the option was set to do so, so we know that's cached. + // start out knowing the cwd, at least + return [ + ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walk()), + ]; } - /** - * {@link LRUCache.OptionsBase.maxSize} (read-only) - */ - get maxSize() { - return this.#maxSize; + walkSync() { + return [ + ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).walkSync(), + ]; } - /** - * The total computed size of items in the cache (read-only) - */ - get calculatedSize() { - return this.#calculatedSize; + stream() { + return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).stream(); + } + streamSync() { + return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { + ...this.opts, + maxDepth: this.maxDepth !== Infinity ? + this.maxDepth + this.scurry.cwd.depth() + : Infinity, + platform: this.platform, + nocase: this.nocase, + includeChildMatches: this.includeChildMatches, + }).streamSync(); } /** - * The number of items stored in the cache (read-only) + * Default sync iteration function. Returns a Generator that + * iterates over the results. */ - get size() { - return this.#size; + iterateSync() { + return this.streamSync()[Symbol.iterator](); + } + [Symbol.iterator]() { + return this.iterateSync(); } /** - * {@link LRUCache.OptionsBase.fetchMethod} (read-only) + * Default async iteration function. Returns an AsyncGenerator that + * iterates over the results. */ - get fetchMethod() { - return this.#fetchMethod; + iterate() { + return this.stream()[Symbol.asyncIterator](); } - get memoMethod() { - return this.#memoMethod; + [Symbol.asyncIterator]() { + return this.iterate(); + } +} +exports.Glob = Glob; +//# sourceMappingURL=glob.js.map + +/***/ }), + +/***/ 66889: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.hasMagic = void 0; +const minimatch_1 = __nccwpck_require__(45613); +/** + * Return true if the patterns provided contain any magic glob characters, + * given the options provided. + * + * Brace expansion is not considered "magic" unless the `magicalBraces` option + * is set, as brace expansion just turns one string into an array of strings. + * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and + * `'xby'` both do not contain any magic glob characters, and it's treated the + * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` + * is in the options, brace expansion _is_ treated as a pattern having magic. + */ +const hasMagic = (pattern, options = {}) => { + if (!Array.isArray(pattern)) { + pattern = [pattern]; } - /** - * {@link LRUCache.OptionsBase.dispose} (read-only) - */ - get dispose() { - return this.#dispose; + for (const p of pattern) { + if (new minimatch_1.Minimatch(p, options).hasMagic()) + return true; } - /** - * {@link LRUCache.OptionsBase.disposeAfter} (read-only) - */ - get disposeAfter() { - return this.#disposeAfter; + return false; +}; +exports.hasMagic = hasMagic; +//# sourceMappingURL=has-magic.js.map + +/***/ }), + +/***/ 4833: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// give it a pattern, and it'll be able to tell you if +// a given path should be ignored. +// Ignoring a path ignores its children if the pattern ends in /** +// Ignores are always parsed in dot:true mode +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Ignore = void 0; +const minimatch_1 = __nccwpck_require__(45613); +const pattern_js_1 = __nccwpck_require__(4041); +const defaultPlatform = (typeof process === 'object' && + process && + typeof process.platform === 'string') ? + process.platform + : 'linux'; +/** + * Class used to process ignored patterns + */ +class Ignore { + relative; + relativeChildren; + absolute; + absoluteChildren; + platform; + mmopts; + constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { + this.relative = []; + this.absolute = []; + this.relativeChildren = []; + this.absoluteChildren = []; + this.platform = platform; + this.mmopts = { + dot: true, + nobrace, + nocase, + noext, + noglobstar, + optimizationLevel: 2, + platform, + nocomment: true, + nonegate: true, + }; + for (const ign of ignored) + this.add(ign); } - constructor(options) { - const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options; - if (max !== 0 && !isPosInt(max)) { - throw new TypeError('max option must be a nonnegative integer'); - } - const UintArray = max ? getUintArray(max) : Array; - if (!UintArray) { - throw new Error('invalid max value: ' + max); - } - this.#max = max; - this.#maxSize = maxSize; - this.maxEntrySize = maxEntrySize || this.#maxSize; - this.sizeCalculation = sizeCalculation; - if (this.sizeCalculation) { - if (!this.#maxSize && !this.maxEntrySize) { - throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize'); + add(ign) { + // this is a little weird, but it gives us a clean set of optimized + // minimatch matchers, without getting tripped up if one of them + // ends in /** inside a brace section, and it's only inefficient at + // the start of the walk, not along it. + // It'd be nice if the Pattern class just had a .test() method, but + // handling globstars is a bit of a pita, and that code already lives + // in minimatch anyway. + // Another way would be if maybe Minimatch could take its set/globParts + // as an option, and then we could at least just use Pattern to test + // for absolute-ness. + // Yet another way, Minimatch could take an array of glob strings, and + // a cwd option, and do the right thing. + const mm = new minimatch_1.Minimatch(ign, this.mmopts); + for (let i = 0; i < mm.set.length; i++) { + const parsed = mm.set[i]; + const globParts = mm.globParts[i]; + /* c8 ignore start */ + if (!parsed || !globParts) { + throw new Error('invalid pattern object'); } - if (typeof this.sizeCalculation !== 'function') { - throw new TypeError('sizeCalculation set to non-function'); + // strip off leading ./ portions + // https://github.com/isaacs/node-glob/issues/570 + while (parsed[0] === '.' && globParts[0] === '.') { + parsed.shift(); + globParts.shift(); + } + /* c8 ignore stop */ + const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform); + const m = new minimatch_1.Minimatch(p.globString(), this.mmopts); + const children = globParts[globParts.length - 1] === '**'; + const absolute = p.isAbsolute(); + if (absolute) + this.absolute.push(m); + else + this.relative.push(m); + if (children) { + if (absolute) + this.absoluteChildren.push(m); + else + this.relativeChildren.push(m); } } - if (memoMethod !== undefined && - typeof memoMethod !== 'function') { - throw new TypeError('memoMethod must be a function if defined'); - } - this.#memoMethod = memoMethod; - if (fetchMethod !== undefined && - typeof fetchMethod !== 'function') { - throw new TypeError('fetchMethod must be a function if specified'); - } - this.#fetchMethod = fetchMethod; - this.#hasFetchMethod = !!fetchMethod; - this.#keyMap = new Map(); - this.#keyList = new Array(max).fill(undefined); - this.#valList = new Array(max).fill(undefined); - 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; - if (typeof dispose === 'function') { - this.#dispose = dispose; + } + ignored(p) { + const fullpath = p.fullpath(); + const fullpaths = `${fullpath}/`; + const relative = p.relative() || '.'; + const relatives = `${relative}/`; + for (const m of this.relative) { + if (m.match(relative) || m.match(relatives)) + return true; } - if (typeof disposeAfter === 'function') { - this.#disposeAfter = disposeAfter; - this.#disposed = []; + for (const m of this.absolute) { + if (m.match(fullpath) || m.match(fullpaths)) + return true; } - else { - this.#disposeAfter = undefined; - this.#disposed = undefined; + return false; + } + childrenIgnored(p) { + const fullpath = p.fullpath() + '/'; + const relative = (p.relative() || '.') + '/'; + for (const m of this.relativeChildren) { + if (m.match(relative)) + return true; } - 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; - // NB: maxEntrySize is set to maxSize if it's set - if (this.maxEntrySize !== 0) { - if (this.#maxSize !== 0) { - if (!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(); + for (const m of this.absoluteChildren) { + if (m.match(fullpath)) + return true; } - 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; - if (this.ttl) { - if (!isPosInt(this.ttl)) { - throw new TypeError('ttl must be a positive integer if specified'); - } - this.#initializeTTLTracking(); + return false; + } +} +exports.Ignore = Ignore; +//# sourceMappingURL=ignore.js.map + +/***/ }), + +/***/ 67471: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0; +exports.globStreamSync = globStreamSync; +exports.globStream = globStream; +exports.globSync = globSync; +exports.globIterateSync = globIterateSync; +exports.globIterate = globIterate; +const minimatch_1 = __nccwpck_require__(45613); +const glob_js_1 = __nccwpck_require__(81017); +const has_magic_js_1 = __nccwpck_require__(66889); +var minimatch_2 = __nccwpck_require__(45613); +Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return minimatch_2.escape; } })); +Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return minimatch_2.unescape; } })); +var glob_js_2 = __nccwpck_require__(81017); +Object.defineProperty(exports, "Glob", ({ enumerable: true, get: function () { return glob_js_2.Glob; } })); +var has_magic_js_2 = __nccwpck_require__(66889); +Object.defineProperty(exports, "hasMagic", ({ enumerable: true, get: function () { return has_magic_js_2.hasMagic; } })); +var ignore_js_1 = __nccwpck_require__(4833); +Object.defineProperty(exports, "Ignore", ({ enumerable: true, get: function () { return ignore_js_1.Ignore; } })); +function globStreamSync(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).streamSync(); +} +function globStream(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).stream(); +} +function globSync(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).walkSync(); +} +async function glob_(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).walk(); +} +function globIterateSync(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).iterateSync(); +} +function globIterate(pattern, options = {}) { + return new glob_js_1.Glob(pattern, options).iterate(); +} +// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc +exports.streamSync = globStreamSync; +exports.stream = Object.assign(globStream, { sync: globStreamSync }); +exports.iterateSync = globIterateSync; +exports.iterate = Object.assign(globIterate, { + sync: globIterateSync, +}); +exports.sync = Object.assign(globSync, { + stream: globStreamSync, + iterate: globIterateSync, +}); +exports.glob = Object.assign(glob_, { + glob: glob_, + globSync, + sync: exports.sync, + globStream, + stream: exports.stream, + globStreamSync, + streamSync: exports.streamSync, + globIterate, + iterate: exports.iterate, + globIterateSync, + iterateSync: exports.iterateSync, + Glob: glob_js_1.Glob, + hasMagic: has_magic_js_1.hasMagic, + escape: minimatch_1.escape, + unescape: minimatch_1.unescape, +}); +exports.glob.glob = exports.glob; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4041: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// this is just a very light wrapper around 2 arrays with an offset index +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Pattern = void 0; +const minimatch_1 = __nccwpck_require__(45613); +const isPatternList = (pl) => pl.length >= 1; +const isGlobList = (gl) => gl.length >= 1; +/** + * An immutable-ish view on an array of glob parts and their parsed + * results + */ +class Pattern { + #patternList; + #globList; + #index; + length; + #platform; + #rest; + #globString; + #isDrive; + #isUNC; + #isAbsolute; + #followGlobstar = true; + constructor(patternList, globList, index, platform) { + if (!isPatternList(patternList)) { + throw new TypeError('empty pattern list'); } - // do not allow completely unbounded caches - if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) { - throw new TypeError('At least one of max, maxSize, or ttl is required'); + if (!isGlobList(globList)) { + throw new TypeError('empty glob list'); } - if (!this.ttlAutopurge && !this.#max && !this.#maxSize) { - const code = 'LRU_CACHE_UNBOUNDED'; - if (shouldWarn(code)) { - warned.add(code); - const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' + - 'result in unbounded memory consumption.'; - emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache); - } + if (globList.length !== patternList.length) { + throw new TypeError('mismatched pattern list and glob list lengths'); } - } - /** - * Return the number of ms left in the item's TTL. If item is not in cache, - * returns `0`. Returns `Infinity` if item is in cache without a defined TTL. - */ - getRemainingTTL(key) { - return this.#keyMap.has(key) ? Infinity : 0; - } - #initializeTTLTracking() { - const ttls = new ZeroArray(this.#max); - const starts = new ZeroArray(this.#max); - this.#ttls = ttls; - this.#starts = starts; - this.#setItemTTL = (index, ttl, start = perf.now()) => { - starts[index] = ttl !== 0 ? start : 0; - ttls[index] = ttl; - if (ttl !== 0 && this.ttlAutopurge) { - const t = setTimeout(() => { - if (this.#isStale(index)) { - this.#delete(this.#keyList[index], 'expire'); - } - }, ttl + 1); - // unref() not supported on all platforms - /* c8 ignore start */ - if (t.unref) { - t.unref(); - } - /* c8 ignore stop */ - } - }; - this.#updateItemAge = index => { - starts[index] = ttls[index] !== 0 ? perf.now() : 0; - }; - this.#statusTTL = (status, index) => { - if (ttls[index]) { - const ttl = ttls[index]; - const start = starts[index]; - /* c8 ignore next */ - if (!ttl || !start) - return; - status.ttl = ttl; - status.start = start; - status.now = cachedNow || getNow(); - const age = status.now - start; - status.remainingTTL = ttl - age; - } - }; - // debounce calls to perf.now() to 1s so we're not hitting - // that costly call repeatedly. - let cachedNow = 0; - const getNow = () => { - const n = perf.now(); - if (this.ttlResolution > 0) { - cachedNow = n; - const t = setTimeout(() => (cachedNow = 0), this.ttlResolution); - // not available on all platforms - /* c8 ignore start */ - if (t.unref) { - t.unref(); - } - /* c8 ignore stop */ - } - return n; - }; - this.getRemainingTTL = key => { - const index = this.#keyMap.get(key); - if (index === undefined) { - return 0; - } - const ttl = ttls[index]; - const start = starts[index]; - if (!ttl || !start) { - return Infinity; - } - const age = (cachedNow || getNow()) - start; - return ttl - age; - }; - this.#isStale = index => { - const s = starts[index]; - const t = ttls[index]; - return !!t && !!s && (cachedNow || getNow()) - s > t; - }; - } - // conditionally set private methods related to TTL - #updateItemAge = () => { }; - #statusTTL = () => { }; - #setItemTTL = () => { }; - /* c8 ignore stop */ - #isStale = () => false; - #initializeSizeTracking() { - const 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) => { - // provisionally accept background fetches. - // actual value size will be checked when they return. - if (this.#isBackgroundFetch(v)) { - return 0; - } - if (!isPosInt(size)) { - if (sizeCalculation) { - if (typeof sizeCalculation !== 'function') { - throw new TypeError('sizeCalculation must be a function'); - } - size = sizeCalculation(v, k); - if (!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) => { - sizes[index] = size; - if (this.#maxSize) { - const maxSize = this.#maxSize - sizes[index]; - while (this.#calculatedSize > maxSize) { - this.#evict(true); - } - } - this.#calculatedSize += sizes[index]; - if (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'); + this.length = patternList.length; + if (index < 0 || index >= this.length) { + throw new TypeError('index out of range'); } - return 0; - }; - *#indexes({ allowStale = this.allowStale } = {}) { - if (this.#size) { - for (let i = this.#tail; true;) { - if (!this.#isValidIndex(i)) { - break; - } - if (allowStale || !this.#isStale(i)) { - yield i; - } - if (i === this.#head) { - break; - } - else { - i = this.#prev[i]; + this.#patternList = patternList; + this.#globList = globList; + this.#index = index; + this.#platform = platform; + // normalize root entries of absolute patterns on initial creation. + if (this.#index === 0) { + // c: => ['c:/'] + // C:/ => ['C:/'] + // C:/x => ['C:/', 'x'] + // //host/share => ['//host/share/'] + // //host/share/ => ['//host/share/'] + // //host/share/x => ['//host/share/', 'x'] + // /etc => ['/', 'etc'] + // / => ['/'] + if (this.isUNC()) { + // '' / '' / 'host' / 'share' + const [p0, p1, p2, p3, ...prest] = this.#patternList; + const [g0, g1, g2, g3, ...grest] = this.#globList; + if (prest[0] === '') { + // ends in / + prest.shift(); + grest.shift(); } + const p = [p0, p1, p2, p3, ''].join('/'); + const g = [g0, g1, g2, g3, ''].join('/'); + this.#patternList = [p, ...prest]; + this.#globList = [g, ...grest]; + this.length = this.#patternList.length; } - } - } - *#rindexes({ allowStale = this.allowStale } = {}) { - if (this.#size) { - for (let i = this.#head; true;) { - if (!this.#isValidIndex(i)) { - break; - } - if (allowStale || !this.#isStale(i)) { - yield i; - } - if (i === this.#tail) { - break; - } - else { - i = this.#next[i]; + else if (this.isDrive() || this.isAbsolute()) { + const [p1, ...prest] = this.#patternList; + const [g1, ...grest] = this.#globList; + if (prest[0] === '') { + // ends in / + prest.shift(); + grest.shift(); } + const p = p1 + '/'; + const g = g1 + '/'; + this.#patternList = [p, ...prest]; + this.#globList = [g, ...grest]; + this.length = this.#patternList.length; } } } - #isValidIndex(index) { - return (index !== undefined && - this.#keyMap.get(this.#keyList[index]) === index); + /** + * The first entry in the parsed list of patterns + */ + pattern() { + return this.#patternList[this.#index]; } /** - * Return a generator yielding `[key, value]` pairs, - * in order from most recently used to least recently used. + * true of if pattern() returns a string */ - *entries() { - for (const i of this.#indexes()) { - if (this.#valList[i] !== undefined && - this.#keyList[i] !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { - yield [this.#keyList[i], this.#valList[i]]; - } - } + isString() { + return typeof this.#patternList[this.#index] === 'string'; } /** - * Inverse order version of {@link LRUCache.entries} - * - * Return a generator yielding `[key, value]` pairs, - * in order from least recently used to most recently used. + * true of if pattern() returns GLOBSTAR */ - *rentries() { - for (const i of this.#rindexes()) { - if (this.#valList[i] !== undefined && - this.#keyList[i] !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { - yield [this.#keyList[i], this.#valList[i]]; - } - } + isGlobstar() { + return this.#patternList[this.#index] === minimatch_1.GLOBSTAR; } /** - * Return a generator yielding the keys in the cache, - * in order from most recently used to least recently used. + * true if pattern() returns a regexp */ - *keys() { - for (const i of this.#indexes()) { - const k = this.#keyList[i]; - if (k !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { - yield k; - } - } + isRegExp() { + return this.#patternList[this.#index] instanceof RegExp; } /** - * 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. + * The /-joined set of glob parts that make up this pattern */ - *rkeys() { - for (const i of this.#rindexes()) { - const k = this.#keyList[i]; - if (k !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { - yield k; - } - } + globString() { + return (this.#globString = + this.#globString || + (this.#index === 0 ? + this.isAbsolute() ? + this.#globList[0] + this.#globList.slice(1).join('/') + : this.#globList.join('/') + : this.#globList.slice(this.#index).join('/'))); } /** - * Return a generator yielding the values in the cache, - * in order from most recently used to least recently used. + * true if there are more pattern parts after this one */ - *values() { - for (const i of this.#indexes()) { - const v = this.#valList[i]; - if (v !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { - yield this.#valList[i]; - } - } + hasMore() { + return this.length > this.#index + 1; } /** - * 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. + * The rest of the pattern after this part, or null if this is the end */ - *rvalues() { - for (const i of this.#rindexes()) { - const v = this.#valList[i]; - if (v !== undefined && - !this.#isBackgroundFetch(this.#valList[i])) { - yield this.#valList[i]; - } - } + rest() { + if (this.#rest !== undefined) + return this.#rest; + if (!this.hasMore()) + return (this.#rest = null); + this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); + this.#rest.#isAbsolute = this.#isAbsolute; + this.#rest.#isUNC = this.#isUNC; + this.#rest.#isDrive = this.#isDrive; + return this.#rest; } /** - * Iterating over the cache itself yields the same results as - * {@link LRUCache.entries} + * true if the pattern represents a //unc/path/ on windows */ - [Symbol.iterator]() { - return this.entries(); + isUNC() { + const pl = this.#patternList; + return this.#isUNC !== undefined ? + this.#isUNC + : (this.#isUNC = + this.#platform === 'win32' && + this.#index === 0 && + pl[0] === '' && + pl[1] === '' && + typeof pl[2] === 'string' && + !!pl[2] && + typeof pl[3] === 'string' && + !!pl[3]); } + // pattern like C:/... + // split = ['C:', ...] + // XXX: would be nice to handle patterns like `c:*` to test the cwd + // in c: for *, but I don't know of a way to even figure out what that + // cwd is without actually chdir'ing into it? /** - * A String value that is used in the creation of the default string - * description of an object. Called by the built-in method - * `Object.prototype.toString`. + * True if the pattern starts with a drive letter on Windows */ - [Symbol.toStringTag] = 'LRUCache'; + isDrive() { + const pl = this.#patternList; + return this.#isDrive !== undefined ? + this.#isDrive + : (this.#isDrive = + this.#platform === 'win32' && + this.#index === 0 && + this.length > 1 && + typeof pl[0] === 'string' && + /^[a-z]:$/i.test(pl[0])); + } + // pattern = '/' or '/...' or '/x/...' + // split = ['', ''] or ['', ...] or ['', 'x', ...] + // Drive and UNC both considered absolute on windows /** - * 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)`. + * True if the pattern is rooted on an absolute path */ - find(fn, getOptions = {}) { - for (const i of this.#indexes()) { - const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; - if (value === undefined) + isAbsolute() { + const pl = this.#patternList; + return this.#isAbsolute !== undefined ? + this.#isAbsolute + : (this.#isAbsolute = + (pl[0] === '' && pl.length > 1) || + this.isDrive() || + this.isUNC()); + } + /** + * consume the root of the pattern, and return it + */ + root() { + const p = this.#patternList[0]; + return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ? + p + : ''; + } + /** + * Check to see if the current globstar pattern is allowed to follow + * a symbolic link. + */ + checkFollowGlobstar() { + return !(this.#index === 0 || + !this.isGlobstar() || + !this.#followGlobstar); + } + /** + * Mark that the current globstar pattern is following a symbolic link + */ + markFollowGlobstar() { + if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) + return false; + this.#followGlobstar = false; + return true; + } +} +exports.Pattern = Pattern; +//# sourceMappingURL=pattern.js.map + +/***/ }), + +/***/ 48095: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// synchronous utility for filtering entries and calculating subwalks +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0; +const minimatch_1 = __nccwpck_require__(45613); +/** + * A cache of which patterns have been processed for a given Path + */ +class HasWalkedCache { + store; + constructor(store = new Map()) { + this.store = store; + } + copy() { + return new HasWalkedCache(new Map(this.store)); + } + hasWalked(target, pattern) { + return this.store.get(target.fullpath())?.has(pattern.globString()); + } + storeWalked(target, pattern) { + const fullpath = target.fullpath(); + const cached = this.store.get(fullpath); + if (cached) + cached.add(pattern.globString()); + else + this.store.set(fullpath, new Set([pattern.globString()])); + } +} +exports.HasWalkedCache = HasWalkedCache; +/** + * A record of which paths have been matched in a given walk step, + * and whether they only are considered a match if they are a directory, + * and whether their absolute or relative path should be returned. + */ +class MatchRecord { + store = new Map(); + add(target, absolute, ifDir) { + const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); + const current = this.store.get(target); + this.store.set(target, current === undefined ? n : n & current); + } + // match, absolute, ifdir + entries() { + return [...this.store.entries()].map(([path, n]) => [ + path, + !!(n & 2), + !!(n & 1), + ]); + } +} +exports.MatchRecord = MatchRecord; +/** + * A collection of patterns that must be processed in a subsequent step + * for a given path. + */ +class SubWalks { + store = new Map(); + add(target, pattern) { + if (!target.canReaddir()) { + return; + } + const subs = this.store.get(target); + if (subs) { + if (!subs.find(p => p.globString() === pattern.globString())) { + subs.push(pattern); + } + } + else + this.store.set(target, [pattern]); + } + get(target) { + const subs = this.store.get(target); + /* c8 ignore start */ + if (!subs) { + throw new Error('attempting to walk unknown path'); + } + /* c8 ignore stop */ + return subs; + } + entries() { + return this.keys().map(k => [k, this.store.get(k)]); + } + keys() { + return [...this.store.keys()].filter(t => t.canReaddir()); + } +} +exports.SubWalks = SubWalks; +/** + * The class that processes patterns for a given path. + * + * Handles child entry filtering, and determining whether a path's + * directory contents must be read. + */ +class Processor { + hasWalkedCache; + matches = new MatchRecord(); + subwalks = new SubWalks(); + patterns; + follow; + dot; + opts; + constructor(opts, hasWalkedCache) { + this.opts = opts; + this.follow = !!opts.follow; + this.dot = !!opts.dot; + this.hasWalkedCache = + hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache(); + } + processPatterns(target, patterns) { + this.patterns = patterns; + const processingSet = patterns.map(p => [target, p]); + // map of paths to the magic-starting subwalks they need to walk + // first item in patterns is the filter + for (let [t, pattern] of processingSet) { + this.hasWalkedCache.storeWalked(t, pattern); + const root = pattern.root(); + const absolute = pattern.isAbsolute() && this.opts.absolute !== false; + // start absolute patterns at root + if (root) { + t = t.resolve(root === '/' && this.opts.root !== undefined ? + this.opts.root + : root); + const rest = pattern.rest(); + if (!rest) { + this.matches.add(t, true, false); + continue; + } + else { + pattern = rest; + } + } + if (t.isENOENT()) continue; - if (fn(value, this.#keyList[i], this)) { - return this.get(this.#keyList[i], getOptions); + let p; + let rest; + let changed = false; + while (typeof (p = pattern.pattern()) === 'string' && + (rest = pattern.rest())) { + const c = t.resolve(p); + t = c; + pattern = rest; + changed = true; + } + p = pattern.pattern(); + rest = pattern.rest(); + if (changed) { + if (this.hasWalkedCache.hasWalked(t, pattern)) + continue; + this.hasWalkedCache.storeWalked(t, pattern); + } + // now we have either a final string for a known entry, + // more strings for an unknown entry, + // or a pattern starting with magic, mounted on t. + if (typeof p === 'string') { + // must not be final entry, otherwise we would have + // concatenated it earlier. + const ifDir = p === '..' || p === '' || p === '.'; + this.matches.add(t.resolve(p), absolute, ifDir); + continue; + } + else if (p === minimatch_1.GLOBSTAR) { + // if no rest, match and subwalk pattern + // if rest, process rest and subwalk pattern + // if it's a symlink, but we didn't get here by way of a + // globstar match (meaning it's the first time THIS globstar + // has traversed a symlink), then we follow it. Otherwise, stop. + if (!t.isSymbolicLink() || + this.follow || + pattern.checkFollowGlobstar()) { + this.subwalks.add(t, pattern); + } + const rp = rest?.pattern(); + const rrest = rest?.rest(); + if (!rest || ((rp === '' || rp === '.') && !rrest)) { + // only HAS to be a dir if it ends in **/ or **/. + // but ending in ** will match files as well. + this.matches.add(t, absolute, rp === '' || rp === '.'); + } + else { + if (rp === '..') { + // this would mean you're matching **/.. at the fs root, + // and no thanks, I'm not gonna test that specific case. + /* c8 ignore start */ + const tp = t.parent || t; + /* c8 ignore stop */ + if (!rrest) + this.matches.add(tp, absolute, true); + else if (!this.hasWalkedCache.hasWalked(tp, rrest)) { + this.subwalks.add(tp, rrest); + } + } + } + } + else if (p instanceof RegExp) { + this.subwalks.add(t, pattern); + } + } + return this; + } + subwalkTargets() { + return this.subwalks.keys(); + } + child() { + return new Processor(this.opts, this.hasWalkedCache); + } + // return a new Processor containing the subwalks for each + // child entry, and a set of matches, and + // a hasWalkedCache that's a copy of this one + // then we're going to call + filterEntries(parent, entries) { + const patterns = this.subwalks.get(parent); + // put matches and entry walks into the results processor + const results = this.child(); + for (const e of entries) { + for (const pattern of patterns) { + const absolute = pattern.isAbsolute(); + const p = pattern.pattern(); + const rest = pattern.rest(); + if (p === minimatch_1.GLOBSTAR) { + results.testGlobstar(e, pattern, rest, absolute); + } + else if (p instanceof RegExp) { + results.testRegExp(e, p, rest, absolute); + } + else { + results.testString(e, p, rest, absolute); + } + } + } + return results; + } + testGlobstar(e, pattern, rest, absolute) { + if (this.dot || !e.name.startsWith('.')) { + if (!pattern.hasMore()) { + this.matches.add(e, absolute, false); + } + if (e.canReaddir()) { + // if we're in follow mode or it's not a symlink, just keep + // testing the same pattern. If there's more after the globstar, + // then this symlink consumes the globstar. If not, then we can + // follow at most ONE symlink along the way, so we mark it, which + // also checks to ensure that it wasn't already marked. + if (this.follow || !e.isSymbolicLink()) { + this.subwalks.add(e, pattern); + } + else if (e.isSymbolicLink()) { + if (rest && pattern.checkFollowGlobstar()) { + this.subwalks.add(e, rest); + } + else if (pattern.markFollowGlobstar()) { + this.subwalks.add(e, pattern); + } + } + } + } + // if the NEXT thing matches this entry, then also add + // the rest. + if (rest) { + const rp = rest.pattern(); + if (typeof rp === 'string' && + // dots and empty were handled already + rp !== '..' && + rp !== '' && + rp !== '.') { + this.testString(e, rp, rest.rest(), absolute); + } + else if (rp === '..') { + /* c8 ignore start */ + const ep = e.parent || e; + /* c8 ignore stop */ + this.subwalks.add(ep, rest); + } + else if (rp instanceof RegExp) { + this.testRegExp(e, rp, rest.rest(), absolute); } } } - /** - * 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)`. - * - * If `thisp` is provided, function will be called in the `this`-context of - * the provided object, or the cache if no `thisp` object is provided. - * - * Does not update age or recenty of use, or iterate over stale values. - */ - forEach(fn, thisp = this) { - for (const i of this.#indexes()) { - const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; - if (value === undefined) - continue; - fn.call(thisp, value, this.#keyList[i], this); + testRegExp(e, p, rest, absolute) { + if (!p.test(e.name)) + return; + if (!rest) { + this.matches.add(e, absolute, false); } - } - /** - * 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 (const i of this.#rindexes()) { - const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; - if (value === undefined) - continue; - fn.call(thisp, value, this.#keyList[i], this); + else { + this.subwalks.add(e, rest); } } - /** - * Delete any stale entries. Returns true if anything was removed, - * false otherwise. - */ - purgeStale() { - let deleted = false; - for (const i of this.#rindexes({ allowStale: true })) { - if (this.#isStale(i)) { - this.#delete(this.#keyList[i], 'expire'); - deleted = true; - } + testString(e, p, rest, absolute) { + // should never happen? + if (!e.isNamed(p)) + return; + if (!rest) { + this.matches.add(e, absolute, false); + } + else { + this.subwalks.add(e, rest); } - return deleted; } - /** - * Get the extended info about a given entry, to get its value, size, and - * TTL info simultaneously. Returns `undefined` if the key is not present. - * - * Unlike {@link LRUCache#dump}, which is designed to be portable and survive - * serialization, the `start` value is always the current timestamp, and the - * `ttl` is a calculated remaining time to live (negative if expired). - * - * Always returns stale values, if their info is found in the cache, so be - * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl}) - * if relevant. - */ - info(key) { - const i = this.#keyMap.get(key); - if (i === undefined) - return undefined; - const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; - if (value === undefined) - return undefined; - const entry = { value }; - if (this.#ttls && this.#starts) { - const ttl = this.#ttls[i]; - const start = this.#starts[i]; - if (ttl && start) { - const remain = ttl - (perf.now() - start); - entry.ttl = remain; - entry.start = Date.now(); +} +exports.Processor = Processor; +//# sourceMappingURL=processor.js.map + +/***/ }), + +/***/ 95049: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0; +/** + * Single-use utility classes to provide functionality to the {@link Glob} + * methods. + * + * @module + */ +const minipass_1 = __nccwpck_require__(78275); +const ignore_js_1 = __nccwpck_require__(4833); +const processor_js_1 = __nccwpck_require__(48095); +const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts) + : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts) + : ignore; +/** + * basic walking utilities that all the glob walker types use + */ +class GlobUtil { + path; + patterns; + opts; + seen = new Set(); + paused = false; + aborted = false; + #onResume = []; + #ignore; + #sep; + signal; + maxDepth; + includeChildMatches; + constructor(patterns, path, opts) { + this.patterns = patterns; + this.path = path; + this.opts = opts; + this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/'; + this.includeChildMatches = opts.includeChildMatches !== false; + if (opts.ignore || !this.includeChildMatches) { + this.#ignore = makeIgnore(opts.ignore ?? [], opts); + if (!this.includeChildMatches && + typeof this.#ignore.add !== 'function') { + const m = 'cannot ignore child matches, ignore lacks add() method.'; + throw new Error(m); } } - if (this.#sizes) { - entry.size = this.#sizes[i]; + // ignore, always set with maxDepth, but it's optional on the + // GlobOptions type + /* c8 ignore start */ + this.maxDepth = opts.maxDepth || Infinity; + /* c8 ignore stop */ + if (opts.signal) { + this.signal = opts.signal; + this.signal.addEventListener('abort', () => { + this.#onResume.length = 0; + }); } - return entry; } - /** - * Return an array of [key, {@link LRUCache.Entry}] tuples which can be - * passed to {@link LRLUCache#load}. - * - * The `start` fields are calculated relative to a portable `Date.now()` - * timestamp, even if `performance.now()` is available. - * - * Stale entries are always included in the `dump`, even if - * {@link LRUCache.OptionsBase.allowStale} is false. - * - * Note: this returns an actual array, not a generator, so it can be more - * easily passed around. - */ - dump() { - const arr = []; - for (const i of this.#indexes({ allowStale: true })) { - const key = this.#keyList[i]; - const v = this.#valList[i]; - const value = this.#isBackgroundFetch(v) - ? v.__staleWhileFetching - : v; - if (value === undefined || key === undefined) - continue; - const entry = { value }; - if (this.#ttls && this.#starts) { - entry.ttl = this.#ttls[i]; - // always dump the start relative to a portable timestamp - // it's ok for this to be a bit slow, it's a rare operation. - const age = perf.now() - this.#starts[i]; - entry.start = Math.floor(Date.now() - age); - } - if (this.#sizes) { - entry.size = this.#sizes[i]; - } - arr.unshift([key, entry]); + #ignored(path) { + return this.seen.has(path) || !!this.#ignore?.ignored?.(path); + } + #childrenIgnored(path) { + return !!this.#ignore?.childrenIgnored?.(path); + } + // backpressure mechanism + pause() { + this.paused = true; + } + resume() { + /* c8 ignore start */ + if (this.signal?.aborted) + return; + /* c8 ignore stop */ + this.paused = false; + let fn = undefined; + while (!this.paused && (fn = this.#onResume.shift())) { + fn(); } - return arr; } - /** - * Reset the cache and load in the items in entries in the order listed. - * - * The shape of the resulting cache may be different if the same options are - * not used in both caches. - * - * The `start` fields are assumed to be calculated relative to a portable - * `Date.now()` timestamp, even if `performance.now()` is available. - */ - load(arr) { - this.clear(); - for (const [key, entry] of arr) { - if (entry.start) { - // entry.start is a portable timestamp, but we may be using - // node's performance.now(), so calculate the offset, so that - // we get the intended remaining TTL, no matter how long it's - // been on ice. - // - // it's ok for this to be a bit slow, it's a rare operation. - const age = Date.now() - entry.start; - entry.start = perf.now() - age; - } - this.set(key, entry.value, entry); + onResume(fn) { + if (this.signal?.aborted) + return; + /* c8 ignore start */ + if (!this.paused) { + fn(); + } + else { + /* c8 ignore stop */ + this.#onResume.push(fn); } } - /** - * Add a value to the cache. - * - * Note: if `undefined` is specified as a value, this is an alias for - * {@link LRUCache#delete} - * - * Fields on the {@link LRUCache.SetOptions} options param will override - * their corresponding values in the constructor options for the scope - * of this single `set()` operation. - * - * If `start` is provided, then that will set the effective start - * time for the TTL calculation. Note that this must be a previous - * value of `performance.now()` if supported, or a previous value of - * `Date.now()` if not. - * - * Options object may also include `size`, which will prevent - * calling the `sizeCalculation` function and just use the specified - * number if it is a positive integer, and `noDisposeOnSet` which - * will prevent calling a `dispose` function in the case of - * overwrites. - * - * If the `size` (or return value of `sizeCalculation`) for a given - * entry is greater than `maxEntrySize`, then the item will not be - * added to the cache. - * - * Will update the recency of the entry. - * - * If the value is `undefined`, then this is an alias for - * `cache.delete(key)`. `undefined` is never stored in the cache. - */ - set(k, v, setOptions = {}) { - if (v === undefined) { - this.delete(k); - return this; + // do the requisite realpath/stat checking, and return the path + // to add or undefined to filter it out. + async matchCheck(e, ifDir) { + if (ifDir && this.opts.nodir) + return undefined; + let rpc; + if (this.opts.realpath) { + rpc = e.realpathCached() || (await e.realpath()); + if (!rpc) + return undefined; + e = rpc; } - const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions; - let { noUpdateTTL = this.noUpdateTTL } = setOptions; - const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation); - // if the item doesn't fit, don't do anything - // NB: maxEntrySize set to maxSize by default - if (this.maxEntrySize && size > this.maxEntrySize) { - if (status) { - status.set = 'miss'; - status.maxEntrySizeExceeded = true; + const needStat = e.isUnknown() || this.opts.stat; + const s = needStat ? await e.lstat() : e; + if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { + const target = await s.realpath(); + /* c8 ignore start */ + if (target && (target.isUnknown() || this.opts.stat)) { + await target.lstat(); } - // have to delete, in case something is there already. - this.#delete(k, 'set'); - return this; + /* c8 ignore stop */ } - let index = this.#size === 0 ? undefined : this.#keyMap.get(k); - if (index === undefined) { - // addition - index = (this.#size === 0 - ? this.#tail - : this.#free.length !== 0 - ? this.#free.pop() - : this.#size === this.#max - ? this.#evict(false) - : 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); - if (status) - status.set = 'add'; - noUpdateTTL = false; + return this.matchCheckTest(s, ifDir); + } + matchCheckTest(e, ifDir) { + return (e && + (this.maxDepth === Infinity || e.depth() <= this.maxDepth) && + (!ifDir || e.canReaddir()) && + (!this.opts.nodir || !e.isDirectory()) && + (!this.opts.nodir || + !this.opts.follow || + !e.isSymbolicLink() || + !e.realpathCached()?.isDirectory()) && + !this.#ignored(e)) ? + e + : undefined; + } + matchCheckSync(e, ifDir) { + if (ifDir && this.opts.nodir) + return undefined; + let rpc; + if (this.opts.realpath) { + rpc = e.realpathCached() || e.realpathSync(); + if (!rpc) + return undefined; + e = rpc; } - else { - // update - this.#moveToTail(index); - const oldVal = this.#valList[index]; - if (v !== oldVal) { - if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) { - oldVal.__abortController.abort(new Error('replaced')); - const { __staleWhileFetching: s } = oldVal; - if (s !== undefined && !noDisposeOnSet) { - if (this.#hasDispose) { - this.#dispose?.(s, k, 'set'); - } - if (this.#hasDisposeAfter) { - this.#disposed?.push([s, k, 'set']); - } - } - } - else if (!noDisposeOnSet) { - if (this.#hasDispose) { - this.#dispose?.(oldVal, k, 'set'); - } - if (this.#hasDisposeAfter) { - this.#disposed?.push([oldVal, k, 'set']); - } - } - this.#removeItemSize(index); - this.#addItemSize(index, size, status); - this.#valList[index] = v; - if (status) { - status.set = 'replace'; - const oldValue = oldVal && this.#isBackgroundFetch(oldVal) - ? oldVal.__staleWhileFetching - : oldVal; - if (oldValue !== undefined) - status.oldValue = oldValue; - } - } - else if (status) { - status.set = 'update'; + const needStat = e.isUnknown() || this.opts.stat; + const s = needStat ? e.lstatSync() : e; + if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) { + const target = s.realpathSync(); + if (target && (target?.isUnknown() || this.opts.stat)) { + target.lstatSync(); } } - if (ttl !== 0 && !this.#ttls) { - this.#initializeTTLTracking(); + return this.matchCheckTest(s, ifDir); + } + matchFinish(e, absolute) { + if (this.#ignored(e)) + return; + // we know we have an ignore if this is false, but TS doesn't + if (!this.includeChildMatches && this.#ignore?.add) { + const ign = `${e.relativePosix()}/**`; + this.#ignore.add(ign); } - if (this.#ttls) { - if (!noUpdateTTL) { - this.#setItemTTL(index, ttl, start); - } - if (status) - this.#statusTTL(status, index); + const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute; + this.seen.add(e); + const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''; + // ok, we have what we need! + if (this.opts.withFileTypes) { + this.matchEmit(e); } - if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) { - const dt = this.#disposed; - let task; - while ((task = dt?.shift())) { - this.#disposeAfter?.(...task); - } + else if (abs) { + const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath(); + this.matchEmit(abs + mark); + } + else { + const rel = this.opts.posix ? e.relativePosix() : e.relative(); + const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ? + '.' + this.#sep + : ''; + this.matchEmit(!rel ? '.' + mark : pre + rel + mark); } - return this; } - /** - * Evict the least recently used item, returning its value or - * `undefined` if cache is empty. - */ - pop() { - try { - while (this.#size) { - const val = this.#valList[this.#head]; - this.#evict(true); - if (this.#isBackgroundFetch(val)) { - if (val.__staleWhileFetching) { - return val.__staleWhileFetching; - } - } - else if (val !== undefined) { - return val; - } - } + async match(e, absolute, ifDir) { + const p = await this.matchCheck(e, ifDir); + if (p) + this.matchFinish(p, absolute); + } + matchSync(e, absolute, ifDir) { + const p = this.matchCheckSync(e, ifDir); + if (p) + this.matchFinish(p, absolute); + } + walkCB(target, patterns, cb) { + /* c8 ignore start */ + if (this.signal?.aborted) + cb(); + /* c8 ignore stop */ + this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb); + } + walkCB2(target, patterns, processor, cb) { + if (this.#childrenIgnored(target)) + return cb(); + if (this.signal?.aborted) + cb(); + if (this.paused) { + this.onResume(() => this.walkCB2(target, patterns, processor, cb)); + return; } - finally { - if (this.#hasDisposeAfter && this.#disposed) { - const dt = this.#disposed; - let task; - while ((task = dt?.shift())) { - this.#disposeAfter?.(...task); - } + processor.processPatterns(target, patterns); + // done processing. all of the above is sync, can be abstracted out. + // subwalks is a map of paths to the entry filters they need + // matches is a map of paths to [absolute, ifDir] tuples. + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + tasks++; + this.match(m, absolute, ifDir).then(() => next()); + } + for (const t of processor.subwalkTargets()) { + if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { + continue; + } + tasks++; + const childrenCached = t.readdirCached(); + if (t.calledReaddir()) + this.walkCB3(t, childrenCached, processor, next); + else { + t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true); } } + next(); } - #evict(free) { - const head = this.#head; - const k = this.#keyList[head]; - const v = this.#valList[head]; - if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) { - v.__abortController.abort(new Error('evicted')); + walkCB3(target, entries, processor, cb) { + processor = processor.filterEntries(target, entries); + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + tasks++; + this.match(m, absolute, ifDir).then(() => next()); } - else if (this.#hasDispose || this.#hasDisposeAfter) { - if (this.#hasDispose) { - this.#dispose?.(v, k, 'evict'); - } - if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, 'evict']); - } + for (const [target, patterns] of processor.subwalks.entries()) { + tasks++; + this.walkCB2(target, patterns, processor.child(), next); } - this.#removeItemSize(head); - // if we aren't about to use the index, then null these out - if (free) { - this.#keyList[head] = undefined; - this.#valList[head] = undefined; - this.#free.push(head); + next(); + } + walkCBSync(target, patterns, cb) { + /* c8 ignore start */ + if (this.signal?.aborted) + cb(); + /* c8 ignore stop */ + this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb); + } + walkCB2Sync(target, patterns, processor, cb) { + if (this.#childrenIgnored(target)) + return cb(); + if (this.signal?.aborted) + cb(); + if (this.paused) { + this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb)); + return; } - if (this.#size === 1) { - this.#head = this.#tail = 0; - this.#free.length = 0; + processor.processPatterns(target, patterns); + // done processing. all of the above is sync, can be abstracted out. + // subwalks is a map of paths to the entry filters they need + // matches is a map of paths to [absolute, ifDir] tuples. + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + this.matchSync(m, absolute, ifDir); } - else { - this.#head = this.#next[head]; + for (const t of processor.subwalkTargets()) { + if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) { + continue; + } + tasks++; + const children = t.readdirSync(); + this.walkCB3Sync(t, children, processor, next); } - this.#keyMap.delete(k); - this.#size--; - return head; + next(); } - /** - * 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. - * - * Check if a key is in the cache, without updating the recency of - * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set - * to `true` in either the options or the constructor. - * - * Will return `false` if the item is stale, even though it is technically in - * the cache. The difference can be determined (if it matters) by using a - * `status` argument, and inspecting the `has` field. - * - * Will not update item age unless - * {@link LRUCache.OptionsBase.updateAgeOnHas} is set. - */ - has(k, hasOptions = {}) { - const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions; - const index = this.#keyMap.get(k); - if (index !== undefined) { - const v = this.#valList[index]; - if (this.#isBackgroundFetch(v) && - v.__staleWhileFetching === undefined) { - return false; - } - if (!this.#isStale(index)) { - if (updateAgeOnHas) { - this.#updateItemAge(index); - } - if (status) { - status.has = 'hit'; - this.#statusTTL(status, index); - } - return true; - } - else if (status) { - status.has = 'stale'; - this.#statusTTL(status, index); - } + walkCB3Sync(target, entries, processor, cb) { + processor = processor.filterEntries(target, entries); + let tasks = 1; + const next = () => { + if (--tasks === 0) + cb(); + }; + for (const [m, absolute, ifDir] of processor.matches.entries()) { + if (this.#ignored(m)) + continue; + this.matchSync(m, absolute, ifDir); } - else if (status) { - status.has = 'miss'; + for (const [target, patterns] of processor.subwalks.entries()) { + tasks++; + this.walkCB2Sync(target, patterns, processor.child(), next); } - return false; + next(); } - /** - * 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 = {}) { - const { allowStale = this.allowStale } = peekOptions; - const index = this.#keyMap.get(k); - if (index === undefined || - (!allowStale && this.#isStale(index))) { - return; - } - const v = this.#valList[index]; - // either stale and allowed, or forcing a refresh of non-stale value - return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v; +} +exports.GlobUtil = GlobUtil; +class GlobWalker extends GlobUtil { + matches = new Set(); + constructor(patterns, path, opts) { + super(patterns, path, opts); } - #backgroundFetch(k, index, options, context) { - const v = index === undefined ? undefined : this.#valList[index]; - if (this.#isBackgroundFetch(v)) { - return v; + matchEmit(e) { + this.matches.add(e); + } + async walk() { + if (this.signal?.aborted) + throw this.signal.reason; + if (this.path.isUnknown()) { + await this.path.lstat(); } - const ac = new AC(); - const { signal } = options; - // when/if our AC signals, then stop listening to theirs. - signal?.addEventListener('abort', () => ac.abort(signal.reason), { - signal: ac.signal, - }); - const fetchOpts = { - signal: ac.signal, - options, - context, - }; - const cb = (v, updateCache = false) => { - const { aborted } = ac.signal; - const ignoreAbort = options.ignoreFetchAbort && v !== undefined; - if (options.status) { - if (aborted && !updateCache) { - options.status.fetchAborted = true; - options.status.fetchError = ac.signal.reason; - if (ignoreAbort) - options.status.fetchAbortIgnored = true; - } - else { - options.status.fetchResolved = true; - } - } - if (aborted && !ignoreAbort && !updateCache) { - return fetchFail(ac.signal.reason); - } - // either we didn't abort, and are still here, or we did, and ignored - const bf = p; - if (this.#valList[index] === p) { - if (v === undefined) { - if (bf.__staleWhileFetching) { - this.#valList[index] = bf.__staleWhileFetching; - } - else { - this.#delete(k, 'fetch'); - } + await new Promise((res, rej) => { + this.walkCB(this.path, this.patterns, () => { + if (this.signal?.aborted) { + rej(this.signal.reason); } else { - if (options.status) - options.status.fetchUpdated = true; - this.set(k, v, fetchOpts.options); - } - } - return v; - }; - const eb = (er) => { - if (options.status) { - options.status.fetchRejected = true; - options.status.fetchError = er; - } - return fetchFail(er); - }; - const fetchFail = (er) => { - const { aborted } = ac.signal; - const allowStaleAborted = aborted && options.allowStaleOnFetchAbort; - const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection; - const noDelete = allowStale || options.noDeleteOnFetchRejection; - const bf = p; - if (this.#valList[index] === p) { - // if we allow stale on fetch rejections, then we need to ensure that - // the stale value is not removed from the cache when the fetch fails. - const del = !noDelete || bf.__staleWhileFetching === undefined; - if (del) { - this.#delete(k, 'fetch'); - } - else if (!allowStaleAborted) { - // still replace the *promise* with the stale value, - // since we are done with the promise at this point. - // leave it untouched if we're still waiting for an - // aborted background fetch that hasn't yet returned. - this.#valList[index] = bf.__staleWhileFetching; - } - } - if (allowStale) { - if (options.status && bf.__staleWhileFetching !== undefined) { - options.status.returnedStale = true; - } - return bf.__staleWhileFetching; - } - else if (bf.__returned === bf) { - throw er; - } - }; - const pcall = (res, rej) => { - const fmp = this.#fetchMethod?.(k, v, fetchOpts); - if (fmp && fmp instanceof Promise) { - fmp.then(v => res(v === undefined ? undefined : v), rej); - } - // ignored, we go until we finish, regardless. - // defer check until we are actually aborting, - // so fetchMethod can override. - ac.signal.addEventListener('abort', () => { - if (!options.ignoreFetchAbort || - options.allowStaleOnFetchAbort) { - res(undefined); - // when it eventually resolves, update the cache. - if (options.allowStaleOnFetchAbort) { - res = v => cb(v, true); - } + res(this.matches); } }); - }; - if (options.status) - options.status.fetchDispatched = true; - const p = new Promise(pcall).then(cb, eb); - const bf = Object.assign(p, { - __abortController: ac, - __staleWhileFetching: v, - __returned: undefined, }); - if (index === undefined) { - // internal, don't expose status. - this.set(k, bf, { ...fetchOpts.options, status: undefined }); - index = this.#keyMap.get(k); + return this.matches; + } + walkSync() { + if (this.signal?.aborted) + throw this.signal.reason; + if (this.path.isUnknown()) { + this.path.lstatSync(); + } + // nothing for the callback to do, because this never pauses + this.walkCBSync(this.path, this.patterns, () => { + if (this.signal?.aborted) + throw this.signal.reason; + }); + return this.matches; + } +} +exports.GlobWalker = GlobWalker; +class GlobStream extends GlobUtil { + results; + constructor(patterns, path, opts) { + super(patterns, path, opts); + this.results = new minipass_1.Minipass({ + signal: this.signal, + objectMode: true, + }); + this.results.on('drain', () => this.resume()); + this.results.on('resume', () => this.resume()); + } + matchEmit(e) { + this.results.write(e); + if (!this.results.flowing) + this.pause(); + } + stream() { + const target = this.path; + if (target.isUnknown()) { + target.lstat().then(() => { + this.walkCB(target, this.patterns, () => this.results.end()); + }); } else { - this.#valList[index] = bf; + this.walkCB(target, this.patterns, () => this.results.end()); } - return bf; + return this.results; } - #isBackgroundFetch(p) { - if (!this.#hasFetchMethod) - return false; - const b = p; - return (!!b && - b instanceof Promise && - b.hasOwnProperty('__staleWhileFetching') && - b.__abortController instanceof AC); + streamSync() { + if (this.path.isUnknown()) { + this.path.lstatSync(); + } + this.walkCBSync(this.path, this.patterns, () => this.results.end()); + return this.results; } - async fetch(k, fetchOptions = {}) { - const { - // 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 = false, status, signal, } = fetchOptions; - if (!this.#hasFetchMethod) { - if (status) - status.fetch = 'get'; - return this.get(k, { - allowStale, - updateAgeOnGet, - noDeleteOnStaleGet, - status, - }); +} +exports.GlobStream = GlobStream; +//# sourceMappingURL=walker.js.map + +/***/ }), + +/***/ 33555: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.assertValidPattern = void 0; +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = (pattern) => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern'); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long'); + } +}; +exports.assertValidPattern = assertValidPattern; +//# sourceMappingURL=assert-valid-pattern.js.map + +/***/ }), + +/***/ 10421: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +// parse a single path portion +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AST = void 0; +const brace_expressions_js_1 = __nccwpck_require__(34796); +const unescape_js_1 = __nccwpck_require__(11633); +const types = new Set(['!', '?', '+', '*', '@']); +const isExtglobType = (c) => types.has(c); +// Patterns that get prepended to bind to the start of either the +// entire string, or just a single path portion, to prevent dots +// and/or traversal patterns, when needed. +// Exts don't need the ^ or / bit, because the root binds that already. +const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))'; +const startNoDot = '(?!\\.)'; +// characters that indicate a start of pattern needs the "no dots" bit, +// because a dot *might* be matched. ( is not in the list, because in +// the case of a child extglob, it will handle the prevention itself. +const addPatternStart = new Set(['[', '.']); +// cases where traversal is A-OK, no dot prevention needed +const justDots = new Set(['..', '.']); +const reSpecials = new Set('().*{}+?[]^$\\!'); +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// any single thing other than / +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// use + when we need to ensure that *something* matches, because the * is +// the only thing in the path portion. +const starNoEmpty = qmark + '+?'; +// remove the \ chars that we added if we end up doing a nonmagic compare +// const deslash = (s: string) => s.replace(/\\(.)/g, '$1') +class AST { + type; + #root; + #hasMagic; + #uflag = false; + #parts = []; + #parent; + #parentIndex; + #negs; + #filledNegs = false; + #options; + #toString; + // set to true if it's an extglob with no children + // (which really means one child of '') + #emptyExt = false; + constructor(type, parent, options = {}) { + this.type = type; + // extglobs are inherently magical + if (type) + this.#hasMagic = true; + this.#parent = parent; + this.#root = this.#parent ? this.#parent.#root : this; + this.#options = this.#root === this ? options : this.#root.#options; + this.#negs = this.#root === this ? [] : this.#root.#negs; + if (type === '!' && !this.#root.#filledNegs) + this.#negs.push(this); + this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0; + } + get hasMagic() { + /* c8 ignore start */ + if (this.#hasMagic !== undefined) + return this.#hasMagic; + /* c8 ignore stop */ + for (const p of this.#parts) { + if (typeof p === 'string') + continue; + if (p.type || p.hasMagic) + return (this.#hasMagic = true); } - const options = { - allowStale, - updateAgeOnGet, - noDeleteOnStaleGet, - ttl, - noDisposeOnSet, - size, - sizeCalculation, - noUpdateTTL, - noDeleteOnFetchRejection, - allowStaleOnFetchRejection, - allowStaleOnFetchAbort, - ignoreFetchAbort, - status, - signal, - }; - let index = this.#keyMap.get(k); - if (index === undefined) { - if (status) - status.fetch = 'miss'; - const p = this.#backgroundFetch(k, index, options, context); - return (p.__returned = p); + // note: will be undefined until we generate the regexp src and find out + return this.#hasMagic; + } + // reconstructs the pattern + toString() { + if (this.#toString !== undefined) + return this.#toString; + if (!this.type) { + return (this.#toString = this.#parts.map(p => String(p)).join('')); } else { - // in cache, maybe already fetching - const v = this.#valList[index]; - if (this.#isBackgroundFetch(v)) { - const stale = allowStale && v.__staleWhileFetching !== undefined; - if (status) { - status.fetch = 'inflight'; - if (stale) - status.returnedStale = true; + return (this.#toString = + this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')'); + } + } + #fillNegs() { + /* c8 ignore start */ + if (this !== this.#root) + throw new Error('should only call on root'); + if (this.#filledNegs) + return this; + /* c8 ignore stop */ + // call toString() once to fill this out + this.toString(); + this.#filledNegs = true; + let n; + while ((n = this.#negs.pop())) { + if (n.type !== '!') + continue; + // walk up the tree, appending everthing that comes AFTER parentIndex + let p = n; + let pp = p.#parent; + while (pp) { + for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) { + for (const part of n.#parts) { + /* c8 ignore start */ + if (typeof part === 'string') { + throw new Error('string part in extglob AST??'); + } + /* c8 ignore stop */ + part.copyIn(pp.#parts[i]); + } } - return stale ? v.__staleWhileFetching : (v.__returned = v); + p = pp; + pp = p.#parent; } - // if we force a refresh, that means do NOT serve the cached value, - // unless we are already in the process of refreshing the cache. - const isStale = this.#isStale(index); - if (!forceRefresh && !isStale) { - if (status) - status.fetch = 'hit'; - this.#moveToTail(index); - if (updateAgeOnGet) { - this.#updateItemAge(index); - } - if (status) - this.#statusTTL(status, index); - return v; + } + return this; + } + push(...parts) { + for (const p of parts) { + if (p === '') + continue; + /* c8 ignore start */ + if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) { + throw new Error('invalid part: ' + p); } - // ok, it is stale or a forced refresh, and not already fetching. - // refresh the cache. - const p = this.#backgroundFetch(k, index, options, context); - const hasStale = p.__staleWhileFetching !== undefined; - const staleVal = hasStale && allowStale; - if (status) { - status.fetch = isStale ? 'stale' : 'refresh'; - if (staleVal && isStale) - status.returnedStale = true; + /* c8 ignore stop */ + this.#parts.push(p); + } + } + toJSON() { + const ret = this.type === null + ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON())) + : [this.type, ...this.#parts.map(p => p.toJSON())]; + if (this.isStart() && !this.type) + ret.unshift([]); + if (this.isEnd() && + (this === this.#root || + (this.#root.#filledNegs && this.#parent?.type === '!'))) { + ret.push({}); + } + return ret; + } + isStart() { + if (this.#root === this) + return true; + // if (this.type) return !!this.#parent?.isStart() + if (!this.#parent?.isStart()) + return false; + if (this.#parentIndex === 0) + return true; + // if everything AHEAD of this is a negation, then it's still the "start" + const p = this.#parent; + for (let i = 0; i < this.#parentIndex; i++) { + const pp = p.#parts[i]; + if (!(pp instanceof AST && pp.type === '!')) { + return false; } - return staleVal ? p.__staleWhileFetching : (p.__returned = p); } + return true; } - async forceFetch(k, fetchOptions = {}) { - const v = await this.fetch(k, fetchOptions); - if (v === undefined) - throw new Error('fetch() returned undefined'); - return v; + isEnd() { + if (this.#root === this) + return true; + if (this.#parent?.type === '!') + return true; + if (!this.#parent?.isEnd()) + return false; + if (!this.type) + return this.#parent?.isEnd(); + // if not root, it'll always have a parent + /* c8 ignore start */ + const pl = this.#parent ? this.#parent.#parts.length : 0; + /* c8 ignore stop */ + return this.#parentIndex === pl - 1; } - memo(k, memoOptions = {}) { - const memoMethod = this.#memoMethod; - if (!memoMethod) { - throw new Error('no memoMethod provided to constructor'); + copyIn(part) { + if (typeof part === 'string') + this.push(part); + else + this.push(part.clone(this)); + } + clone(parent) { + const c = new AST(this.type, parent); + for (const p of this.#parts) { + c.copyIn(p); } - const { context, forceRefresh, ...options } = memoOptions; - const v = this.get(k, options); - if (!forceRefresh && v !== undefined) - return v; - const vv = memoMethod(k, v, { - options, - context, - }); - this.set(k, vv, options); - return vv; + return c; } - /** - * 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 = {}) { - const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions; - const index = this.#keyMap.get(k); - if (index !== undefined) { - const value = this.#valList[index]; - const fetching = this.#isBackgroundFetch(value); - if (status) - this.#statusTTL(status, index); - if (this.#isStale(index)) { - if (status) - status.get = 'stale'; - // delete only if not an in-flight background fetch - if (!fetching) { - if (!noDeleteOnStaleGet) { - this.#delete(k, 'expire'); - } - if (status && allowStale) - status.returnedStale = true; - return allowStale ? value : undefined; + static #parseAST(str, ast, pos, opt) { + let escaping = false; + let inBrace = false; + let braceStart = -1; + let braceNeg = false; + if (ast.type === null) { + // outside of a extglob, append until we find a start + let i = pos; + let acc = ''; + while (i < str.length) { + const c = str.charAt(i++); + // still accumulate escapes at this point, but we do ignore + // starts that are escaped + if (escaping || c === '\\') { + escaping = !escaping; + acc += c; + continue; } - else { - if (status && - allowStale && - value.__staleWhileFetching !== undefined) { - status.returnedStale = true; + if (inBrace) { + if (i === braceStart + 1) { + if (c === '^' || c === '!') { + braceNeg = true; + } } - return allowStale ? value.__staleWhileFetching : undefined; + else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; } - } - else { - if (status) - status.get = 'hit'; - // if we're currently fetching it, we don't actually have it yet - // it's not stale, which means this isn't a staleWhileRefetching. - // If it's not stale, and fetching, AND has a __staleWhileFetching - // value, then that means the user fetched with {forceRefresh:true}, - // so it's safe to return that value. - if (fetching) { - return value.__staleWhileFetching; + else if (c === '[') { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; } - this.#moveToTail(index); - if (updateAgeOnGet) { - this.#updateItemAge(index); + if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') { + ast.push(acc); + acc = ''; + const ext = new AST(c, ast); + i = AST.#parseAST(str, ext, i, opt); + ast.push(ext); + continue; } - return value; + acc += c; } + ast.push(acc); + return i; } - else if (status) { - status.get = 'miss'; + // some kind of extglob, pos is at the ( + // find the next | or ) + let i = pos + 1; + let part = new AST(null, ast); + const parts = []; + let acc = ''; + while (i < str.length) { + const c = str.charAt(i++); + // still accumulate escapes at this point, but we do ignore + // starts that are escaped + if (escaping || c === '\\') { + escaping = !escaping; + acc += c; + continue; + } + if (inBrace) { + if (i === braceStart + 1) { + if (c === '^' || c === '!') { + braceNeg = true; + } + } + else if (c === ']' && !(i === braceStart + 2 && braceNeg)) { + inBrace = false; + } + acc += c; + continue; + } + else if (c === '[') { + inBrace = true; + braceStart = i; + braceNeg = false; + acc += c; + continue; + } + if (isExtglobType(c) && str.charAt(i) === '(') { + part.push(acc); + acc = ''; + const ext = new AST(c, part); + part.push(ext); + i = AST.#parseAST(str, ext, i, opt); + continue; + } + if (c === '|') { + part.push(acc); + acc = ''; + parts.push(part); + part = new AST(null, ast); + continue; + } + if (c === ')') { + if (acc === '' && ast.#parts.length === 0) { + ast.#emptyExt = true; + } + part.push(acc); + acc = ''; + ast.push(...parts, part); + return i; + } + acc += c; } + // unfinished extglob + // if we got here, it was a malformed extglob! not an extglob, but + // maybe something else in there. + ast.type = null; + ast.#hasMagic = undefined; + ast.#parts = [str.substring(pos - 1)]; + return i; } - #connect(p, n) { - this.#prev[n] = p; - this.#next[p] = n; + static fromGlob(pattern, options = {}) { + const ast = new AST(null, undefined, options); + AST.#parseAST(pattern, ast, 0, options); + return ast; } - #moveToTail(index) { - // if tail already, nothing to do - // if head, move head to next[index] - // else - // move next[prev[index]] to next[index] (head has no prev) - // move prev[next[index]] to prev[index] - // prev[index] = tail - // next[tail] = index - // tail = index - if (index !== this.#tail) { - if (index === this.#head) { - this.#head = this.#next[index]; - } - else { - this.#connect(this.#prev[index], this.#next[index]); - } - this.#connect(this.#tail, index); - this.#tail = index; + // returns the regular expression if there's magic, or the unescaped + // string if not. + toMMPattern() { + // should only be called on root + /* c8 ignore start */ + if (this !== this.#root) + return this.#root.toMMPattern(); + /* c8 ignore stop */ + const glob = this.toString(); + const [re, body, hasMagic, uflag] = this.toRegExpSource(); + // if we're in nocase mode, and not nocaseMagicOnly, then we do + // still need a regular expression if we have to case-insensitively + // match capital/lowercase characters. + const anyMagic = hasMagic || + this.#hasMagic || + (this.#options.nocase && + !this.#options.nocaseMagicOnly && + glob.toUpperCase() !== glob.toLowerCase()); + if (!anyMagic) { + return body; } + const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : ''); + return Object.assign(new RegExp(`^${re}$`, flags), { + _src: re, + _glob: glob, + }); } - /** - * Deletes a key out of the cache. - * - * Returns true if the key was deleted, false otherwise. - */ - delete(k) { - return this.#delete(k, 'delete'); + get options() { + return this.#options; } - #delete(k, reason) { - let deleted = false; - if (this.#size !== 0) { - const index = this.#keyMap.get(k); - if (index !== undefined) { - deleted = true; - if (this.#size === 1) { - this.#clear(reason); - } - else { - this.#removeItemSize(index); - const v = this.#valList[index]; - if (this.#isBackgroundFetch(v)) { - v.__abortController.abort(new Error('deleted')); - } - else if (this.#hasDispose || this.#hasDisposeAfter) { - if (this.#hasDispose) { - this.#dispose?.(v, k, reason); - } - if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, reason]); - } - } - this.#keyMap.delete(k); - this.#keyList[index] = undefined; - this.#valList[index] = undefined; - if (index === this.#tail) { - this.#tail = this.#prev[index]; - } - else if (index === this.#head) { - this.#head = this.#next[index]; - } - else { - const pi = this.#prev[index]; - this.#next[pi] = this.#next[index]; - const ni = this.#next[index]; - this.#prev[ni] = this.#prev[index]; + // returns the string match, the regexp source, whether there's magic + // in the regexp (so a regular expression is required) and whether or + // not the uflag is needed for the regular expression (for posix classes) + // TODO: instead of injecting the start/end at this point, just return + // the BODY of the regexp, along with the start/end portions suitable + // for binding the start/end in either a joined full-path makeRe context + // (where we bind to (^|/), or a standalone matchPart context (where + // we bind to ^, and not /). Otherwise slashes get duped! + // + // In part-matching mode, the start is: + // - if not isStart: nothing + // - if traversal possible, but not allowed: ^(?!\.\.?$) + // - if dots allowed or not possible: ^ + // - if dots possible and not allowed: ^(?!\.) + // end is: + // - if not isEnd(): nothing + // - else: $ + // + // In full-path matching mode, we put the slash at the START of the + // pattern, so start is: + // - if first pattern: same as part-matching mode + // - if not isStart(): nothing + // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) + // - if dots allowed or not possible: / + // - if dots possible and not allowed: /(?!\.) + // end is: + // - if last pattern, same as part-matching mode + // - else nothing + // + // Always put the (?:$|/) on negated tails, though, because that has to be + // there to bind the end of the negated pattern portion, and it's easier to + // just stick it in now rather than try to inject it later in the middle of + // the pattern. + // + // We can just always return the same end, and leave it up to the caller + // to know whether it's going to be used joined or in parts. + // And, if the start is adjusted slightly, can do the same there: + // - if not isStart: nothing + // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) + // - if dots allowed or not possible: (?:/|^) + // - if dots possible and not allowed: (?:/|^)(?!\.) + // + // But it's better to have a simpler binding without a conditional, for + // performance, so probably better to return both start options. + // + // Then the caller just ignores the end if it's not the first pattern, + // and the start always gets applied. + // + // But that's always going to be $ if it's the ending pattern, or nothing, + // so the caller can just attach $ at the end of the pattern when building. + // + // So the todo is: + // - better detect what kind of start is needed + // - return both flavors of starting pattern + // - attach $ at the end of the pattern when creating the actual RegExp + // + // Ah, but wait, no, that all only applies to the root when the first pattern + // is not an extglob. If the first pattern IS an extglob, then we need all + // that dot prevention biz to live in the extglob portions, because eg + // +(*|.x*) can match .xy but not .yx. + // + // So, return the two flavors if it's #root and the first child is not an + // AST, otherwise leave it to the child AST to handle it, and there, + // use the (?:^|/) style of start binding. + // + // Even simplified further: + // - Since the start for a join is eg /(?!\.) and the start for a part + // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root + // or start or whatever) and prepend ^ or / at the Regexp construction. + toRegExpSource(allowDot) { + const dot = allowDot ?? !!this.#options.dot; + if (this.#root === this) + this.#fillNegs(); + if (!this.type) { + const noEmpty = this.isStart() && this.isEnd(); + const src = this.#parts + .map(p => { + const [re, _, hasMagic, uflag] = typeof p === 'string' + ? AST.#parseGlob(p, this.#hasMagic, noEmpty) + : p.toRegExpSource(allowDot); + this.#hasMagic = this.#hasMagic || hasMagic; + this.#uflag = this.#uflag || uflag; + return re; + }) + .join(''); + let start = ''; + if (this.isStart()) { + if (typeof this.#parts[0] === 'string') { + // this is the string that will match the start of the pattern, + // so we need to protect against dots and such. + // '.' and '..' cannot match unless the pattern is that exactly, + // even if it starts with . or dot:true is set. + const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]); + if (!dotTravAllowed) { + const aps = addPatternStart; + // check if we have a possibility of matching . or .., + // and prevent that. + const needNoTrav = + // dots are allowed, and the pattern starts with [ or . + (dot && aps.has(src.charAt(0))) || + // the pattern starts with \., and then [ or . + (src.startsWith('\\.') && aps.has(src.charAt(2))) || + // the pattern starts with \.\., and then [ or . + (src.startsWith('\\.\\.') && aps.has(src.charAt(4))); + // no need to prevent dots if it can't match a dot, or if a + // sub-pattern will be preventing it anyway. + const needNoDot = !dot && !allowDot && aps.has(src.charAt(0)); + start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''; } - this.#size--; - this.#free.push(index); } } + // append the "end of path portion" pattern to negation tails + let end = ''; + if (this.isEnd() && + this.#root.#filledNegs && + this.#parent?.type === '!') { + end = '(?:$|\\/)'; + } + const final = start + src + end; + return [ + final, + (0, unescape_js_1.unescape)(src), + (this.#hasMagic = !!this.#hasMagic), + this.#uflag, + ]; } - if (this.#hasDisposeAfter && this.#disposed?.length) { - const dt = this.#disposed; - let task; - while ((task = dt?.shift())) { - this.#disposeAfter?.(...task); - } + // We need to calculate the body *twice* if it's a repeat pattern + // at the start, once in nodot mode, then again in dot mode, so a + // pattern like *(?) can match 'x.y' + const repeated = this.type === '*' || this.type === '+'; + // some kind of extglob + const start = this.type === '!' ? '(?:(?!(?:' : '(?:'; + let body = this.#partsToRegExp(dot); + if (this.isStart() && this.isEnd() && !body && this.type !== '!') { + // invalid extglob, has to at least be *something* present, if it's + // the entire path portion. + const s = this.toString(); + this.#parts = [s]; + this.type = null; + this.#hasMagic = undefined; + return [s, (0, unescape_js_1.unescape)(this.toString()), false, false]; } - return deleted; + // XXX abstract out this map method + let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot + ? '' + : this.#partsToRegExp(true); + if (bodyDotAllowed === body) { + bodyDotAllowed = ''; + } + if (bodyDotAllowed) { + body = `(?:${body})(?:${bodyDotAllowed})*?`; + } + // an empty !() is exactly equivalent to a starNoEmpty + let final = ''; + if (this.type === '!' && this.#emptyExt) { + final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty; + } + else { + const close = this.type === '!' + ? // !() must match something,but !(x) can match '' + '))' + + (this.isStart() && !dot && !allowDot ? startNoDot : '') + + star + + ')' + : this.type === '@' + ? ')' + : this.type === '?' + ? ')?' + : this.type === '+' && bodyDotAllowed + ? ')' + : this.type === '*' && bodyDotAllowed + ? `)?` + : `)${this.type}`; + final = start + body + close; + } + return [ + final, + (0, unescape_js_1.unescape)(body), + (this.#hasMagic = !!this.#hasMagic), + this.#uflag, + ]; } - /** - * Clear the cache entirely, throwing away all values. - */ - clear() { - return this.#clear('delete'); + #partsToRegExp(dot) { + return this.#parts + .map(p => { + // extglob ASTs should only contain parent ASTs + /* c8 ignore start */ + if (typeof p === 'string') { + throw new Error('string type in extglob ast??'); + } + /* c8 ignore stop */ + // can ignore hasMagic, because extglobs are already always magic + const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot); + this.#uflag = this.#uflag || uflag; + return re; + }) + .filter(p => !(this.isStart() && this.isEnd()) || !!p) + .join('|'); } - #clear(reason) { - for (const index of this.#rindexes({ allowStale: true })) { - const v = this.#valList[index]; - if (this.#isBackgroundFetch(v)) { - v.__abortController.abort(new Error('deleted')); + static #parseGlob(glob, hasMagic, noEmpty = false) { + let escaping = false; + let re = ''; + let uflag = false; + for (let i = 0; i < glob.length; i++) { + const c = glob.charAt(i); + if (escaping) { + escaping = false; + re += (reSpecials.has(c) ? '\\' : '') + c; + continue; } - else { - const k = this.#keyList[index]; - if (this.#hasDispose) { - this.#dispose?.(v, k, reason); + if (c === '\\') { + if (i === glob.length - 1) { + re += '\\\\'; } - if (this.#hasDisposeAfter) { - this.#disposed?.push([v, k, reason]); + else { + escaping = true; } + continue; } - } - this.#keyMap.clear(); - this.#valList.fill(undefined); - this.#keyList.fill(undefined); - if (this.#ttls && this.#starts) { - this.#ttls.fill(0); - this.#starts.fill(0); - } - if (this.#sizes) { - this.#sizes.fill(0); - } - this.#head = 0; - this.#tail = 0; - this.#free.length = 0; - this.#calculatedSize = 0; - this.#size = 0; - if (this.#hasDisposeAfter && this.#disposed) { - const dt = this.#disposed; - let task; - while ((task = dt?.shift())) { - this.#disposeAfter?.(...task); + if (c === '[') { + const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i); + if (consumed) { + re += src; + uflag = uflag || needUflag; + i += consumed - 1; + hasMagic = hasMagic || magic; + continue; + } + } + if (c === '*') { + if (noEmpty && glob === '*') + re += starNoEmpty; + else + re += star; + hasMagic = true; + continue; + } + if (c === '?') { + re += qmark; + hasMagic = true; + continue; } + re += regExpEscape(c); } + return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag]; } } -exports.LRUCache = LRUCache; -//# sourceMappingURL=index.js.map +exports.AST = AST; +//# sourceMappingURL=ast.js.map /***/ }), -/***/ 81017: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 34796: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +// translate the various posix character classes into unicode properties +// this works across all unicode locales Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Glob = void 0; -const minimatch_1 = __nccwpck_require__(85207); -const node_url_1 = __nccwpck_require__(73136); -const path_scurry_1 = __nccwpck_require__(16577); -const pattern_js_1 = __nccwpck_require__(4041); -const walker_js_1 = __nccwpck_require__(95049); -// if no process global, just call it linux. -// so we default to case-sensitive, / separators -const defaultPlatform = (typeof process === 'object' && - process && - typeof process.platform === 'string') ? - process.platform - : 'linux'; -/** - * An object that can perform glob pattern traversals. - */ -class Glob { - absolute; - cwd; - root; - dot; - dotRelative; - follow; - ignore; - magicalBraces; - mark; - matchBase; - maxDepth; - nobrace; - nocase; - nodir; - noext; - noglobstar; - pattern; - platform; - realpath; - scurry; - stat; - signal; - windowsPathsNoEscape; - withFileTypes; - includeChildMatches; - /** - * The options provided to the constructor. - */ - opts; - /** - * An array of parsed immutable {@link Pattern} objects. - */ - patterns; - /** - * All options are stored as properties on the `Glob` object. - * - * See {@link GlobOptions} for full options descriptions. - * - * Note that a previous `Glob` object can be passed as the - * `GlobOptions` to another `Glob` instantiation to re-use settings - * and caches with a new pattern. - * - * Traversal functions can be called multiple times to run the walk - * again. - */ - constructor(pattern, opts) { - /* c8 ignore start */ - if (!opts) - throw new TypeError('glob options required'); - /* c8 ignore stop */ - this.withFileTypes = !!opts.withFileTypes; - this.signal = opts.signal; - this.follow = !!opts.follow; - this.dot = !!opts.dot; - this.dotRelative = !!opts.dotRelative; - this.nodir = !!opts.nodir; - this.mark = !!opts.mark; - if (!opts.cwd) { - this.cwd = ''; - } - else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) { - opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd); - } - this.cwd = opts.cwd || ''; - this.root = opts.root; - this.magicalBraces = !!opts.magicalBraces; - this.nobrace = !!opts.nobrace; - this.noext = !!opts.noext; - this.realpath = !!opts.realpath; - this.absolute = opts.absolute; - this.includeChildMatches = opts.includeChildMatches !== false; - this.noglobstar = !!opts.noglobstar; - this.matchBase = !!opts.matchBase; - this.maxDepth = - typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity; - this.stat = !!opts.stat; - this.ignore = opts.ignore; - if (this.withFileTypes && this.absolute !== undefined) { - throw new Error('cannot set absolute and withFileTypes:true'); +exports.parseClass = void 0; +// { : [, /u flag required, negated] +const posixClasses = { + '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true], + '[:alpha:]': ['\\p{L}\\p{Nl}', true], + '[:ascii:]': ['\\x' + '00-\\x' + '7f', false], + '[:blank:]': ['\\p{Zs}\\t', true], + '[:cntrl:]': ['\\p{Cc}', true], + '[:digit:]': ['\\p{Nd}', true], + '[:graph:]': ['\\p{Z}\\p{C}', true, true], + '[:lower:]': ['\\p{Ll}', true], + '[:print:]': ['\\p{C}', true], + '[:punct:]': ['\\p{P}', true], + '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true], + '[:upper:]': ['\\p{Lu}', true], + '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true], + '[:xdigit:]': ['A-Fa-f0-9', false], +}; +// only need to escape a few things inside of brace expressions +// escapes: [ \ ] - +const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&'); +// escape all regexp magic characters +const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +// everything has already been escaped, we just have to join +const rangesToString = (ranges) => ranges.join(''); +// takes a glob string at a posix brace expression, and returns +// an equivalent regular expression source, and boolean indicating +// whether the /u flag needs to be applied, and the number of chars +// consumed to parse the character class. +// This also removes out of order ranges, and returns ($.) if the +// entire class just no good. +const parseClass = (glob, position) => { + const pos = position; + /* c8 ignore start */ + if (glob.charAt(pos) !== '[') { + throw new Error('not in a brace expression'); + } + /* c8 ignore stop */ + const ranges = []; + const negs = []; + let i = pos + 1; + let sawStart = false; + let uflag = false; + let escaping = false; + let negate = false; + let endPos = pos; + let rangeStart = ''; + WHILE: while (i < glob.length) { + const c = glob.charAt(i); + if ((c === '!' || c === '^') && i === pos + 1) { + negate = true; + i++; + continue; } - if (typeof pattern === 'string') { - pattern = [pattern]; + if (c === ']' && sawStart && !escaping) { + endPos = i + 1; + break; } - this.windowsPathsNoEscape = - !!opts.windowsPathsNoEscape || - opts.allowWindowsEscape === - false; - if (this.windowsPathsNoEscape) { - pattern = pattern.map(p => p.replace(/\\/g, '/')); + sawStart = true; + if (c === '\\') { + if (!escaping) { + escaping = true; + i++; + continue; + } + // escaped \ char, fall through and treat like normal char } - if (this.matchBase) { - if (opts.noglobstar) { - throw new TypeError('base matching requires globstar'); + if (c === '[' && !escaping) { + // either a posix class, a collation equivalent, or just a [ + for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { + if (glob.startsWith(cls, i)) { + // invalid, [a-[] is fine, but not [a-[:alpha]] + if (rangeStart) { + return ['$.', false, glob.length - pos, true]; + } + i += cls.length; + if (neg) + negs.push(unip); + else + ranges.push(unip); + uflag = uflag || u; + continue WHILE; + } } - pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`)); } - this.pattern = pattern; - this.platform = opts.platform || defaultPlatform; - this.opts = { ...opts, platform: this.platform }; - if (opts.scurry) { - this.scurry = opts.scurry; - if (opts.nocase !== undefined && - opts.nocase !== opts.scurry.nocase) { - throw new Error('nocase option contradicts provided scurry option'); + // now it's just a normal character, effectively + escaping = false; + if (rangeStart) { + // throw this range away if it's not valid, but others + // can still match. + if (c > rangeStart) { + ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c)); } + else if (c === rangeStart) { + ranges.push(braceEscape(c)); + } + rangeStart = ''; + i++; + continue; } - else { - const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32 - : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin - : opts.platform ? path_scurry_1.PathScurryPosix - : path_scurry_1.PathScurry; - this.scurry = new Scurry(this.cwd, { - nocase: opts.nocase, - fs: opts.fs, - }); + // now might be the start of a range. + // can be either c-d or c-] or c] or c] at this point + if (glob.startsWith('-]', i + 1)) { + ranges.push(braceEscape(c + '-')); + i += 2; + continue; } - this.nocase = this.scurry.nocase; - // If you do nocase:true on a case-sensitive file system, then - // we need to use regexps instead of strings for non-magic - // path portions, because statting `aBc` won't return results - // for the file `AbC` for example. - const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32'; - const mmo = { - // default nocase based on platform - ...opts, - dot: this.dot, - matchBase: this.matchBase, - nobrace: this.nobrace, - nocase: this.nocase, - nocaseMagicOnly, - nocomment: true, - noext: this.noext, - nonegate: true, - optimizationLevel: 2, - platform: this.platform, - windowsPathsNoEscape: this.windowsPathsNoEscape, - debug: !!this.opts.debug, - }; - const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo)); - const [matchSet, globParts] = mms.reduce((set, m) => { - set[0].push(...m.set); - set[1].push(...m.globParts); - return set; - }, [[], []]); - this.patterns = matchSet.map((set, i) => { - const g = globParts[i]; - /* c8 ignore start */ - if (!g) - throw new Error('invalid pattern object'); - /* c8 ignore stop */ - return new pattern_js_1.Pattern(set, g, 0, this.platform); - }); - } - async walk() { - // Walkers always return array of Path objects, so we just have to - // coerce them into the right shape. It will have already called - // realpath() if the option was set to do so, so we know that's cached. - // start out knowing the cwd, at least - return [ - ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { - ...this.opts, - maxDepth: this.maxDepth !== Infinity ? - this.maxDepth + this.scurry.cwd.depth() - : Infinity, - platform: this.platform, - nocase: this.nocase, - includeChildMatches: this.includeChildMatches, - }).walk()), - ]; - } - walkSync() { - return [ - ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, { - ...this.opts, - maxDepth: this.maxDepth !== Infinity ? - this.maxDepth + this.scurry.cwd.depth() - : Infinity, - platform: this.platform, - nocase: this.nocase, - includeChildMatches: this.includeChildMatches, - }).walkSync(), - ]; - } - stream() { - return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { - ...this.opts, - maxDepth: this.maxDepth !== Infinity ? - this.maxDepth + this.scurry.cwd.depth() - : Infinity, - platform: this.platform, - nocase: this.nocase, - includeChildMatches: this.includeChildMatches, - }).stream(); - } - streamSync() { - return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, { - ...this.opts, - maxDepth: this.maxDepth !== Infinity ? - this.maxDepth + this.scurry.cwd.depth() - : Infinity, - platform: this.platform, - nocase: this.nocase, - includeChildMatches: this.includeChildMatches, - }).streamSync(); - } - /** - * Default sync iteration function. Returns a Generator that - * iterates over the results. - */ - iterateSync() { - return this.streamSync()[Symbol.iterator](); + if (glob.startsWith('-', i + 1)) { + rangeStart = c; + i += 2; + continue; + } + // not the start of a range, just a single character + ranges.push(braceEscape(c)); + i++; } - [Symbol.iterator]() { - return this.iterateSync(); + if (endPos < i) { + // didn't see the end of the class, not a valid class, + // but might still be valid as a literal match. + return ['', false, 0, false]; } - /** - * Default async iteration function. Returns an AsyncGenerator that - * iterates over the results. - */ - iterate() { - return this.stream()[Symbol.asyncIterator](); + // if we got no ranges and no negates, then we have a range that + // cannot possibly match anything, and that poisons the whole glob + if (!ranges.length && !negs.length) { + return ['$.', false, glob.length - pos, true]; } - [Symbol.asyncIterator]() { - return this.iterate(); + // if we got one positive range, and it's a single character, then that's + // not actually a magic pattern, it's just that one literal character. + // we should not treat that as "magic", we should just return the literal + // character. [_] is a perfectly valid way to escape glob magic chars. + if (negs.length === 0 && + ranges.length === 1 && + /^\\?.$/.test(ranges[0]) && + !negate) { + const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; + return [regexpEscape(r), false, endPos - pos, false]; } -} -exports.Glob = Glob; -//# sourceMappingURL=glob.js.map + const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'; + const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'; + const comb = ranges.length && negs.length + ? '(' + sranges + '|' + snegs + ')' + : ranges.length + ? sranges + : snegs; + return [comb, uflag, endPos - pos, true]; +}; +exports.parseClass = parseClass; +//# sourceMappingURL=brace-expressions.js.map /***/ }), -/***/ 66889: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4578: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.hasMagic = void 0; -const minimatch_1 = __nccwpck_require__(85207); +exports.escape = void 0; /** - * Return true if the patterns provided contain any magic glob characters, - * given the options provided. + * Escape all magic characters in a glob pattern. * - * Brace expansion is not considered "magic" unless the `magicalBraces` option - * is set, as brace expansion just turns one string into an array of strings. - * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and - * `'xby'` both do not contain any magic glob characters, and it's treated the - * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true` - * is in the options, brace expansion _is_ treated as a pattern having magic. + * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape} + * option is used, then characters are escaped by wrapping in `[]`, because + * a magic character wrapped in a character class can only be satisfied by + * that exact character. In this mode, `\` is _not_ escaped, because it is + * not interpreted as a magic character, but instead as a path separator. */ -const hasMagic = (pattern, options = {}) => { - if (!Array.isArray(pattern)) { - pattern = [pattern]; - } - for (const p of pattern) { - if (new minimatch_1.Minimatch(p, options).hasMagic()) - return true; - } - return false; +const escape = (s, { windowsPathsNoEscape = false, } = {}) => { + // don't need to escape +@! because we escape the parens + // that make those magic, and escaping ! as [!] isn't valid, + // because [!]] is a valid glob class meaning not ']'. + return windowsPathsNoEscape + ? s.replace(/[?*()[\]]/g, '[$&]') + : s.replace(/[?*()[\]\\]/g, '\\$&'); }; -exports.hasMagic = hasMagic; -//# sourceMappingURL=has-magic.js.map +exports.escape = escape; +//# sourceMappingURL=escape.js.map /***/ }), -/***/ 4833: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 45613: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -// give it a pattern, and it'll be able to tell you if -// a given path should be ignored. -// Ignoring a path ignores its children if the pattern ends in /** -// Ignores are always parsed in dot:true mode +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Ignore = void 0; -const minimatch_1 = __nccwpck_require__(85207); -const pattern_js_1 = __nccwpck_require__(4041); -const defaultPlatform = (typeof process === 'object' && - process && - typeof process.platform === 'string') ? - process.platform - : 'linux'; -/** - * Class used to process ignored patterns - */ -class Ignore { - relative; - relativeChildren; - absolute; - absoluteChildren; - platform; - mmopts; - constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) { - this.relative = []; - this.absolute = []; - this.relativeChildren = []; - this.absoluteChildren = []; - this.platform = platform; - this.mmopts = { - dot: true, - nobrace, - nocase, - noext, - noglobstar, - optimizationLevel: 2, - platform, - nocomment: true, - nonegate: true, - }; - for (const ign of ignored) - this.add(ign); +exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; +const brace_expansion_1 = __importDefault(__nccwpck_require__(66723)); +const assert_valid_pattern_js_1 = __nccwpck_require__(33555); +const ast_js_1 = __nccwpck_require__(10421); +const escape_js_1 = __nccwpck_require__(4578); +const unescape_js_1 = __nccwpck_require__(11633); +const minimatch = (p, pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false; } - add(ign) { - // this is a little weird, but it gives us a clean set of optimized - // minimatch matchers, without getting tripped up if one of them - // ends in /** inside a brace section, and it's only inefficient at - // the start of the walk, not along it. - // It'd be nice if the Pattern class just had a .test() method, but - // handling globstars is a bit of a pita, and that code already lives - // in minimatch anyway. - // Another way would be if maybe Minimatch could take its set/globParts - // as an option, and then we could at least just use Pattern to test - // for absolute-ness. - // Yet another way, Minimatch could take an array of glob strings, and - // a cwd option, and do the right thing. - const mm = new minimatch_1.Minimatch(ign, this.mmopts); - for (let i = 0; i < mm.set.length; i++) { - const parsed = mm.set[i]; - const globParts = mm.globParts[i]; - /* c8 ignore start */ - if (!parsed || !globParts) { - throw new Error('invalid pattern object'); + return new Minimatch(pattern, options).match(p); +}; +exports.minimatch = minimatch; +// Optimized checking for the most common glob patterns. +const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); +const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); +const starDotExtTestNocase = (ext) => { + ext = ext.toLowerCase(); + return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); +}; +const starDotExtTestNocaseDot = (ext) => { + ext = ext.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext); +}; +const starDotStarRE = /^\*+\.\*+$/; +const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); +const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); +const dotStarRE = /^\.\*+$/; +const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); +const starRE = /^\*+$/; +const starTest = (f) => f.length !== 0 && !f.startsWith('.'); +const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; +const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; +const qmarksTestNocase = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestNocaseDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTest = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith('.'); +}; +const qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== '.' && f !== '..'; +}; +/* c8 ignore start */ +const defaultPlatform = (typeof process === 'object' && process + ? (typeof process.env === 'object' && + process.env && + process.env.__MINIMATCH_TESTING_PLATFORM__) || + process.platform + : 'posix'); +const path = { + win32: { sep: '\\' }, + posix: { sep: '/' }, +}; +/* c8 ignore stop */ +exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep; +exports.minimatch.sep = exports.sep; +exports.GLOBSTAR = Symbol('globstar **'); +exports.minimatch.GLOBSTAR = exports.GLOBSTAR; +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; +const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); +exports.filter = filter; +exports.minimatch.filter = exports.filter; +const ext = (a, b = {}) => Object.assign({}, a, b); +const defaults = (def) => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return exports.minimatch; + } + const orig = exports.minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); } - // strip off leading ./ portions - // https://github.com/isaacs/node-glob/issues/570 - while (parsed[0] === '.' && globParts[0] === '.') { - parsed.shift(); - globParts.shift(); + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + AST: class AST extends orig.AST { + /* c8 ignore start */ + constructor(type, parent, options = {}) { + super(type, parent, ext(def, options)); } /* c8 ignore stop */ - const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform); - const m = new minimatch_1.Minimatch(p.globString(), this.mmopts); - const children = globParts[globParts.length - 1] === '**'; - const absolute = p.isAbsolute(); - if (absolute) - this.absolute.push(m); - else - this.relative.push(m); - if (children) { - if (absolute) - this.absoluteChildren.push(m); - else - this.relativeChildren.push(m); + static fromGlob(pattern, options = {}) { + return orig.AST.fromGlob(pattern, ext(def, options)); } - } + }, + unescape: (s, options = {}) => orig.unescape(s, ext(def, options)), + escape: (s, options = {}) => orig.escape(s, ext(def, options)), + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR: exports.GLOBSTAR, + }); +}; +exports.defaults = defaults; +exports.minimatch.defaults = exports.defaults; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +const braceExpand = (pattern, options = {}) => { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern]; } - ignored(p) { - const fullpath = p.fullpath(); - const fullpaths = `${fullpath}/`; - const relative = p.relative() || '.'; - const relatives = `${relative}/`; - for (const m of this.relative) { - if (m.match(relative) || m.match(relatives)) - return true; - } - for (const m of this.absolute) { - if (m.match(fullpath) || m.match(fullpaths)) - return true; + return (0, brace_expansion_1.default)(pattern); +}; +exports.braceExpand = braceExpand; +exports.minimatch.braceExpand = exports.braceExpand; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); +exports.makeRe = makeRe; +exports.minimatch.makeRe = exports.makeRe; +const match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; +}; +exports.match = match; +exports.minimatch.match = exports.match; +// replace stuff like \* with * +const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +class Minimatch { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + nocase; + isWindows; + platform; + windowsNoMagicRoot; + regexp; + constructor(pattern, options = {}) { + (0, assert_valid_pattern_js_1.assertValidPattern)(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.platform = options.platform || defaultPlatform; + this.isWindows = this.platform === 'win32'; + this.windowsPathsNoEscape = + !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); } - return false; + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.nocase = !!this.options.nocase; + this.windowsNoMagicRoot = + options.windowsNoMagicRoot !== undefined + ? options.windowsNoMagicRoot + : !!(this.isWindows && this.nocase); + this.globSet = []; + this.globParts = []; + this.set = []; + // make the set of regexps etc. + this.make(); } - childrenIgnored(p) { - const fullpath = p.fullpath() + '/'; - const relative = (p.relative() || '.') + '/'; - for (const m of this.relativeChildren) { - if (m.match(relative)) - return true; + hasMagic() { + if (this.options.magicalBraces && this.set.length > 1) { + return true; } - for (const m of this.absoluteChildren) { - if (m.match(fullpath)) - return true; + for (const pattern of this.set) { + for (const part of pattern) { + if (typeof part !== 'string') + return true; + } } return false; } -} -exports.Ignore = Ignore; -//# sourceMappingURL=ignore.js.map - -/***/ }), - -/***/ 67471: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0; -exports.globStreamSync = globStreamSync; -exports.globStream = globStream; -exports.globSync = globSync; -exports.globIterateSync = globIterateSync; -exports.globIterate = globIterate; -const minimatch_1 = __nccwpck_require__(85207); -const glob_js_1 = __nccwpck_require__(81017); -const has_magic_js_1 = __nccwpck_require__(66889); -var minimatch_2 = __nccwpck_require__(85207); -Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return minimatch_2.escape; } })); -Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return minimatch_2.unescape; } })); -var glob_js_2 = __nccwpck_require__(81017); -Object.defineProperty(exports, "Glob", ({ enumerable: true, get: function () { return glob_js_2.Glob; } })); -var has_magic_js_2 = __nccwpck_require__(66889); -Object.defineProperty(exports, "hasMagic", ({ enumerable: true, get: function () { return has_magic_js_2.hasMagic; } })); -var ignore_js_1 = __nccwpck_require__(4833); -Object.defineProperty(exports, "Ignore", ({ enumerable: true, get: function () { return ignore_js_1.Ignore; } })); -function globStreamSync(pattern, options = {}) { - return new glob_js_1.Glob(pattern, options).streamSync(); -} -function globStream(pattern, options = {}) { - return new glob_js_1.Glob(pattern, options).stream(); -} -function globSync(pattern, options = {}) { - return new glob_js_1.Glob(pattern, options).walkSync(); -} -async function glob_(pattern, options = {}) { - return new glob_js_1.Glob(pattern, options).walk(); -} -function globIterateSync(pattern, options = {}) { - return new glob_js_1.Glob(pattern, options).iterateSync(); -} -function globIterate(pattern, options = {}) { - return new glob_js_1.Glob(pattern, options).iterate(); -} -// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc -exports.streamSync = globStreamSync; -exports.stream = Object.assign(globStream, { sync: globStreamSync }); -exports.iterateSync = globIterateSync; -exports.iterate = Object.assign(globIterate, { - sync: globIterateSync, -}); -exports.sync = Object.assign(globSync, { - stream: globStreamSync, - iterate: globIterateSync, -}); -exports.glob = Object.assign(glob_, { - glob: glob_, - globSync, - sync: exports.sync, - globStream, - stream: exports.stream, - globStreamSync, - streamSync: exports.streamSync, - globIterate, - iterate: exports.iterate, - globIterateSync, - iterateSync: exports.iterateSync, - Glob: glob_js_1.Glob, - hasMagic: has_magic_js_1.hasMagic, - escape: minimatch_1.escape, - unescape: minimatch_1.unescape, -}); -exports.glob.glob = exports.glob; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 4041: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -// this is just a very light wrapper around 2 arrays with an offset index -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Pattern = void 0; -const minimatch_1 = __nccwpck_require__(85207); -const isPatternList = (pl) => pl.length >= 1; -const isGlobList = (gl) => gl.length >= 1; -/** - * An immutable-ish view on an array of glob parts and their parsed - * results - */ -class Pattern { - #patternList; - #globList; - #index; - length; - #platform; - #rest; - #globString; - #isDrive; - #isUNC; - #isAbsolute; - #followGlobstar = true; - constructor(patternList, globList, index, platform) { - if (!isPatternList(patternList)) { - throw new TypeError('empty pattern list'); - } - if (!isGlobList(globList)) { - throw new TypeError('empty glob list'); + debug(..._) { } + make() { + const pattern = this.pattern; + const options = this.options; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return; } - if (globList.length !== patternList.length) { - throw new TypeError('mismatched pattern list and glob list lengths'); + if (!pattern) { + this.empty = true; + return; } - this.length = patternList.length; - if (index < 0 || index >= this.length) { - throw new TypeError('index out of range'); + // step 1: figure out negation, etc. + this.parseNegate(); + // step 2: expand braces + this.globSet = [...new Set(this.braceExpand())]; + if (options.debug) { + this.debug = (...args) => console.error(...args); } - this.#patternList = patternList; - this.#globList = globList; - this.#index = index; - this.#platform = platform; - // normalize root entries of absolute patterns on initial creation. - if (this.#index === 0) { - // c: => ['c:/'] - // C:/ => ['C:/'] - // C:/x => ['C:/', 'x'] - // //host/share => ['//host/share/'] - // //host/share/ => ['//host/share/'] - // //host/share/x => ['//host/share/', 'x'] - // /etc => ['/', 'etc'] - // / => ['/'] - if (this.isUNC()) { - // '' / '' / 'host' / 'share' - const [p0, p1, p2, p3, ...prest] = this.#patternList; - const [g0, g1, g2, g3, ...grest] = this.#globList; - if (prest[0] === '') { - // ends in / - prest.shift(); - grest.shift(); + this.debug(this.pattern, this.globSet); + // step 3: now we have a set, so turn each one into a series of + // path-portion matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + // + // First, we preprocess to make the glob pattern sets a bit simpler + // and deduped. There are some perf-killing patterns that can cause + // problems with a glob walk, but we can simplify them down a bit. + const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); + this.globParts = this.preprocess(rawGlobParts); + this.debug(this.pattern, this.globParts); + // glob --> regexps + let set = this.globParts.map((s, _, __) => { + if (this.isWindows && this.windowsNoMagicRoot) { + // check if it's a drive or unc path. + const isUNC = s[0] === '' && + s[1] === '' && + (s[2] === '?' || !globMagic.test(s[2])) && + !globMagic.test(s[3]); + const isDrive = /^[a-z]:/i.test(s[0]); + if (isUNC) { + return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]; + } + else if (isDrive) { + return [s[0], ...s.slice(1).map(ss => this.parse(ss))]; } - const p = [p0, p1, p2, p3, ''].join('/'); - const g = [g0, g1, g2, g3, ''].join('/'); - this.#patternList = [p, ...prest]; - this.#globList = [g, ...grest]; - this.length = this.#patternList.length; } - else if (this.isDrive() || this.isAbsolute()) { - const [p1, ...prest] = this.#patternList; - const [g1, ...grest] = this.#globList; - if (prest[0] === '') { - // ends in / - prest.shift(); - grest.shift(); + return s.map(ss => this.parse(ss)); + }); + this.debug(this.pattern, set); + // filter out everything that didn't compile properly. + this.set = set.filter(s => s.indexOf(false) === -1); + // do not treat the ? in UNC paths as magic + if (this.isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === '' && + p[1] === '' && + this.globParts[i][2] === '?' && + typeof p[3] === 'string' && + /^[a-z]:$/i.test(p[3])) { + p[2] = '?'; } - const p = p1 + '/'; - const g = g1 + '/'; - this.#patternList = [p, ...prest]; - this.#globList = [g, ...grest]; - this.length = this.#patternList.length; } } + this.debug(this.pattern, this.set); } - /** - * The first entry in the parsed list of patterns - */ - pattern() { - return this.#patternList[this.#index]; - } - /** - * true of if pattern() returns a string - */ - isString() { - return typeof this.#patternList[this.#index] === 'string'; - } - /** - * true of if pattern() returns GLOBSTAR - */ - isGlobstar() { - return this.#patternList[this.#index] === minimatch_1.GLOBSTAR; - } - /** - * true if pattern() returns a regexp - */ - isRegExp() { - return this.#patternList[this.#index] instanceof RegExp; - } - /** - * The /-joined set of glob parts that make up this pattern - */ - globString() { - return (this.#globString = - this.#globString || - (this.#index === 0 ? - this.isAbsolute() ? - this.#globList[0] + this.#globList.slice(1).join('/') - : this.#globList.join('/') - : this.#globList.slice(this.#index).join('/'))); - } - /** - * true if there are more pattern parts after this one - */ - hasMore() { - return this.length > this.#index + 1; - } - /** - * The rest of the pattern after this part, or null if this is the end - */ - rest() { - if (this.#rest !== undefined) - return this.#rest; - if (!this.hasMore()) - return (this.#rest = null); - this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform); - this.#rest.#isAbsolute = this.#isAbsolute; - this.#rest.#isUNC = this.#isUNC; - this.#rest.#isDrive = this.#isDrive; - return this.#rest; - } - /** - * true if the pattern represents a //unc/path/ on windows - */ - isUNC() { - const pl = this.#patternList; - return this.#isUNC !== undefined ? - this.#isUNC - : (this.#isUNC = - this.#platform === 'win32' && - this.#index === 0 && - pl[0] === '' && - pl[1] === '' && - typeof pl[2] === 'string' && - !!pl[2] && - typeof pl[3] === 'string' && - !!pl[3]); - } - // pattern like C:/... - // split = ['C:', ...] - // XXX: would be nice to handle patterns like `c:*` to test the cwd - // in c: for *, but I don't know of a way to even figure out what that - // cwd is without actually chdir'ing into it? - /** - * True if the pattern starts with a drive letter on Windows - */ - isDrive() { - const pl = this.#patternList; - return this.#isDrive !== undefined ? - this.#isDrive - : (this.#isDrive = - this.#platform === 'win32' && - this.#index === 0 && - this.length > 1 && - typeof pl[0] === 'string' && - /^[a-z]:$/i.test(pl[0])); - } - // pattern = '/' or '/...' or '/x/...' - // split = ['', ''] or ['', ...] or ['', 'x', ...] - // Drive and UNC both considered absolute on windows - /** - * True if the pattern is rooted on an absolute path - */ - isAbsolute() { - const pl = this.#patternList; - return this.#isAbsolute !== undefined ? - this.#isAbsolute - : (this.#isAbsolute = - (pl[0] === '' && pl.length > 1) || - this.isDrive() || - this.isUNC()); - } - /** - * consume the root of the pattern, and return it - */ - root() { - const p = this.#patternList[0]; - return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ? - p - : ''; - } - /** - * Check to see if the current globstar pattern is allowed to follow - * a symbolic link. - */ - checkFollowGlobstar() { - return !(this.#index === 0 || - !this.isGlobstar() || - !this.#followGlobstar); - } - /** - * Mark that the current globstar pattern is following a symbolic link - */ - markFollowGlobstar() { - if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar) - return false; - this.#followGlobstar = false; - return true; - } -} -exports.Pattern = Pattern; -//# sourceMappingURL=pattern.js.map - -/***/ }), - -/***/ 48095: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -// synchronous utility for filtering entries and calculating subwalks -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0; -const minimatch_1 = __nccwpck_require__(85207); -/** - * A cache of which patterns have been processed for a given Path - */ -class HasWalkedCache { - store; - constructor(store = new Map()) { - this.store = store; - } - copy() { - return new HasWalkedCache(new Map(this.store)); - } - hasWalked(target, pattern) { - return this.store.get(target.fullpath())?.has(pattern.globString()); - } - storeWalked(target, pattern) { - const fullpath = target.fullpath(); - const cached = this.store.get(fullpath); - if (cached) - cached.add(pattern.globString()); - else - this.store.set(fullpath, new Set([pattern.globString()])); - } -} -exports.HasWalkedCache = HasWalkedCache; -/** - * A record of which paths have been matched in a given walk step, - * and whether they only are considered a match if they are a directory, - * and whether their absolute or relative path should be returned. - */ -class MatchRecord { - store = new Map(); - add(target, absolute, ifDir) { - const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0); - const current = this.store.get(target); - this.store.set(target, current === undefined ? n : n & current); - } - // match, absolute, ifdir - entries() { - return [...this.store.entries()].map(([path, n]) => [ - path, - !!(n & 2), - !!(n & 1), - ]); - } -} -exports.MatchRecord = MatchRecord; -/** - * A collection of patterns that must be processed in a subsequent step - * for a given path. - */ -class SubWalks { - store = new Map(); - add(target, pattern) { - if (!target.canReaddir()) { - return; - } - const subs = this.store.get(target); - if (subs) { - if (!subs.find(p => p.globString() === pattern.globString())) { - subs.push(pattern); + // various transforms to equivalent pattern sets that are + // faster to process in a filesystem walk. The goal is to + // eliminate what we can, and push all ** patterns as far + // to the right as possible, even if it increases the number + // of patterns that we have to process. + preprocess(globParts) { + // if we're not in globstar mode, then turn all ** into * + if (this.options.noglobstar) { + for (let i = 0; i < globParts.length; i++) { + for (let j = 0; j < globParts[i].length; j++) { + if (globParts[i][j] === '**') { + globParts[i][j] = '*'; + } + } } } - else - this.store.set(target, [pattern]); - } - get(target) { - const subs = this.store.get(target); - /* c8 ignore start */ - if (!subs) { - throw new Error('attempting to walk unknown path'); + const { optimizationLevel = 1 } = this.options; + if (optimizationLevel >= 2) { + // aggressive optimization for the purpose of fs walking + globParts = this.firstPhasePreProcess(globParts); + globParts = this.secondPhasePreProcess(globParts); } - /* c8 ignore stop */ - return subs; - } - entries() { - return this.keys().map(k => [k, this.store.get(k)]); + else if (optimizationLevel >= 1) { + // just basic optimizations to remove some .. parts + globParts = this.levelOneOptimize(globParts); + } + else { + // just collapse multiple ** portions into one + globParts = this.adjascentGlobstarOptimize(globParts); + } + return globParts; } - keys() { - return [...this.store.keys()].filter(t => t.canReaddir()); + // just get rid of adjascent ** portions + adjascentGlobstarOptimize(globParts) { + return globParts.map(parts => { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let i = gs; + while (parts[i + 1] === '**') { + i++; + } + if (i !== gs) { + parts.splice(gs, i - gs); + } + } + return parts; + }); } -} -exports.SubWalks = SubWalks; -/** - * The class that processes patterns for a given path. - * - * Handles child entry filtering, and determining whether a path's - * directory contents must be read. - */ -class Processor { - hasWalkedCache; - matches = new MatchRecord(); - subwalks = new SubWalks(); - patterns; - follow; - dot; - opts; - constructor(opts, hasWalkedCache) { - this.opts = opts; - this.follow = !!opts.follow; - this.dot = !!opts.dot; - this.hasWalkedCache = - hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache(); + // get rid of adjascent ** and resolve .. portions + levelOneOptimize(globParts) { + return globParts.map(parts => { + parts = parts.reduce((set, part) => { + const prev = set[set.length - 1]; + if (part === '**' && prev === '**') { + return set; + } + if (part === '..') { + if (prev && prev !== '..' && prev !== '.' && prev !== '**') { + set.pop(); + return set; + } + } + set.push(part); + return set; + }, []); + return parts.length === 0 ? [''] : parts; + }); } - processPatterns(target, patterns) { - this.patterns = patterns; - const processingSet = patterns.map(p => [target, p]); - // map of paths to the magic-starting subwalks they need to walk - // first item in patterns is the filter - for (let [t, pattern] of processingSet) { - this.hasWalkedCache.storeWalked(t, pattern); - const root = pattern.root(); - const absolute = pattern.isAbsolute() && this.opts.absolute !== false; - // start absolute patterns at root - if (root) { - t = t.resolve(root === '/' && this.opts.root !== undefined ? - this.opts.root - : root); - const rest = pattern.rest(); - if (!rest) { - this.matches.add(t, true, false); - continue; + levelTwoFileOptimize(parts) { + if (!Array.isArray(parts)) { + parts = this.slashSplit(parts); + } + let didSomething = false; + do { + didSomething = false; + //
// -> 
/
+            if (!this.preserveMultipleSlashes) {
+                for (let i = 1; i < parts.length - 1; i++) {
+                    const p = parts[i];
+                    // don't squeeze out UNC patterns
+                    if (i === 1 && p === '' && parts[0] === '')
+                        continue;
+                    if (p === '.' || p === '') {
+                        didSomething = true;
+                        parts.splice(i, 1);
+                        i--;
+                    }
                 }
-                else {
-                    pattern = rest;
+                if (parts[0] === '.' &&
+                    parts.length === 2 &&
+                    (parts[1] === '.' || parts[1] === '')) {
+                    didSomething = true;
+                    parts.pop();
                 }
             }
-            if (t.isENOENT())
-                continue;
-            let p;
-            let rest;
-            let changed = false;
-            while (typeof (p = pattern.pattern()) === 'string' &&
-                (rest = pattern.rest())) {
-                const c = t.resolve(p);
-                t = c;
-                pattern = rest;
-                changed = true;
-            }
-            p = pattern.pattern();
-            rest = pattern.rest();
-            if (changed) {
-                if (this.hasWalkedCache.hasWalked(t, pattern))
-                    continue;
-                this.hasWalkedCache.storeWalked(t, pattern);
-            }
-            // now we have either a final string for a known entry,
-            // more strings for an unknown entry,
-            // or a pattern starting with magic, mounted on t.
-            if (typeof p === 'string') {
-                // must not be final entry, otherwise we would have
-                // concatenated it earlier.
-                const ifDir = p === '..' || p === '' || p === '.';
-                this.matches.add(t.resolve(p), absolute, ifDir);
-                continue;
-            }
-            else if (p === minimatch_1.GLOBSTAR) {
-                // if no rest, match and subwalk pattern
-                // if rest, process rest and subwalk pattern
-                // if it's a symlink, but we didn't get here by way of a
-                // globstar match (meaning it's the first time THIS globstar
-                // has traversed a symlink), then we follow it. Otherwise, stop.
-                if (!t.isSymbolicLink() ||
-                    this.follow ||
-                    pattern.checkFollowGlobstar()) {
-                    this.subwalks.add(t, pattern);
+            // 
/

/../ ->

/
+            let dd = 0;
+            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                const p = parts[dd - 1];
+                if (p && p !== '.' && p !== '..' && p !== '**') {
+                    didSomething = true;
+                    parts.splice(dd - 1, 2);
+                    dd -= 2;
                 }
-                const rp = rest?.pattern();
-                const rrest = rest?.rest();
-                if (!rest || ((rp === '' || rp === '.') && !rrest)) {
-                    // only HAS to be a dir if it ends in **/ or **/.
-                    // but ending in ** will match files as well.
-                    this.matches.add(t, absolute, rp === '' || rp === '.');
+            }
+        } while (didSomething);
+        return parts.length === 0 ? [''] : parts;
+    }
+    // First phase: single-pattern processing
+    // 
 is 1 or more portions
+    //  is 1 or more portions
+    // 

is any portion other than ., .., '', or ** + // is . or '' + // + // **/.. is *brutal* for filesystem walking performance, because + // it effectively resets the recursive walk each time it occurs, + // and ** cannot be reduced out by a .. pattern part like a regexp + // or most strings (other than .., ., and '') can be. + // + //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+    // 
/

/../ ->

/
+    // **/**/ -> **/
+    //
+    // **/*/ -> */**/ <== not valid because ** doesn't follow
+    // this WOULD be allowed if ** did follow symlinks, or * didn't
+    firstPhasePreProcess(globParts) {
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + for (let parts of globParts) { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let gss = gs; + while (parts[gss + 1] === '**') { + //

/**/**/ -> 
/**/
+                        gss++;
+                    }
+                    // eg, if gs is 2 and gss is 4, that means we have 3 **
+                    // parts, and can remove 2 of them.
+                    if (gss > gs) {
+                        parts.splice(gs + 1, gss - gs);
+                    }
+                    let next = parts[gs + 1];
+                    const p = parts[gs + 2];
+                    const p2 = parts[gs + 3];
+                    if (next !== '..')
+                        continue;
+                    if (!p ||
+                        p === '.' ||
+                        p === '..' ||
+                        !p2 ||
+                        p2 === '.' ||
+                        p2 === '..') {
+                        continue;
+                    }
+                    didSomething = true;
+                    // edit parts in place, and push the new one
+                    parts.splice(gs, 1);
+                    const other = parts.slice(0);
+                    other[gs] = '**';
+                    globParts.push(other);
+                    gs--;
                 }
-                else {
-                    if (rp === '..') {
-                        // this would mean you're matching **/.. at the fs root,
-                        // and no thanks, I'm not gonna test that specific case.
-                        /* c8 ignore start */
-                        const tp = t.parent || t;
-                        /* c8 ignore stop */
-                        if (!rrest)
-                            this.matches.add(tp, absolute, true);
-                        else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
-                            this.subwalks.add(tp, rrest);
+                // 
// -> 
/
+                if (!this.preserveMultipleSlashes) {
+                    for (let i = 1; i < parts.length - 1; i++) {
+                        const p = parts[i];
+                        // don't squeeze out UNC patterns
+                        if (i === 1 && p === '' && parts[0] === '')
+                            continue;
+                        if (p === '.' || p === '') {
+                            didSomething = true;
+                            parts.splice(i, 1);
+                            i--;
                         }
                     }
+                    if (parts[0] === '.' &&
+                        parts.length === 2 &&
+                        (parts[1] === '.' || parts[1] === '')) {
+                        didSomething = true;
+                        parts.pop();
+                    }
+                }
+                // 
/

/../ ->

/
+                let dd = 0;
+                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                    const p = parts[dd - 1];
+                    if (p && p !== '.' && p !== '..' && p !== '**') {
+                        didSomething = true;
+                        const needDot = dd === 1 && parts[dd + 1] === '**';
+                        const splin = needDot ? ['.'] : [];
+                        parts.splice(dd - 1, 2, ...splin);
+                        if (parts.length === 0)
+                            parts.push('');
+                        dd -= 2;
+                    }
                 }
             }
-            else if (p instanceof RegExp) {
-                this.subwalks.add(t, pattern);
-            }
-        }
-        return this;
-    }
-    subwalkTargets() {
-        return this.subwalks.keys();
-    }
-    child() {
-        return new Processor(this.opts, this.hasWalkedCache);
+        } while (didSomething);
+        return globParts;
     }
-    // return a new Processor containing the subwalks for each
-    // child entry, and a set of matches, and
-    // a hasWalkedCache that's a copy of this one
-    // then we're going to call
-    filterEntries(parent, entries) {
-        const patterns = this.subwalks.get(parent);
-        // put matches and entry walks into the results processor
-        const results = this.child();
-        for (const e of entries) {
-            for (const pattern of patterns) {
-                const absolute = pattern.isAbsolute();
-                const p = pattern.pattern();
-                const rest = pattern.rest();
-                if (p === minimatch_1.GLOBSTAR) {
-                    results.testGlobstar(e, pattern, rest, absolute);
-                }
-                else if (p instanceof RegExp) {
-                    results.testRegExp(e, p, rest, absolute);
-                }
-                else {
-                    results.testString(e, p, rest, absolute);
+    // second phase: multi-pattern dedupes
+    // {
/*/,
/

/} ->

/*/
+    // {
/,
/} -> 
/
+    // {
/**/,
/} -> 
/**/
+    //
+    // {
/**/,
/**/

/} ->

/**/
+    // ^-- not valid because ** doens't follow symlinks
+    secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+            for (let j = i + 1; j < globParts.length; j++) {
+                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+                if (matched) {
+                    globParts[i] = [];
+                    globParts[j] = matched;
+                    break;
                 }
             }
         }
-        return results;
+        return globParts.filter(gs => gs.length);
     }
-    testGlobstar(e, pattern, rest, absolute) {
-        if (this.dot || !e.name.startsWith('.')) {
-            if (!pattern.hasMore()) {
-                this.matches.add(e, absolute, false);
+    partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which = '';
+        while (ai < a.length && bi < b.length) {
+            if (a[ai] === b[bi]) {
+                result.push(which === 'b' ? b[bi] : a[ai]);
+                ai++;
+                bi++;
             }
-            if (e.canReaddir()) {
-                // if we're in follow mode or it's not a symlink, just keep
-                // testing the same pattern. If there's more after the globstar,
-                // then this symlink consumes the globstar. If not, then we can
-                // follow at most ONE symlink along the way, so we mark it, which
-                // also checks to ensure that it wasn't already marked.
-                if (this.follow || !e.isSymbolicLink()) {
-                    this.subwalks.add(e, pattern);
-                }
-                else if (e.isSymbolicLink()) {
-                    if (rest && pattern.checkFollowGlobstar()) {
-                        this.subwalks.add(e, rest);
-                    }
-                    else if (pattern.markFollowGlobstar()) {
-                        this.subwalks.add(e, pattern);
-                    }
-                }
+            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
+                result.push(a[ai]);
+                ai++;
             }
-        }
-        // if the NEXT thing matches this entry, then also add
-        // the rest.
-        if (rest) {
-            const rp = rest.pattern();
-            if (typeof rp === 'string' &&
-                // dots and empty were handled already
-                rp !== '..' &&
-                rp !== '' &&
-                rp !== '.') {
-                this.testString(e, rp, rest.rest(), absolute);
+            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
+                result.push(b[bi]);
+                bi++;
             }
-            else if (rp === '..') {
-                /* c8 ignore start */
-                const ep = e.parent || e;
-                /* c8 ignore stop */
-                this.subwalks.add(ep, rest);
+            else if (a[ai] === '*' &&
+                b[bi] &&
+                (this.options.dot || !b[bi].startsWith('.')) &&
+                b[bi] !== '**') {
+                if (which === 'b')
+                    return false;
+                which = 'a';
+                result.push(a[ai]);
+                ai++;
+                bi++;
             }
-            else if (rp instanceof RegExp) {
-                this.testRegExp(e, rp, rest.rest(), absolute);
+            else if (b[bi] === '*' &&
+                a[ai] &&
+                (this.options.dot || !a[ai].startsWith('.')) &&
+                a[ai] !== '**') {
+                if (which === 'a')
+                    return false;
+                which = 'b';
+                result.push(b[bi]);
+                ai++;
+                bi++;
             }
-        }
-    }
-    testRegExp(e, p, rest, absolute) {
-        if (!p.test(e.name))
-            return;
-        if (!rest) {
-            this.matches.add(e, absolute, false);
-        }
-        else {
-            this.subwalks.add(e, rest);
-        }
-    }
-    testString(e, p, rest, absolute) {
-        // should never happen?
-        if (!e.isNamed(p))
-            return;
-        if (!rest) {
-            this.matches.add(e, absolute, false);
-        }
-        else {
-            this.subwalks.add(e, rest);
-        }
-    }
-}
-exports.Processor = Processor;
-//# sourceMappingURL=processor.js.map
-
-/***/ }),
-
-/***/ 95049:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0;
-/**
- * Single-use utility classes to provide functionality to the {@link Glob}
- * methods.
- *
- * @module
- */
-const minipass_1 = __nccwpck_require__(78275);
-const ignore_js_1 = __nccwpck_require__(4833);
-const processor_js_1 = __nccwpck_require__(48095);
-const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts)
-    : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts)
-        : ignore;
-/**
- * basic walking utilities that all the glob walker types use
- */
-class GlobUtil {
-    path;
-    patterns;
-    opts;
-    seen = new Set();
-    paused = false;
-    aborted = false;
-    #onResume = [];
-    #ignore;
-    #sep;
-    signal;
-    maxDepth;
-    includeChildMatches;
-    constructor(patterns, path, opts) {
-        this.patterns = patterns;
-        this.path = path;
-        this.opts = opts;
-        this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
-        this.includeChildMatches = opts.includeChildMatches !== false;
-        if (opts.ignore || !this.includeChildMatches) {
-            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
-            if (!this.includeChildMatches &&
-                typeof this.#ignore.add !== 'function') {
-                const m = 'cannot ignore child matches, ignore lacks add() method.';
-                throw new Error(m);
+            else {
+                return false;
             }
         }
-        // ignore, always set with maxDepth, but it's optional on the
-        // GlobOptions type
-        /* c8 ignore start */
-        this.maxDepth = opts.maxDepth || Infinity;
-        /* c8 ignore stop */
-        if (opts.signal) {
-            this.signal = opts.signal;
-            this.signal.addEventListener('abort', () => {
-                this.#onResume.length = 0;
-            });
-        }
-    }
-    #ignored(path) {
-        return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
-    }
-    #childrenIgnored(path) {
-        return !!this.#ignore?.childrenIgnored?.(path);
-    }
-    // backpressure mechanism
-    pause() {
-        this.paused = true;
+        // if we fall out of the loop, it means they two are identical
+        // as long as their lengths match
+        return a.length === b.length && result;
     }
-    resume() {
-        /* c8 ignore start */
-        if (this.signal?.aborted)
+    parseNegate() {
+        if (this.nonegate)
             return;
-        /* c8 ignore stop */
-        this.paused = false;
-        let fn = undefined;
-        while (!this.paused && (fn = this.#onResume.shift())) {
-            fn();
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+            negate = !negate;
+            negateOffset++;
         }
+        if (negateOffset)
+            this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
     }
-    onResume(fn) {
-        if (this.signal?.aborted)
-            return;
-        /* c8 ignore start */
-        if (!this.paused) {
-            fn();
-        }
-        else {
-            /* c8 ignore stop */
-            this.#onResume.push(fn);
+    // set partial to true to test if, for example,
+    // "/a/b" matches the start of "/*/b/*/d"
+    // Partial means, if you run out of file before you run
+    // out of pattern, then that's fine, as long as all
+    // the parts match.
+    matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        // UNC paths like //?/X:/... can match X:/... and vice versa
+        // Drive letters in absolute drive or unc paths are always compared
+        // case-insensitively.
+        if (this.isWindows) {
+            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
+            const fileUNC = !fileDrive &&
+                file[0] === '' &&
+                file[1] === '' &&
+                file[2] === '?' &&
+                /^[a-z]:$/i.test(file[3]);
+            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
+            const patternUNC = !patternDrive &&
+                pattern[0] === '' &&
+                pattern[1] === '' &&
+                pattern[2] === '?' &&
+                typeof pattern[3] === 'string' &&
+                /^[a-z]:$/i.test(pattern[3]);
+            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
+            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
+            if (typeof fdi === 'number' && typeof pdi === 'number') {
+                const [fd, pd] = [file[fdi], pattern[pdi]];
+                if (fd.toLowerCase() === pd.toLowerCase()) {
+                    pattern[pdi] = fd;
+                    if (pdi > fdi) {
+                        pattern = pattern.slice(pdi);
+                    }
+                    else if (fdi > pdi) {
+                        file = file.slice(fdi);
+                    }
+                }
+            }
         }
-    }
-    // do the requisite realpath/stat checking, and return the path
-    // to add or undefined to filter it out.
-    async matchCheck(e, ifDir) {
-        if (ifDir && this.opts.nodir)
-            return undefined;
-        let rpc;
-        if (this.opts.realpath) {
-            rpc = e.realpathCached() || (await e.realpath());
-            if (!rpc)
-                return undefined;
-            e = rpc;
+        // resolve and reduce . and .. portions in the file as well.
+        // dont' need to do the second phase, because it's only one string[]
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            file = this.levelTwoFileOptimize(file);
         }
-        const needStat = e.isUnknown() || this.opts.stat;
-        const s = needStat ? await e.lstat() : e;
-        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
-            const target = await s.realpath();
+        this.debug('matchOne', this, { file, pattern });
+        this.debug('matchOne', file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+            this.debug('matchOne loop');
+            var p = pattern[pi];
+            var f = file[fi];
+            this.debug(pattern, p, f);
+            // should be impossible.
+            // some invalid regexp stuff in the set.
             /* c8 ignore start */
-            if (target && (target.isUnknown() || this.opts.stat)) {
-                await target.lstat();
+            if (p === false) {
+                return false;
+            }
+            /* c8 ignore stop */
+            if (p === exports.GLOBSTAR) {
+                this.debug('GLOBSTAR', [pattern, p, f]);
+                // "**"
+                // a/**/b/**/c would match the following:
+                // a/b/x/y/z/c
+                // a/x/y/z/b/c
+                // a/b/x/b/x/c
+                // a/b/c
+                // To do this, take the rest of the pattern after
+                // the **, and see if it would match the file remainder.
+                // If so, return success.
+                // If not, the ** "swallows" a segment, and try again.
+                // This is recursively awful.
+                //
+                // a/**/b/**/c matching a/b/x/y/z/c
+                // - a matches a
+                // - doublestar
+                //   - matchOne(b/x/y/z/c, b/**/c)
+                //     - b matches b
+                //     - doublestar
+                //       - matchOne(x/y/z/c, c) -> no
+                //       - matchOne(y/z/c, c) -> no
+                //       - matchOne(z/c, c) -> no
+                //       - matchOne(c, c) yes, hit
+                var fr = fi;
+                var pr = pi + 1;
+                if (pr === pl) {
+                    this.debug('** at the end');
+                    // a ** at the end will just swallow the rest.
+                    // We have found a match.
+                    // however, it will not swallow /.x, unless
+                    // options.dot is set.
+                    // . and .. are *never* matched by **, for explosively
+                    // exponential reasons.
+                    for (; fi < fl; fi++) {
+                        if (file[fi] === '.' ||
+                            file[fi] === '..' ||
+                            (!options.dot && file[fi].charAt(0) === '.'))
+                            return false;
+                    }
+                    return true;
+                }
+                // ok, let's see if we can swallow whatever we can.
+                while (fr < fl) {
+                    var swallowee = file[fr];
+                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+                    // XXX remove this slice.  Just pass the start index.
+                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                        this.debug('globstar found match!', fr, fl, swallowee);
+                        // found a match.
+                        return true;
+                    }
+                    else {
+                        // can't swallow "." or ".." ever.
+                        // can only swallow ".foo" when explicitly asked.
+                        if (swallowee === '.' ||
+                            swallowee === '..' ||
+                            (!options.dot && swallowee.charAt(0) === '.')) {
+                            this.debug('dot detected!', file, fr, pattern, pr);
+                            break;
+                        }
+                        // ** swallows a segment, and continue.
+                        this.debug('globstar swallow a segment, and continue');
+                        fr++;
+                    }
+                }
+                // no match was found.
+                // However, in partial mode, we can't say this is necessarily over.
+                /* c8 ignore start */
+                if (partial) {
+                    // ran out of file
+                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+                    if (fr === fl) {
+                        return true;
+                    }
+                }
+                /* c8 ignore stop */
+                return false;
+            }
+            // something other than **
+            // non-magic patterns just have to match exactly
+            // patterns with magic have been turned into regexps.
+            let hit;
+            if (typeof p === 'string') {
+                hit = f === p;
+                this.debug('string match', p, f, hit);
             }
-            /* c8 ignore stop */
-        }
-        return this.matchCheckTest(s, ifDir);
-    }
-    matchCheckTest(e, ifDir) {
-        return (e &&
-            (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
-            (!ifDir || e.canReaddir()) &&
-            (!this.opts.nodir || !e.isDirectory()) &&
-            (!this.opts.nodir ||
-                !this.opts.follow ||
-                !e.isSymbolicLink() ||
-                !e.realpathCached()?.isDirectory()) &&
-            !this.#ignored(e)) ?
-            e
-            : undefined;
-    }
-    matchCheckSync(e, ifDir) {
-        if (ifDir && this.opts.nodir)
-            return undefined;
-        let rpc;
-        if (this.opts.realpath) {
-            rpc = e.realpathCached() || e.realpathSync();
-            if (!rpc)
-                return undefined;
-            e = rpc;
-        }
-        const needStat = e.isUnknown() || this.opts.stat;
-        const s = needStat ? e.lstatSync() : e;
-        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
-            const target = s.realpathSync();
-            if (target && (target?.isUnknown() || this.opts.stat)) {
-                target.lstatSync();
+            else {
+                hit = p.test(f);
+                this.debug('pattern match', p, f, hit);
             }
+            if (!hit)
+                return false;
         }
-        return this.matchCheckTest(s, ifDir);
-    }
-    matchFinish(e, absolute) {
-        if (this.#ignored(e))
-            return;
-        // we know we have an ignore if this is false, but TS doesn't
-        if (!this.includeChildMatches && this.#ignore?.add) {
-            const ign = `${e.relativePosix()}/**`;
-            this.#ignore.add(ign);
+        // Note: ending in / means that we'll get a final ""
+        // at the end of the pattern.  This can only match a
+        // corresponding "" at the end of the file.
+        // If the file ends in /, then it can only match a
+        // a pattern that ends in /, unless the pattern just
+        // doesn't have any more for it. But, a/b/ should *not*
+        // match "a/b/*", even though "" matches against the
+        // [^/]*? pattern, except in partial mode, where it might
+        // simply not be reached yet.
+        // However, a/b/ should still satisfy a/*
+        // now either we fell off the end of the pattern, or we're done.
+        if (fi === fl && pi === pl) {
+            // ran out of pattern and filename at the same time.
+            // an exact hit!
+            return true;
         }
-        const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
-        this.seen.add(e);
-        const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
-        // ok, we have what we need!
-        if (this.opts.withFileTypes) {
-            this.matchEmit(e);
+        else if (fi === fl) {
+            // ran out of file, but still had pattern left.
+            // this is ok if we're doing the match as part of
+            // a glob fs traversal.
+            return partial;
         }
-        else if (abs) {
-            const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
-            this.matchEmit(abs + mark);
+        else if (pi === pl) {
+            // ran out of pattern, still have file left.
+            // this is only acceptable if we're on the very last
+            // empty segment of a file with a trailing slash.
+            // a/* should match a/b/
+            return fi === fl - 1 && file[fi] === '';
+            /* c8 ignore start */
         }
         else {
-            const rel = this.opts.posix ? e.relativePosix() : e.relative();
-            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
-                '.' + this.#sep
-                : '';
-            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
+            // should be unreachable.
+            throw new Error('wtf?');
         }
-    }
-    async match(e, absolute, ifDir) {
-        const p = await this.matchCheck(e, ifDir);
-        if (p)
-            this.matchFinish(p, absolute);
-    }
-    matchSync(e, absolute, ifDir) {
-        const p = this.matchCheckSync(e, ifDir);
-        if (p)
-            this.matchFinish(p, absolute);
-    }
-    walkCB(target, patterns, cb) {
-        /* c8 ignore start */
-        if (this.signal?.aborted)
-            cb();
         /* c8 ignore stop */
-        this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
     }
-    walkCB2(target, patterns, processor, cb) {
-        if (this.#childrenIgnored(target))
-            return cb();
-        if (this.signal?.aborted)
-            cb();
-        if (this.paused) {
-            this.onResume(() => this.walkCB2(target, patterns, processor, cb));
-            return;
-        }
-        processor.processPatterns(target, patterns);
-        // done processing.  all of the above is sync, can be abstracted out.
-        // subwalks is a map of paths to the entry filters they need
-        // matches is a map of paths to [absolute, ifDir] tuples.
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
-        }
-        for (const t of processor.subwalkTargets()) {
-            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
-                continue;
-            }
-            tasks++;
-            const childrenCached = t.readdirCached();
-            if (t.calledReaddir())
-                this.walkCB3(t, childrenCached, processor, next);
-            else {
-                t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
-            }
-        }
-        next();
+    braceExpand() {
+        return (0, exports.braceExpand)(this.pattern, this.options);
     }
-    walkCB3(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
-        }
-        for (const [target, patterns] of processor.subwalks.entries()) {
-            tasks++;
-            this.walkCB2(target, patterns, processor.child(), next);
+    parse(pattern) {
+        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+        const options = this.options;
+        // shortcuts
+        if (pattern === '**')
+            return exports.GLOBSTAR;
+        if (pattern === '')
+            return '';
+        // far and away, the most common glob pattern parts are
+        // *, *.*, and *.  Add a fast check method for those.
+        let m;
+        let fastTest = null;
+        if ((m = pattern.match(starRE))) {
+            fastTest = options.dot ? starTestDot : starTest;
         }
-        next();
-    }
-    walkCBSync(target, patterns, cb) {
-        /* c8 ignore start */
-        if (this.signal?.aborted)
-            cb();
-        /* c8 ignore stop */
-        this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
-    }
-    walkCB2Sync(target, patterns, processor, cb) {
-        if (this.#childrenIgnored(target))
-            return cb();
-        if (this.signal?.aborted)
-            cb();
-        if (this.paused) {
-            this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
-            return;
+        else if ((m = pattern.match(starDotExtRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? starDotExtTestNocaseDot
+                    : starDotExtTestNocase
+                : options.dot
+                    ? starDotExtTestDot
+                    : starDotExtTest)(m[1]);
         }
-        processor.processPatterns(target, patterns);
-        // done processing.  all of the above is sync, can be abstracted out.
-        // subwalks is a map of paths to the entry filters they need
-        // matches is a map of paths to [absolute, ifDir] tuples.
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            this.matchSync(m, absolute, ifDir);
+        else if ((m = pattern.match(qmarksRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? qmarksTestNocaseDot
+                    : qmarksTestNocase
+                : options.dot
+                    ? qmarksTestDot
+                    : qmarksTest)(m);
         }
-        for (const t of processor.subwalkTargets()) {
-            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
-                continue;
-            }
-            tasks++;
-            const children = t.readdirSync();
-            this.walkCB3Sync(t, children, processor, next);
+        else if ((m = pattern.match(starDotStarRE))) {
+            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
         }
-        next();
-    }
-    walkCB3Sync(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            this.matchSync(m, absolute, ifDir);
+        else if ((m = pattern.match(dotStarRE))) {
+            fastTest = dotStarTest;
         }
-        for (const [target, patterns] of processor.subwalks.entries()) {
-            tasks++;
-            this.walkCB2Sync(target, patterns, processor.child(), next);
+        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === 'object') {
+            // Avoids overriding in frozen environments
+            Reflect.defineProperty(re, 'test', { value: fastTest });
         }
-        next();
-    }
-}
-exports.GlobUtil = GlobUtil;
-class GlobWalker extends GlobUtil {
-    matches = new Set();
-    constructor(patterns, path, opts) {
-        super(patterns, path, opts);
-    }
-    matchEmit(e) {
-        this.matches.add(e);
+        return re;
     }
-    async walk() {
-        if (this.signal?.aborted)
-            throw this.signal.reason;
-        if (this.path.isUnknown()) {
-            await this.path.lstat();
+    makeRe() {
+        if (this.regexp || this.regexp === false)
+            return this.regexp;
+        // at this point, this.set is a 2d array of partial
+        // pattern strings, or "**".
+        //
+        // It's better to use .match().  This function shouldn't
+        // be used, really, but it's pretty convenient sometimes,
+        // when you just want to work with a regex.
+        const set = this.set;
+        if (!set.length) {
+            this.regexp = false;
+            return this.regexp;
         }
-        await new Promise((res, rej) => {
-            this.walkCB(this.path, this.patterns, () => {
-                if (this.signal?.aborted) {
-                    rej(this.signal.reason);
+        const options = this.options;
+        const twoStar = options.noglobstar
+            ? star
+            : options.dot
+                ? twoStarDot
+                : twoStarNoDot;
+        const flags = new Set(options.nocase ? ['i'] : []);
+        // regexpify non-globstar patterns
+        // if ** is only item, then we just do one twoStar
+        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
+        // if ** is last, append (\/twoStar|) to previous
+        // if ** is in the middle, append (\/|\/twoStar\/) to previous
+        // then filter out GLOBSTAR symbols
+        let re = set
+            .map(pattern => {
+            const pp = pattern.map(p => {
+                if (p instanceof RegExp) {
+                    for (const f of p.flags.split(''))
+                        flags.add(f);
                 }
-                else {
-                    res(this.matches);
+                return typeof p === 'string'
+                    ? regExpEscape(p)
+                    : p === exports.GLOBSTAR
+                        ? exports.GLOBSTAR
+                        : p._src;
+            });
+            pp.forEach((p, i) => {
+                const next = pp[i + 1];
+                const prev = pp[i - 1];
+                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
+                    return;
+                }
+                if (prev === undefined) {
+                    if (next !== undefined && next !== exports.GLOBSTAR) {
+                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
+                    }
+                    else {
+                        pp[i] = twoStar;
+                    }
+                }
+                else if (next === undefined) {
+                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                }
+                else if (next !== exports.GLOBSTAR) {
+                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
+                    pp[i + 1] = exports.GLOBSTAR;
                 }
             });
-        });
-        return this.matches;
-    }
-    walkSync() {
-        if (this.signal?.aborted)
-            throw this.signal.reason;
-        if (this.path.isUnknown()) {
-            this.path.lstatSync();
+            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
+        })
+            .join('|');
+        // need to wrap in parens if we had more than one thing with |,
+        // otherwise only the first will be anchored to ^ and the last to $
+        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
+        // must match entire pattern
+        // ending in a * or ** will make it less strict.
+        re = '^' + open + re + close + '$';
+        // can match anything, as long as it's not this.
+        if (this.negate)
+            re = '^(?!' + re + ').+$';
+        try {
+            this.regexp = new RegExp(re, [...flags].join(''));
+            /* c8 ignore start */
         }
-        // nothing for the callback to do, because this never pauses
-        this.walkCBSync(this.path, this.patterns, () => {
-            if (this.signal?.aborted)
-                throw this.signal.reason;
-        });
-        return this.matches;
-    }
-}
-exports.GlobWalker = GlobWalker;
-class GlobStream extends GlobUtil {
-    results;
-    constructor(patterns, path, opts) {
-        super(patterns, path, opts);
-        this.results = new minipass_1.Minipass({
-            signal: this.signal,
-            objectMode: true,
-        });
-        this.results.on('drain', () => this.resume());
-        this.results.on('resume', () => this.resume());
-    }
-    matchEmit(e) {
-        this.results.write(e);
-        if (!this.results.flowing)
-            this.pause();
+        catch (ex) {
+            // should be impossible
+            this.regexp = false;
+        }
+        /* c8 ignore stop */
+        return this.regexp;
     }
-    stream() {
-        const target = this.path;
-        if (target.isUnknown()) {
-            target.lstat().then(() => {
-                this.walkCB(target, this.patterns, () => this.results.end());
-            });
+    slashSplit(p) {
+        // if p starts with // on windows, we preserve that
+        // so that UNC paths aren't broken.  Otherwise, any number of
+        // / characters are coalesced into one, unless
+        // preserveMultipleSlashes is set to true.
+        if (this.preserveMultipleSlashes) {
+            return p.split('/');
+        }
+        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+            // add an extra '' for the one we lose
+            return ['', ...p.split(/\/+/)];
         }
         else {
-            this.walkCB(target, this.patterns, () => this.results.end());
+            return p.split(/\/+/);
         }
-        return this.results;
     }
-    streamSync() {
-        if (this.path.isUnknown()) {
-            this.path.lstatSync();
+    match(f, partial = this.partial) {
+        this.debug('match', f, this.pattern);
+        // short-circuit in the case of busted things.
+        // comments, etc.
+        if (this.comment) {
+            return false;
         }
-        this.walkCBSync(this.path, this.patterns, () => this.results.end());
-        return this.results;
+        if (this.empty) {
+            return f === '';
+        }
+        if (f === '/' && partial) {
+            return true;
+        }
+        const options = this.options;
+        // windows: need to use /, not \
+        if (this.isWindows) {
+            f = f.split('\\').join('/');
+        }
+        // treat the test path as a set of pathparts.
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, 'split', ff);
+        // just ONE of the pattern sets in this.set needs to match
+        // in order for it to be valid.  If negating, then just one
+        // match means that we have failed.
+        // Either way, return on the first hit.
+        const set = this.set;
+        this.debug(this.pattern, 'set', set);
+        // Find the basename of the path by looking for the last non-empty segment
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+            for (let i = ff.length - 2; !filename && i >= 0; i--) {
+                filename = ff[i];
+            }
+        }
+        for (let i = 0; i < set.length; i++) {
+            const pattern = set[i];
+            let file = ff;
+            if (options.matchBase && pattern.length === 1) {
+                file = [filename];
+            }
+            const hit = this.matchOne(file, pattern, partial);
+            if (hit) {
+                if (options.flipNegate) {
+                    return true;
+                }
+                return !this.negate;
+            }
+        }
+        // didn't get any hits.  this is success if it's a negative
+        // pattern, failure otherwise.
+        if (options.flipNegate) {
+            return false;
+        }
+        return this.negate;
+    }
+    static defaults(def) {
+        return exports.minimatch.defaults(def).Minimatch;
     }
 }
-exports.GlobStream = GlobStream;
-//# sourceMappingURL=walker.js.map
+exports.Minimatch = Minimatch;
+/* c8 ignore start */
+var ast_js_2 = __nccwpck_require__(10421);
+Object.defineProperty(exports, "AST", ({ enumerable: true, get: function () { return ast_js_2.AST; } }));
+var escape_js_2 = __nccwpck_require__(4578);
+Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return escape_js_2.escape; } }));
+var unescape_js_2 = __nccwpck_require__(11633);
+Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return unescape_js_2.unescape; } }));
+/* c8 ignore stop */
+exports.minimatch.AST = ast_js_1.AST;
+exports.minimatch.Minimatch = Minimatch;
+exports.minimatch.escape = escape_js_1.escape;
+exports.minimatch.unescape = unescape_js_1.unescape;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 11633:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.unescape = void 0;
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    return windowsPathsNoEscape
+        ? s.replace(/\[([^\/\\])\]/g, '$1')
+        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
+};
+exports.unescape = unescape;
+//# sourceMappingURL=unescape.js.map
 
 /***/ }),
 
@@ -77684,2004 +78033,1694 @@ class LRUCache {
             status.get = 'miss';
         }
     }
-    #connect(p, n) {
-        this.#prev[n] = p;
-        this.#next[p] = n;
-    }
-    #moveToTail(index) {
-        // if tail already, nothing to do
-        // if head, move head to next[index]
-        // else
-        //   move next[prev[index]] to next[index] (head has no prev)
-        //   move prev[next[index]] to prev[index]
-        // prev[index] = tail
-        // next[tail] = index
-        // tail = index
-        if (index !== this.#tail) {
-            if (index === this.#head) {
-                this.#head = this.#next[index];
-            }
-            else {
-                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) {
-        return this.#delete(k, 'delete');
-    }
-    #delete(k, reason) {
-        let deleted = false;
-        if (this.#size !== 0) {
-            const index = this.#keyMap.get(k);
-            if (index !== undefined) {
-                deleted = true;
-                if (this.#size === 1) {
-                    this.#clear(reason);
-                }
-                else {
-                    this.#removeItemSize(index);
-                    const v = this.#valList[index];
-                    if (this.#isBackgroundFetch(v)) {
-                        v.__abortController.abort(new Error('deleted'));
-                    }
-                    else if (this.#hasDispose || this.#hasDisposeAfter) {
-                        if (this.#hasDispose) {
-                            this.#dispose?.(v, k, reason);
-                        }
-                        if (this.#hasDisposeAfter) {
-                            this.#disposed?.push([v, k, reason]);
-                        }
-                    }
-                    this.#keyMap.delete(k);
-                    this.#keyList[index] = undefined;
-                    this.#valList[index] = undefined;
-                    if (index === this.#tail) {
-                        this.#tail = this.#prev[index];
-                    }
-                    else if (index === this.#head) {
-                        this.#head = this.#next[index];
-                    }
-                    else {
-                        const pi = this.#prev[index];
-                        this.#next[pi] = this.#next[index];
-                        const ni = this.#next[index];
-                        this.#prev[ni] = this.#prev[index];
-                    }
-                    this.#size--;
-                    this.#free.push(index);
-                }
-            }
-        }
-        if (this.#hasDisposeAfter && this.#disposed?.length) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
-            }
-        }
-        return deleted;
-    }
-    /**
-     * Clear the cache entirely, throwing away all values.
-     */
-    clear() {
-        return this.#clear('delete');
-    }
-    #clear(reason) {
-        for (const index of this.#rindexes({ allowStale: true })) {
-            const v = this.#valList[index];
-            if (this.#isBackgroundFetch(v)) {
-                v.__abortController.abort(new Error('deleted'));
-            }
-            else {
-                const k = this.#keyList[index];
-                if (this.#hasDispose) {
-                    this.#dispose?.(v, k, reason);
-                }
-                if (this.#hasDisposeAfter) {
-                    this.#disposed?.push([v, k, reason]);
-                }
-            }
-        }
-        this.#keyMap.clear();
-        this.#valList.fill(undefined);
-        this.#keyList.fill(undefined);
-        if (this.#ttls && this.#starts) {
-            this.#ttls.fill(0);
-            this.#starts.fill(0);
-        }
-        if (this.#sizes) {
-            this.#sizes.fill(0);
-        }
-        this.#head = 0;
-        this.#tail = 0;
-        this.#free.length = 0;
-        this.#calculatedSize = 0;
-        this.#size = 0;
-        if (this.#hasDisposeAfter && this.#disposed) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
-            }
-        }
-    }
-}
-exports.LRUCache = LRUCache;
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 30013:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.assertValidPattern = void 0;
-const MAX_PATTERN_LENGTH = 1024 * 64;
-const assertValidPattern = (pattern) => {
-    if (typeof pattern !== 'string') {
-        throw new TypeError('invalid pattern');
-    }
-    if (pattern.length > MAX_PATTERN_LENGTH) {
-        throw new TypeError('pattern is too long');
-    }
-};
-exports.assertValidPattern = assertValidPattern;
-//# sourceMappingURL=assert-valid-pattern.js.map
-
-/***/ }),
-
-/***/ 6215:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// parse a single path portion
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AST = void 0;
-const brace_expressions_js_1 = __nccwpck_require__(10038);
-const unescape_js_1 = __nccwpck_require__(18047);
-const types = new Set(['!', '?', '+', '*', '@']);
-const isExtglobType = (c) => types.has(c);
-// Patterns that get prepended to bind to the start of either the
-// entire string, or just a single path portion, to prevent dots
-// and/or traversal patterns, when needed.
-// Exts don't need the ^ or / bit, because the root binds that already.
-const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
-const startNoDot = '(?!\\.)';
-// characters that indicate a start of pattern needs the "no dots" bit,
-// because a dot *might* be matched. ( is not in the list, because in
-// the case of a child extglob, it will handle the prevention itself.
-const addPatternStart = new Set(['[', '.']);
-// cases where traversal is A-OK, no dot prevention needed
-const justDots = new Set(['..', '.']);
-const reSpecials = new Set('().*{}+?[]^$\\!');
-const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-// any single thing other than /
-const qmark = '[^/]';
-// * => any number of characters
-const star = qmark + '*?';
-// use + when we need to ensure that *something* matches, because the * is
-// the only thing in the path portion.
-const starNoEmpty = qmark + '+?';
-// remove the \ chars that we added if we end up doing a nonmagic compare
-// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
-class AST {
-    type;
-    #root;
-    #hasMagic;
-    #uflag = false;
-    #parts = [];
-    #parent;
-    #parentIndex;
-    #negs;
-    #filledNegs = false;
-    #options;
-    #toString;
-    // set to true if it's an extglob with no children
-    // (which really means one child of '')
-    #emptyExt = false;
-    constructor(type, parent, options = {}) {
-        this.type = type;
-        // extglobs are inherently magical
-        if (type)
-            this.#hasMagic = true;
-        this.#parent = parent;
-        this.#root = this.#parent ? this.#parent.#root : this;
-        this.#options = this.#root === this ? options : this.#root.#options;
-        this.#negs = this.#root === this ? [] : this.#root.#negs;
-        if (type === '!' && !this.#root.#filledNegs)
-            this.#negs.push(this);
-        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
-    }
-    get hasMagic() {
-        /* c8 ignore start */
-        if (this.#hasMagic !== undefined)
-            return this.#hasMagic;
-        /* c8 ignore stop */
-        for (const p of this.#parts) {
-            if (typeof p === 'string')
-                continue;
-            if (p.type || p.hasMagic)
-                return (this.#hasMagic = true);
-        }
-        // note: will be undefined until we generate the regexp src and find out
-        return this.#hasMagic;
-    }
-    // reconstructs the pattern
-    toString() {
-        if (this.#toString !== undefined)
-            return this.#toString;
-        if (!this.type) {
-            return (this.#toString = this.#parts.map(p => String(p)).join(''));
-        }
-        else {
-            return (this.#toString =
-                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
-        }
-    }
-    #fillNegs() {
-        /* c8 ignore start */
-        if (this !== this.#root)
-            throw new Error('should only call on root');
-        if (this.#filledNegs)
-            return this;
-        /* c8 ignore stop */
-        // call toString() once to fill this out
-        this.toString();
-        this.#filledNegs = true;
-        let n;
-        while ((n = this.#negs.pop())) {
-            if (n.type !== '!')
-                continue;
-            // walk up the tree, appending everthing that comes AFTER parentIndex
-            let p = n;
-            let pp = p.#parent;
-            while (pp) {
-                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
-                    for (const part of n.#parts) {
-                        /* c8 ignore start */
-                        if (typeof part === 'string') {
-                            throw new Error('string part in extglob AST??');
-                        }
-                        /* c8 ignore stop */
-                        part.copyIn(pp.#parts[i]);
-                    }
-                }
-                p = pp;
-                pp = p.#parent;
-            }
-        }
-        return this;
-    }
-    push(...parts) {
-        for (const p of parts) {
-            if (p === '')
-                continue;
-            /* c8 ignore start */
-            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
-                throw new Error('invalid part: ' + p);
-            }
-            /* c8 ignore stop */
-            this.#parts.push(p);
-        }
-    }
-    toJSON() {
-        const ret = this.type === null
-            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
-            : [this.type, ...this.#parts.map(p => p.toJSON())];
-        if (this.isStart() && !this.type)
-            ret.unshift([]);
-        if (this.isEnd() &&
-            (this === this.#root ||
-                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
-            ret.push({});
-        }
-        return ret;
-    }
-    isStart() {
-        if (this.#root === this)
-            return true;
-        // if (this.type) return !!this.#parent?.isStart()
-        if (!this.#parent?.isStart())
-            return false;
-        if (this.#parentIndex === 0)
-            return true;
-        // if everything AHEAD of this is a negation, then it's still the "start"
-        const p = this.#parent;
-        for (let i = 0; i < this.#parentIndex; i++) {
-            const pp = p.#parts[i];
-            if (!(pp instanceof AST && pp.type === '!')) {
-                return false;
-            }
-        }
-        return true;
-    }
-    isEnd() {
-        if (this.#root === this)
-            return true;
-        if (this.#parent?.type === '!')
-            return true;
-        if (!this.#parent?.isEnd())
-            return false;
-        if (!this.type)
-            return this.#parent?.isEnd();
-        // if not root, it'll always have a parent
-        /* c8 ignore start */
-        const pl = this.#parent ? this.#parent.#parts.length : 0;
-        /* c8 ignore stop */
-        return this.#parentIndex === pl - 1;
-    }
-    copyIn(part) {
-        if (typeof part === 'string')
-            this.push(part);
-        else
-            this.push(part.clone(this));
+    #connect(p, n) {
+        this.#prev[n] = p;
+        this.#next[p] = n;
     }
-    clone(parent) {
-        const c = new AST(this.type, parent);
-        for (const p of this.#parts) {
-            c.copyIn(p);
+    #moveToTail(index) {
+        // if tail already, nothing to do
+        // if head, move head to next[index]
+        // else
+        //   move next[prev[index]] to next[index] (head has no prev)
+        //   move prev[next[index]] to prev[index]
+        // prev[index] = tail
+        // next[tail] = index
+        // tail = index
+        if (index !== this.#tail) {
+            if (index === this.#head) {
+                this.#head = this.#next[index];
+            }
+            else {
+                this.#connect(this.#prev[index], this.#next[index]);
+            }
+            this.#connect(this.#tail, index);
+            this.#tail = index;
         }
-        return c;
     }
-    static #parseAST(str, ast, pos, opt) {
-        let escaping = false;
-        let inBrace = false;
-        let braceStart = -1;
-        let braceNeg = false;
-        if (ast.type === null) {
-            // outside of a extglob, append until we find a start
-            let i = pos;
-            let acc = '';
-            while (i < str.length) {
-                const c = str.charAt(i++);
-                // still accumulate escapes at this point, but we do ignore
-                // starts that are escaped
-                if (escaping || c === '\\') {
-                    escaping = !escaping;
-                    acc += c;
-                    continue;
+    /**
+     * Deletes a key out of the cache.
+     *
+     * Returns true if the key was deleted, false otherwise.
+     */
+    delete(k) {
+        return this.#delete(k, 'delete');
+    }
+    #delete(k, reason) {
+        let deleted = false;
+        if (this.#size !== 0) {
+            const index = this.#keyMap.get(k);
+            if (index !== undefined) {
+                deleted = true;
+                if (this.#size === 1) {
+                    this.#clear(reason);
                 }
-                if (inBrace) {
-                    if (i === braceStart + 1) {
-                        if (c === '^' || c === '!') {
-                            braceNeg = true;
+                else {
+                    this.#removeItemSize(index);
+                    const v = this.#valList[index];
+                    if (this.#isBackgroundFetch(v)) {
+                        v.__abortController.abort(new Error('deleted'));
+                    }
+                    else if (this.#hasDispose || this.#hasDisposeAfter) {
+                        if (this.#hasDispose) {
+                            this.#dispose?.(v, k, reason);
+                        }
+                        if (this.#hasDisposeAfter) {
+                            this.#disposed?.push([v, k, reason]);
                         }
                     }
-                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
-                        inBrace = false;
+                    this.#keyMap.delete(k);
+                    this.#keyList[index] = undefined;
+                    this.#valList[index] = undefined;
+                    if (index === this.#tail) {
+                        this.#tail = this.#prev[index];
                     }
-                    acc += c;
-                    continue;
-                }
-                else if (c === '[') {
-                    inBrace = true;
-                    braceStart = i;
-                    braceNeg = false;
-                    acc += c;
-                    continue;
-                }
-                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
-                    ast.push(acc);
-                    acc = '';
-                    const ext = new AST(c, ast);
-                    i = AST.#parseAST(str, ext, i, opt);
-                    ast.push(ext);
-                    continue;
+                    else if (index === this.#head) {
+                        this.#head = this.#next[index];
+                    }
+                    else {
+                        const pi = this.#prev[index];
+                        this.#next[pi] = this.#next[index];
+                        const ni = this.#next[index];
+                        this.#prev[ni] = this.#prev[index];
+                    }
+                    this.#size--;
+                    this.#free.push(index);
                 }
-                acc += c;
             }
-            ast.push(acc);
-            return i;
         }
-        // some kind of extglob, pos is at the (
-        // find the next | or )
-        let i = pos + 1;
-        let part = new AST(null, ast);
-        const parts = [];
-        let acc = '';
-        while (i < str.length) {
-            const c = str.charAt(i++);
-            // still accumulate escapes at this point, but we do ignore
-            // starts that are escaped
-            if (escaping || c === '\\') {
-                escaping = !escaping;
-                acc += c;
-                continue;
+        if (this.#hasDisposeAfter && this.#disposed?.length) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
-            if (inBrace) {
-                if (i === braceStart + 1) {
-                    if (c === '^' || c === '!') {
-                        braceNeg = true;
-                    }
+        }
+        return deleted;
+    }
+    /**
+     * Clear the cache entirely, throwing away all values.
+     */
+    clear() {
+        return this.#clear('delete');
+    }
+    #clear(reason) {
+        for (const index of this.#rindexes({ allowStale: true })) {
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                v.__abortController.abort(new Error('deleted'));
+            }
+            else {
+                const k = this.#keyList[index];
+                if (this.#hasDispose) {
+                    this.#dispose?.(v, k, reason);
                 }
-                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
-                    inBrace = false;
+                if (this.#hasDisposeAfter) {
+                    this.#disposed?.push([v, k, reason]);
                 }
-                acc += c;
-                continue;
-            }
-            else if (c === '[') {
-                inBrace = true;
-                braceStart = i;
-                braceNeg = false;
-                acc += c;
-                continue;
-            }
-            if (isExtglobType(c) && str.charAt(i) === '(') {
-                part.push(acc);
-                acc = '';
-                const ext = new AST(c, part);
-                part.push(ext);
-                i = AST.#parseAST(str, ext, i, opt);
-                continue;
             }
-            if (c === '|') {
-                part.push(acc);
-                acc = '';
-                parts.push(part);
-                part = new AST(null, ast);
-                continue;
+        }
+        this.#keyMap.clear();
+        this.#valList.fill(undefined);
+        this.#keyList.fill(undefined);
+        if (this.#ttls && this.#starts) {
+            this.#ttls.fill(0);
+            this.#starts.fill(0);
+        }
+        if (this.#sizes) {
+            this.#sizes.fill(0);
+        }
+        this.#head = 0;
+        this.#tail = 0;
+        this.#free.length = 0;
+        this.#calculatedSize = 0;
+        this.#size = 0;
+        if (this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
-            if (c === ')') {
-                if (acc === '' && ast.#parts.length === 0) {
-                    ast.#emptyExt = true;
-                }
-                part.push(acc);
-                acc = '';
-                ast.push(...parts, part);
-                return i;
+        }
+    }
+}
+exports.LRUCache = LRUCache;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 32477:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+/**
+ * @module LRUCache
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LRUCache = void 0;
+const perf = typeof performance === 'object' &&
+    performance &&
+    typeof performance.now === 'function'
+    ? performance
+    : Date;
+const warned = new Set();
+/* c8 ignore start */
+const PROCESS = (typeof process === 'object' && !!process ? process : {});
+/* c8 ignore start */
+const emitWarning = (msg, type, code, fn) => {
+    typeof PROCESS.emitWarning === 'function'
+        ? PROCESS.emitWarning(msg, type, code, fn)
+        : console.error(`[${code}] ${type}: ${msg}`);
+};
+let AC = globalThis.AbortController;
+let AS = globalThis.AbortSignal;
+/* c8 ignore start */
+if (typeof AC === 'undefined') {
+    //@ts-ignore
+    AS = class AbortSignal {
+        onabort;
+        _onabort = [];
+        reason;
+        aborted = false;
+        addEventListener(_, fn) {
+            this._onabort.push(fn);
+        }
+    };
+    //@ts-ignore
+    AC = class AbortController {
+        constructor() {
+            warnACPolyfill();
+        }
+        signal = new AS();
+        abort(reason) {
+            if (this.signal.aborted)
+                return;
+            //@ts-ignore
+            this.signal.reason = reason;
+            //@ts-ignore
+            this.signal.aborted = true;
+            //@ts-ignore
+            for (const fn of this.signal._onabort) {
+                fn(reason);
             }
-            acc += c;
+            this.signal.onabort?.(reason);
         }
-        // unfinished extglob
-        // if we got here, it was a malformed extglob! not an extglob, but
-        // maybe something else in there.
-        ast.type = null;
-        ast.#hasMagic = undefined;
-        ast.#parts = [str.substring(pos - 1)];
-        return i;
+    };
+    let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
+    const warnACPolyfill = () => {
+        if (!printACPolyfillWarning)
+            return;
+        printACPolyfillWarning = false;
+        emitWarning('AbortController is not defined. If using lru-cache in ' +
+            'node 14, load an AbortController polyfill from the ' +
+            '`node-abort-controller` package. A minimal polyfill is ' +
+            'provided for use by LRUCache.fetch(), but it should not be ' +
+            'relied upon in other contexts (eg, passing it to other APIs that ' +
+            'use AbortController/AbortSignal might have undesirable effects). ' +
+            'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
+    };
+}
+/* c8 ignore stop */
+const shouldWarn = (code) => !warned.has(code);
+const TYPE = Symbol('type');
+const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
+/* c8 ignore start */
+// This is a little bit ridiculous, tbh.
+// The maximum array length is 2^32-1 or thereabouts on most JS impls.
+// And well before that point, you're caching the entire world, I mean,
+// that's ~32GB of just integers for the next/prev links, plus whatever
+// else to hold that many keys and values.  Just filling the memory with
+// zeroes at init time is brutal when you get that big.
+// But why not be complete?
+// Maybe in the future, these limits will have expanded.
+const getUintArray = (max) => !isPosInt(max)
+    ? null
+    : 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;
+/* c8 ignore stop */
+class ZeroArray extends Array {
+    constructor(size) {
+        super(size);
+        this.fill(0);
+    }
+}
+class Stack {
+    heap;
+    length;
+    // private constructor
+    static #constructing = false;
+    static create(max) {
+        const HeapCls = getUintArray(max);
+        if (!HeapCls)
+            return [];
+        Stack.#constructing = true;
+        const s = new Stack(max, HeapCls);
+        Stack.#constructing = false;
+        return s;
+    }
+    constructor(max, HeapCls) {
+        /* c8 ignore start */
+        if (!Stack.#constructing) {
+            throw new TypeError('instantiate Stack using Stack.create(n)');
+        }
+        /* c8 ignore stop */
+        this.heap = new HeapCls(max);
+        this.length = 0;
+    }
+    push(n) {
+        this.heap[this.length++] = n;
+    }
+    pop() {
+        return this.heap[--this.length];
+    }
+}
+/**
+ * Default export, the thing you're using this module to get.
+ *
+ * The `K` and `V` types define the key and value types, respectively. The
+ * optional `FC` type defines the type of the `context` object passed to
+ * `cache.fetch()` and `cache.memo()`.
+ *
+ * Keys and values **must not** be `null` or `undefined`.
+ *
+ * All properties from the options object (with the exception of `max`,
+ * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
+ * added as normal public members. (The listed options are read-only getters.)
+ *
+ * Changing any of these will alter the defaults for subsequent method calls.
+ */
+class LRUCache {
+    // options that cannot be changed without disaster
+    #max;
+    #maxSize;
+    #dispose;
+    #disposeAfter;
+    #fetchMethod;
+    #memoMethod;
+    /**
+     * {@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),
+        };
     }
-    static fromGlob(pattern, options = {}) {
-        const ast = new AST(null, undefined, options);
-        AST.#parseAST(pattern, ast, 0, options);
-        return ast;
+    // Protected read-only members
+    /**
+     * {@link LRUCache.OptionsBase.max} (read-only)
+     */
+    get max() {
+        return this.#max;
     }
-    // returns the regular expression if there's magic, or the unescaped
-    // string if not.
-    toMMPattern() {
-        // should only be called on root
-        /* c8 ignore start */
-        if (this !== this.#root)
-            return this.#root.toMMPattern();
-        /* c8 ignore stop */
-        const glob = this.toString();
-        const [re, body, hasMagic, uflag] = this.toRegExpSource();
-        // if we're in nocase mode, and not nocaseMagicOnly, then we do
-        // still need a regular expression if we have to case-insensitively
-        // match capital/lowercase characters.
-        const anyMagic = hasMagic ||
-            this.#hasMagic ||
-            (this.#options.nocase &&
-                !this.#options.nocaseMagicOnly &&
-                glob.toUpperCase() !== glob.toLowerCase());
-        if (!anyMagic) {
-            return body;
-        }
-        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
-        return Object.assign(new RegExp(`^${re}$`, flags), {
-            _src: re,
-            _glob: glob,
-        });
+    /**
+     * {@link LRUCache.OptionsBase.maxSize} (read-only)
+     */
+    get maxSize() {
+        return this.#maxSize;
     }
-    get options() {
-        return this.#options;
+    /**
+     * The total computed size of items in the cache (read-only)
+     */
+    get calculatedSize() {
+        return this.#calculatedSize;
     }
-    // returns the string match, the regexp source, whether there's magic
-    // in the regexp (so a regular expression is required) and whether or
-    // not the uflag is needed for the regular expression (for posix classes)
-    // TODO: instead of injecting the start/end at this point, just return
-    // the BODY of the regexp, along with the start/end portions suitable
-    // for binding the start/end in either a joined full-path makeRe context
-    // (where we bind to (^|/), or a standalone matchPart context (where
-    // we bind to ^, and not /).  Otherwise slashes get duped!
-    //
-    // In part-matching mode, the start is:
-    // - if not isStart: nothing
-    // - if traversal possible, but not allowed: ^(?!\.\.?$)
-    // - if dots allowed or not possible: ^
-    // - if dots possible and not allowed: ^(?!\.)
-    // end is:
-    // - if not isEnd(): nothing
-    // - else: $
-    //
-    // In full-path matching mode, we put the slash at the START of the
-    // pattern, so start is:
-    // - if first pattern: same as part-matching mode
-    // - if not isStart(): nothing
-    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
-    // - if dots allowed or not possible: /
-    // - if dots possible and not allowed: /(?!\.)
-    // end is:
-    // - if last pattern, same as part-matching mode
-    // - else nothing
-    //
-    // Always put the (?:$|/) on negated tails, though, because that has to be
-    // there to bind the end of the negated pattern portion, and it's easier to
-    // just stick it in now rather than try to inject it later in the middle of
-    // the pattern.
-    //
-    // We can just always return the same end, and leave it up to the caller
-    // to know whether it's going to be used joined or in parts.
-    // And, if the start is adjusted slightly, can do the same there:
-    // - if not isStart: nothing
-    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
-    // - if dots allowed or not possible: (?:/|^)
-    // - if dots possible and not allowed: (?:/|^)(?!\.)
-    //
-    // But it's better to have a simpler binding without a conditional, for
-    // performance, so probably better to return both start options.
-    //
-    // Then the caller just ignores the end if it's not the first pattern,
-    // and the start always gets applied.
-    //
-    // But that's always going to be $ if it's the ending pattern, or nothing,
-    // so the caller can just attach $ at the end of the pattern when building.
-    //
-    // So the todo is:
-    // - better detect what kind of start is needed
-    // - return both flavors of starting pattern
-    // - attach $ at the end of the pattern when creating the actual RegExp
-    //
-    // Ah, but wait, no, that all only applies to the root when the first pattern
-    // is not an extglob. If the first pattern IS an extglob, then we need all
-    // that dot prevention biz to live in the extglob portions, because eg
-    // +(*|.x*) can match .xy but not .yx.
-    //
-    // So, return the two flavors if it's #root and the first child is not an
-    // AST, otherwise leave it to the child AST to handle it, and there,
-    // use the (?:^|/) style of start binding.
-    //
-    // Even simplified further:
-    // - Since the start for a join is eg /(?!\.) and the start for a part
-    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
-    // or start or whatever) and prepend ^ or / at the Regexp construction.
-    toRegExpSource(allowDot) {
-        const dot = allowDot ?? !!this.#options.dot;
-        if (this.#root === this)
-            this.#fillNegs();
-        if (!this.type) {
-            const noEmpty = this.isStart() && this.isEnd();
-            const src = this.#parts
-                .map(p => {
-                const [re, _, hasMagic, uflag] = typeof p === 'string'
-                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
-                    : p.toRegExpSource(allowDot);
-                this.#hasMagic = this.#hasMagic || hasMagic;
-                this.#uflag = this.#uflag || uflag;
-                return re;
-            })
-                .join('');
-            let start = '';
-            if (this.isStart()) {
-                if (typeof this.#parts[0] === 'string') {
-                    // this is the string that will match the start of the pattern,
-                    // so we need to protect against dots and such.
-                    // '.' and '..' cannot match unless the pattern is that exactly,
-                    // even if it starts with . or dot:true is set.
-                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
-                    if (!dotTravAllowed) {
-                        const aps = addPatternStart;
-                        // check if we have a possibility of matching . or ..,
-                        // and prevent that.
-                        const needNoTrav = 
-                        // dots are allowed, and the pattern starts with [ or .
-                        (dot && aps.has(src.charAt(0))) ||
-                            // the pattern starts with \., and then [ or .
-                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
-                            // the pattern starts with \.\., and then [ or .
-                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
-                        // no need to prevent dots if it can't match a dot, or if a
-                        // sub-pattern will be preventing it anyway.
-                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
-                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
-                    }
-                }
+    /**
+     * 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;
+    }
+    get memoMethod() {
+        return this.#memoMethod;
+    }
+    /**
+     * {@link LRUCache.OptionsBase.dispose} (read-only)
+     */
+    get dispose() {
+        return this.#dispose;
+    }
+    /**
+     * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
+     */
+    get disposeAfter() {
+        return this.#disposeAfter;
+    }
+    constructor(options) {
+        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
+        if (max !== 0 && !isPosInt(max)) {
+            throw new TypeError('max option must be a nonnegative integer');
+        }
+        const UintArray = max ? getUintArray(max) : Array;
+        if (!UintArray) {
+            throw new Error('invalid max value: ' + max);
+        }
+        this.#max = max;
+        this.#maxSize = maxSize;
+        this.maxEntrySize = maxEntrySize || this.#maxSize;
+        this.sizeCalculation = sizeCalculation;
+        if (this.sizeCalculation) {
+            if (!this.#maxSize && !this.maxEntrySize) {
+                throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
             }
-            // append the "end of path portion" pattern to negation tails
-            let end = '';
-            if (this.isEnd() &&
-                this.#root.#filledNegs &&
-                this.#parent?.type === '!') {
-                end = '(?:$|\\/)';
+            if (typeof this.sizeCalculation !== 'function') {
+                throw new TypeError('sizeCalculation set to non-function');
             }
-            const final = start + src + end;
-            return [
-                final,
-                (0, unescape_js_1.unescape)(src),
-                (this.#hasMagic = !!this.#hasMagic),
-                this.#uflag,
-            ];
         }
-        // We need to calculate the body *twice* if it's a repeat pattern
-        // at the start, once in nodot mode, then again in dot mode, so a
-        // pattern like *(?) can match 'x.y'
-        const repeated = this.type === '*' || this.type === '+';
-        // some kind of extglob
-        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
-        let body = this.#partsToRegExp(dot);
-        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
-            // invalid extglob, has to at least be *something* present, if it's
-            // the entire path portion.
-            const s = this.toString();
-            this.#parts = [s];
-            this.type = null;
-            this.#hasMagic = undefined;
-            return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
+        if (memoMethod !== undefined &&
+            typeof memoMethod !== 'function') {
+            throw new TypeError('memoMethod must be a function if defined');
         }
-        // XXX abstract out this map method
-        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
-            ? ''
-            : this.#partsToRegExp(true);
-        if (bodyDotAllowed === body) {
-            bodyDotAllowed = '';
+        this.#memoMethod = memoMethod;
+        if (fetchMethod !== undefined &&
+            typeof fetchMethod !== 'function') {
+            throw new TypeError('fetchMethod must be a function if specified');
         }
-        if (bodyDotAllowed) {
-            body = `(?:${body})(?:${bodyDotAllowed})*?`;
+        this.#fetchMethod = fetchMethod;
+        this.#hasFetchMethod = !!fetchMethod;
+        this.#keyMap = new Map();
+        this.#keyList = new Array(max).fill(undefined);
+        this.#valList = new Array(max).fill(undefined);
+        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;
+        if (typeof dispose === 'function') {
+            this.#dispose = dispose;
         }
-        // an empty !() is exactly equivalent to a starNoEmpty
-        let final = '';
-        if (this.type === '!' && this.#emptyExt) {
-            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
+        if (typeof disposeAfter === 'function') {
+            this.#disposeAfter = disposeAfter;
+            this.#disposed = [];
         }
         else {
-            const close = this.type === '!'
-                ? // !() must match something,but !(x) can match ''
-                    '))' +
-                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
-                        star +
-                        ')'
-                : this.type === '@'
-                    ? ')'
-                    : this.type === '?'
-                        ? ')?'
-                        : this.type === '+' && bodyDotAllowed
-                            ? ')'
-                            : this.type === '*' && bodyDotAllowed
-                                ? `)?`
-                                : `)${this.type}`;
-            final = start + body + close;
+            this.#disposeAfter = undefined;
+            this.#disposed = undefined;
         }
-        return [
-            final,
-            (0, unescape_js_1.unescape)(body),
-            (this.#hasMagic = !!this.#hasMagic),
-            this.#uflag,
-        ];
-    }
-    #partsToRegExp(dot) {
-        return this.#parts
-            .map(p => {
-            // extglob ASTs should only contain parent ASTs
-            /* c8 ignore start */
-            if (typeof p === 'string') {
-                throw new Error('string type in extglob ast??');
-            }
-            /* c8 ignore stop */
-            // can ignore hasMagic, because extglobs are already always magic
-            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
-            this.#uflag = this.#uflag || uflag;
-            return re;
-        })
-            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
-            .join('|');
-    }
-    static #parseGlob(glob, hasMagic, noEmpty = false) {
-        let escaping = false;
-        let re = '';
-        let uflag = false;
-        for (let i = 0; i < glob.length; i++) {
-            const c = glob.charAt(i);
-            if (escaping) {
-                escaping = false;
-                re += (reSpecials.has(c) ? '\\' : '') + c;
-                continue;
-            }
-            if (c === '\\') {
-                if (i === glob.length - 1) {
-                    re += '\\\\';
-                }
-                else {
-                    escaping = true;
+        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;
+        // NB: maxEntrySize is set to maxSize if it's set
+        if (this.maxEntrySize !== 0) {
+            if (this.#maxSize !== 0) {
+                if (!isPosInt(this.#maxSize)) {
+                    throw new TypeError('maxSize must be a positive integer if specified');
                 }
-                continue;
             }
-            if (c === '[') {
-                const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
-                if (consumed) {
-                    re += src;
-                    uflag = uflag || needUflag;
-                    i += consumed - 1;
-                    hasMagic = hasMagic || magic;
-                    continue;
-                }
+            if (!isPosInt(this.maxEntrySize)) {
+                throw new TypeError('maxEntrySize must be a positive integer if specified');
             }
-            if (c === '*') {
-                if (noEmpty && glob === '*')
-                    re += starNoEmpty;
-                else
-                    re += star;
-                hasMagic = true;
-                continue;
+            this.#initializeSizeTracking();
+        }
+        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;
+        if (this.ttl) {
+            if (!isPosInt(this.ttl)) {
+                throw new TypeError('ttl must be a positive integer if specified');
             }
-            if (c === '?') {
-                re += qmark;
-                hasMagic = true;
-                continue;
+            this.#initializeTTLTracking();
+        }
+        // do not allow completely unbounded caches
+        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) {
+            const code = 'LRU_CACHE_UNBOUNDED';
+            if (shouldWarn(code)) {
+                warned.add(code);
+                const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
+                    'result in unbounded memory consumption.';
+                emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
             }
-            re += regExpEscape(c);
         }
-        return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
     }
-}
-exports.AST = AST;
-//# sourceMappingURL=ast.js.map
-
-/***/ }),
-
-/***/ 10038:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-// translate the various posix character classes into unicode properties
-// this works across all unicode locales
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseClass = void 0;
-// { : [, /u flag required, negated]
-const posixClasses = {
-    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
-    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
-    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
-    '[:blank:]': ['\\p{Zs}\\t', true],
-    '[:cntrl:]': ['\\p{Cc}', true],
-    '[:digit:]': ['\\p{Nd}', true],
-    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
-    '[:lower:]': ['\\p{Ll}', true],
-    '[:print:]': ['\\p{C}', true],
-    '[:punct:]': ['\\p{P}', true],
-    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
-    '[:upper:]': ['\\p{Lu}', true],
-    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
-    '[:xdigit:]': ['A-Fa-f0-9', false],
-};
-// only need to escape a few things inside of brace expressions
-// escapes: [ \ ] -
-const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
-// escape all regexp magic characters
-const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-// everything has already been escaped, we just have to join
-const rangesToString = (ranges) => ranges.join('');
-// takes a glob string at a posix brace expression, and returns
-// an equivalent regular expression source, and boolean indicating
-// whether the /u flag needs to be applied, and the number of chars
-// consumed to parse the character class.
-// This also removes out of order ranges, and returns ($.) if the
-// entire class just no good.
-const parseClass = (glob, position) => {
-    const pos = position;
-    /* c8 ignore start */
-    if (glob.charAt(pos) !== '[') {
-        throw new Error('not in a brace expression');
+    /**
+     * Return the number of ms left in the item's TTL. If item is not in cache,
+     * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
+     */
+    getRemainingTTL(key) {
+        return this.#keyMap.has(key) ? Infinity : 0;
+    }
+    #initializeTTLTracking() {
+        const ttls = new ZeroArray(this.#max);
+        const starts = new ZeroArray(this.#max);
+        this.#ttls = ttls;
+        this.#starts = starts;
+        this.#setItemTTL = (index, ttl, start = perf.now()) => {
+            starts[index] = ttl !== 0 ? start : 0;
+            ttls[index] = ttl;
+            if (ttl !== 0 && this.ttlAutopurge) {
+                const t = setTimeout(() => {
+                    if (this.#isStale(index)) {
+                        this.#delete(this.#keyList[index], 'expire');
+                    }
+                }, ttl + 1);
+                // unref() not supported on all platforms
+                /* c8 ignore start */
+                if (t.unref) {
+                    t.unref();
+                }
+                /* c8 ignore stop */
+            }
+        };
+        this.#updateItemAge = index => {
+            starts[index] = ttls[index] !== 0 ? perf.now() : 0;
+        };
+        this.#statusTTL = (status, index) => {
+            if (ttls[index]) {
+                const ttl = ttls[index];
+                const start = starts[index];
+                /* c8 ignore next */
+                if (!ttl || !start)
+                    return;
+                status.ttl = ttl;
+                status.start = start;
+                status.now = cachedNow || getNow();
+                const age = status.now - start;
+                status.remainingTTL = ttl - age;
+            }
+        };
+        // debounce calls to perf.now() to 1s so we're not hitting
+        // that costly call repeatedly.
+        let cachedNow = 0;
+        const getNow = () => {
+            const n = perf.now();
+            if (this.ttlResolution > 0) {
+                cachedNow = n;
+                const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
+                // not available on all platforms
+                /* c8 ignore start */
+                if (t.unref) {
+                    t.unref();
+                }
+                /* c8 ignore stop */
+            }
+            return n;
+        };
+        this.getRemainingTTL = key => {
+            const index = this.#keyMap.get(key);
+            if (index === undefined) {
+                return 0;
+            }
+            const ttl = ttls[index];
+            const start = starts[index];
+            if (!ttl || !start) {
+                return Infinity;
+            }
+            const age = (cachedNow || getNow()) - start;
+            return ttl - age;
+        };
+        this.#isStale = index => {
+            const s = starts[index];
+            const t = ttls[index];
+            return !!t && !!s && (cachedNow || getNow()) - s > t;
+        };
     }
+    // conditionally set private methods related to TTL
+    #updateItemAge = () => { };
+    #statusTTL = () => { };
+    #setItemTTL = () => { };
     /* c8 ignore stop */
-    const ranges = [];
-    const negs = [];
-    let i = pos + 1;
-    let sawStart = false;
-    let uflag = false;
-    let escaping = false;
-    let negate = false;
-    let endPos = pos;
-    let rangeStart = '';
-    WHILE: while (i < glob.length) {
-        const c = glob.charAt(i);
-        if ((c === '!' || c === '^') && i === pos + 1) {
-            negate = true;
-            i++;
-            continue;
-        }
-        if (c === ']' && sawStart && !escaping) {
-            endPos = i + 1;
-            break;
-        }
-        sawStart = true;
-        if (c === '\\') {
-            if (!escaping) {
-                escaping = true;
-                i++;
-                continue;
+    #isStale = () => false;
+    #initializeSizeTracking() {
+        const 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) => {
+            // provisionally accept background fetches.
+            // actual value size will be checked when they return.
+            if (this.#isBackgroundFetch(v)) {
+                return 0;
             }
-            // escaped \ char, fall through and treat like normal char
-        }
-        if (c === '[' && !escaping) {
-            // either a posix class, a collation equivalent, or just a [
-            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
-                if (glob.startsWith(cls, i)) {
-                    // invalid, [a-[] is fine, but not [a-[:alpha]]
-                    if (rangeStart) {
-                        return ['$.', false, glob.length - pos, true];
+            if (!isPosInt(size)) {
+                if (sizeCalculation) {
+                    if (typeof sizeCalculation !== 'function') {
+                        throw new TypeError('sizeCalculation must be a function');
                     }
-                    i += cls.length;
-                    if (neg)
-                        negs.push(unip);
-                    else
-                        ranges.push(unip);
-                    uflag = uflag || u;
-                    continue WHILE;
+                    size = sizeCalculation(v, k);
+                    if (!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.');
                 }
             }
-        }
-        // now it's just a normal character, effectively
-        escaping = false;
-        if (rangeStart) {
-            // throw this range away if it's not valid, but others
-            // can still match.
-            if (c > rangeStart) {
-                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
+            return size;
+        };
+        this.#addItemSize = (index, size, status) => {
+            sizes[index] = size;
+            if (this.#maxSize) {
+                const maxSize = this.#maxSize - sizes[index];
+                while (this.#calculatedSize > maxSize) {
+                    this.#evict(true);
+                }
             }
-            else if (c === rangeStart) {
-                ranges.push(braceEscape(c));
+            this.#calculatedSize += sizes[index];
+            if (status) {
+                status.entrySize = size;
+                status.totalCalculatedSize = this.#calculatedSize;
             }
-            rangeStart = '';
-            i++;
-            continue;
-        }
-        // now might be the start of a range.
-        // can be either c-d or c-] or c] or c] at this point
-        if (glob.startsWith('-]', i + 1)) {
-            ranges.push(braceEscape(c + '-'));
-            i += 2;
-            continue;
+        };
+    }
+    #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');
         }
-        if (glob.startsWith('-', i + 1)) {
-            rangeStart = c;
-            i += 2;
-            continue;
+        return 0;
+    };
+    *#indexes({ allowStale = this.allowStale } = {}) {
+        if (this.#size) {
+            for (let i = this.#tail; true;) {
+                if (!this.#isValidIndex(i)) {
+                    break;
+                }
+                if (allowStale || !this.#isStale(i)) {
+                    yield i;
+                }
+                if (i === this.#head) {
+                    break;
+                }
+                else {
+                    i = this.#prev[i];
+                }
+            }
         }
-        // not the start of a range, just a single character
-        ranges.push(braceEscape(c));
-        i++;
-    }
-    if (endPos < i) {
-        // didn't see the end of the class, not a valid class,
-        // but might still be valid as a literal match.
-        return ['', false, 0, false];
-    }
-    // if we got no ranges and no negates, then we have a range that
-    // cannot possibly match anything, and that poisons the whole glob
-    if (!ranges.length && !negs.length) {
-        return ['$.', false, glob.length - pos, true];
-    }
-    // if we got one positive range, and it's a single character, then that's
-    // not actually a magic pattern, it's just that one literal character.
-    // we should not treat that as "magic", we should just return the literal
-    // character. [_] is a perfectly valid way to escape glob magic chars.
-    if (negs.length === 0 &&
-        ranges.length === 1 &&
-        /^\\?.$/.test(ranges[0]) &&
-        !negate) {
-        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
-        return [regexpEscape(r), false, endPos - pos, false];
     }
-    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
-    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
-    const comb = ranges.length && negs.length
-        ? '(' + sranges + '|' + snegs + ')'
-        : ranges.length
-            ? sranges
-            : snegs;
-    return [comb, uflag, endPos - pos, true];
-};
-exports.parseClass = parseClass;
-//# sourceMappingURL=brace-expressions.js.map
-
-/***/ }),
-
-/***/ 96076:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.escape = void 0;
-/**
- * Escape all magic characters in a glob pattern.
- *
- * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
- * option is used, then characters are escaped by wrapping in `[]`, because
- * a magic character wrapped in a character class can only be satisfied by
- * that exact character.  In this mode, `\` is _not_ escaped, because it is
- * not interpreted as a magic character, but instead as a path separator.
- */
-const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
-    // don't need to escape +@! because we escape the parens
-    // that make those magic, and escaping ! as [!] isn't valid,
-    // because [!]] is a valid glob class meaning not ']'.
-    return windowsPathsNoEscape
-        ? s.replace(/[?*()[\]]/g, '[$&]')
-        : s.replace(/[?*()[\]\\]/g, '\\$&');
-};
-exports.escape = escape;
-//# sourceMappingURL=escape.js.map
-
-/***/ }),
-
-/***/ 85207:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0;
-const brace_expansion_1 = __importDefault(__nccwpck_require__(45177));
-const assert_valid_pattern_js_1 = __nccwpck_require__(30013);
-const ast_js_1 = __nccwpck_require__(6215);
-const escape_js_1 = __nccwpck_require__(96076);
-const unescape_js_1 = __nccwpck_require__(18047);
-const minimatch = (p, pattern, options = {}) => {
-    (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-    // shortcut: comments match nothing.
-    if (!options.nocomment && pattern.charAt(0) === '#') {
-        return false;
+    *#rindexes({ allowStale = this.allowStale } = {}) {
+        if (this.#size) {
+            for (let i = this.#head; true;) {
+                if (!this.#isValidIndex(i)) {
+                    break;
+                }
+                if (allowStale || !this.#isStale(i)) {
+                    yield i;
+                }
+                if (i === this.#tail) {
+                    break;
+                }
+                else {
+                    i = this.#next[i];
+                }
+            }
+        }
     }
-    return new Minimatch(pattern, options).match(p);
-};
-exports.minimatch = minimatch;
-// Optimized checking for the most common glob patterns.
-const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
-const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
-const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
-const starDotExtTestNocase = (ext) => {
-    ext = ext.toLowerCase();
-    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
-};
-const starDotExtTestNocaseDot = (ext) => {
-    ext = ext.toLowerCase();
-    return (f) => f.toLowerCase().endsWith(ext);
-};
-const starDotStarRE = /^\*+\.\*+$/;
-const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
-const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
-const dotStarRE = /^\.\*+$/;
-const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
-const starRE = /^\*+$/;
-const starTest = (f) => f.length !== 0 && !f.startsWith('.');
-const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
-const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
-const qmarksTestNocase = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExt([$0]);
-    if (!ext)
-        return noext;
-    ext = ext.toLowerCase();
-    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
-};
-const qmarksTestNocaseDot = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExtDot([$0]);
-    if (!ext)
-        return noext;
-    ext = ext.toLowerCase();
-    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
-};
-const qmarksTestDot = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExtDot([$0]);
-    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
-};
-const qmarksTest = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExt([$0]);
-    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
-};
-const qmarksTestNoExt = ([$0]) => {
-    const len = $0.length;
-    return (f) => f.length === len && !f.startsWith('.');
-};
-const qmarksTestNoExtDot = ([$0]) => {
-    const len = $0.length;
-    return (f) => f.length === len && f !== '.' && f !== '..';
-};
-/* c8 ignore start */
-const defaultPlatform = (typeof process === 'object' && process
-    ? (typeof process.env === 'object' &&
-        process.env &&
-        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
-        process.platform
-    : 'posix');
-const path = {
-    win32: { sep: '\\' },
-    posix: { sep: '/' },
-};
-/* c8 ignore stop */
-exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
-exports.minimatch.sep = exports.sep;
-exports.GLOBSTAR = Symbol('globstar **');
-exports.minimatch.GLOBSTAR = exports.GLOBSTAR;
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-const qmark = '[^/]';
-// * => any number of characters
-const star = qmark + '*?';
-// ** when dots are allowed.  Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
-const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options);
-exports.filter = filter;
-exports.minimatch.filter = exports.filter;
-const ext = (a, b = {}) => Object.assign({}, a, b);
-const defaults = (def) => {
-    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
-        return exports.minimatch;
+    #isValidIndex(index) {
+        return (index !== undefined &&
+            this.#keyMap.get(this.#keyList[index]) === index);
     }
-    const orig = exports.minimatch;
-    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
-    return Object.assign(m, {
-        Minimatch: class Minimatch extends orig.Minimatch {
-            constructor(pattern, options = {}) {
-                super(pattern, ext(def, options));
-            }
-            static defaults(options) {
-                return orig.defaults(ext(def, options)).Minimatch;
-            }
-        },
-        AST: class AST extends orig.AST {
-            /* c8 ignore start */
-            constructor(type, parent, options = {}) {
-                super(type, parent, ext(def, options));
+    /**
+     * Return a generator yielding `[key, value]` pairs,
+     * in order from most recently used to least recently used.
+     */
+    *entries() {
+        for (const i of this.#indexes()) {
+            if (this.#valList[i] !== undefined &&
+                this.#keyList[i] !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield [this.#keyList[i], this.#valList[i]];
             }
-            /* c8 ignore stop */
-            static fromGlob(pattern, options = {}) {
-                return orig.AST.fromGlob(pattern, ext(def, options));
+        }
+    }
+    /**
+     * 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 (const i of this.#rindexes()) {
+            if (this.#valList[i] !== undefined &&
+                this.#keyList[i] !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield [this.#keyList[i], this.#valList[i]];
             }
-        },
-        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
-        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
-        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
-        defaults: (options) => orig.defaults(ext(def, options)),
-        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
-        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
-        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
-        sep: orig.sep,
-        GLOBSTAR: exports.GLOBSTAR,
-    });
-};
-exports.defaults = defaults;
-exports.minimatch.defaults = exports.defaults;
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-const braceExpand = (pattern, options = {}) => {
-    (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-    // Thanks to Yeting Li  for
-    // improving this regexp to avoid a ReDOS vulnerability.
-    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
-        // shortcut. no need to expand.
-        return [pattern];
+        }
     }
-    return (0, brace_expansion_1.default)(pattern);
-};
-exports.braceExpand = braceExpand;
-exports.minimatch.braceExpand = exports.braceExpand;
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion.  Otherwise, any series
-// of * is equivalent to a single *.  Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
-exports.makeRe = makeRe;
-exports.minimatch.makeRe = exports.makeRe;
-const match = (list, pattern, options = {}) => {
-    const mm = new Minimatch(pattern, options);
-    list = list.filter(f => mm.match(f));
-    if (mm.options.nonull && !list.length) {
-        list.push(pattern);
+    /**
+     * Return a generator yielding the keys in the cache,
+     * in order from most recently used to least recently used.
+     */
+    *keys() {
+        for (const i of this.#indexes()) {
+            const k = this.#keyList[i];
+            if (k !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield k;
+            }
+        }
     }
-    return list;
-};
-exports.match = match;
-exports.minimatch.match = exports.match;
-// replace stuff like \* with *
-const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
-const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-class Minimatch {
-    options;
-    set;
-    pattern;
-    windowsPathsNoEscape;
-    nonegate;
-    negate;
-    comment;
-    empty;
-    preserveMultipleSlashes;
-    partial;
-    globSet;
-    globParts;
-    nocase;
-    isWindows;
-    platform;
-    windowsNoMagicRoot;
-    regexp;
-    constructor(pattern, options = {}) {
-        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-        options = options || {};
-        this.options = options;
-        this.pattern = pattern;
-        this.platform = options.platform || defaultPlatform;
-        this.isWindows = this.platform === 'win32';
-        this.windowsPathsNoEscape =
-            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
-        if (this.windowsPathsNoEscape) {
-            this.pattern = this.pattern.replace(/\\/g, '/');
+    /**
+     * 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 (const i of this.#rindexes()) {
+            const k = this.#keyList[i];
+            if (k !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield k;
+            }
         }
-        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
-        this.regexp = null;
-        this.negate = false;
-        this.nonegate = !!options.nonegate;
-        this.comment = false;
-        this.empty = false;
-        this.partial = !!options.partial;
-        this.nocase = !!this.options.nocase;
-        this.windowsNoMagicRoot =
-            options.windowsNoMagicRoot !== undefined
-                ? options.windowsNoMagicRoot
-                : !!(this.isWindows && this.nocase);
-        this.globSet = [];
-        this.globParts = [];
-        this.set = [];
-        // make the set of regexps etc.
-        this.make();
     }
-    hasMagic() {
-        if (this.options.magicalBraces && this.set.length > 1) {
-            return true;
+    /**
+     * Return a generator yielding the values in the cache,
+     * in order from most recently used to least recently used.
+     */
+    *values() {
+        for (const i of this.#indexes()) {
+            const v = this.#valList[i];
+            if (v !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield this.#valList[i];
+            }
         }
-        for (const pattern of this.set) {
-            for (const part of pattern) {
-                if (typeof part !== 'string')
-                    return true;
+    }
+    /**
+     * 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 (const i of this.#rindexes()) {
+            const v = this.#valList[i];
+            if (v !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield this.#valList[i];
             }
         }
-        return false;
     }
-    debug(..._) { }
-    make() {
-        const pattern = this.pattern;
-        const options = this.options;
-        // empty patterns and comments match nothing.
-        if (!options.nocomment && pattern.charAt(0) === '#') {
-            this.comment = true;
-            return;
+    /**
+     * Iterating over the cache itself yields the same results as
+     * {@link LRUCache.entries}
+     */
+    [Symbol.iterator]() {
+        return this.entries();
+    }
+    /**
+     * A String value that is used in the creation of the default string
+     * description of an object. Called by the built-in method
+     * `Object.prototype.toString`.
+     */
+    [Symbol.toStringTag] = 'LRUCache';
+    /**
+     * 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 (const i of this.#indexes()) {
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined)
+                continue;
+            if (fn(value, this.#keyList[i], this)) {
+                return this.get(this.#keyList[i], getOptions);
+            }
         }
-        if (!pattern) {
-            this.empty = true;
-            return;
+    }
+    /**
+     * 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)`.
+     *
+     * If `thisp` is provided, function will be called in the `this`-context of
+     * the provided object, or the cache if no `thisp` object is provided.
+     *
+     * Does not update age or recenty of use, or iterate over stale values.
+     */
+    forEach(fn, thisp = this) {
+        for (const i of this.#indexes()) {
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined)
+                continue;
+            fn.call(thisp, value, this.#keyList[i], this);
         }
-        // step 1: figure out negation, etc.
-        this.parseNegate();
-        // step 2: expand braces
-        this.globSet = [...new Set(this.braceExpand())];
-        if (options.debug) {
-            this.debug = (...args) => console.error(...args);
+    }
+    /**
+     * 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 (const i of this.#rindexes()) {
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined)
+                continue;
+            fn.call(thisp, value, this.#keyList[i], this);
         }
-        this.debug(this.pattern, this.globSet);
-        // step 3: now we have a set, so turn each one into a series of
-        // path-portion matching patterns.
-        // These will be regexps, except in the case of "**", which is
-        // set to the GLOBSTAR object for globstar behavior,
-        // and will not contain any / characters
-        //
-        // First, we preprocess to make the glob pattern sets a bit simpler
-        // and deduped.  There are some perf-killing patterns that can cause
-        // problems with a glob walk, but we can simplify them down a bit.
-        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
-        this.globParts = this.preprocess(rawGlobParts);
-        this.debug(this.pattern, this.globParts);
-        // glob --> regexps
-        let set = this.globParts.map((s, _, __) => {
-            if (this.isWindows && this.windowsNoMagicRoot) {
-                // check if it's a drive or unc path.
-                const isUNC = s[0] === '' &&
-                    s[1] === '' &&
-                    (s[2] === '?' || !globMagic.test(s[2])) &&
-                    !globMagic.test(s[3]);
-                const isDrive = /^[a-z]:/i.test(s[0]);
-                if (isUNC) {
-                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
-                }
-                else if (isDrive) {
-                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
-                }
-            }
-            return s.map(ss => this.parse(ss));
-        });
-        this.debug(this.pattern, set);
-        // filter out everything that didn't compile properly.
-        this.set = set.filter(s => s.indexOf(false) === -1);
-        // do not treat the ? in UNC paths as magic
-        if (this.isWindows) {
-            for (let i = 0; i < this.set.length; i++) {
-                const p = this.set[i];
-                if (p[0] === '' &&
-                    p[1] === '' &&
-                    this.globParts[i][2] === '?' &&
-                    typeof p[3] === 'string' &&
-                    /^[a-z]:$/i.test(p[3])) {
-                    p[2] = '?';
-                }
+    }
+    /**
+     * Delete any stale entries. Returns true if anything was removed,
+     * false otherwise.
+     */
+    purgeStale() {
+        let deleted = false;
+        for (const i of this.#rindexes({ allowStale: true })) {
+            if (this.#isStale(i)) {
+                this.#delete(this.#keyList[i], 'expire');
+                deleted = true;
             }
         }
-        this.debug(this.pattern, this.set);
+        return deleted;
     }
-    // various transforms to equivalent pattern sets that are
-    // faster to process in a filesystem walk.  The goal is to
-    // eliminate what we can, and push all ** patterns as far
-    // to the right as possible, even if it increases the number
-    // of patterns that we have to process.
-    preprocess(globParts) {
-        // if we're not in globstar mode, then turn all ** into *
-        if (this.options.noglobstar) {
-            for (let i = 0; i < globParts.length; i++) {
-                for (let j = 0; j < globParts[i].length; j++) {
-                    if (globParts[i][j] === '**') {
-                        globParts[i][j] = '*';
-                    }
-                }
+    /**
+     * Get the extended info about a given entry, to get its value, size, and
+     * TTL info simultaneously. Returns `undefined` if the key is not present.
+     *
+     * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
+     * serialization, the `start` value is always the current timestamp, and the
+     * `ttl` is a calculated remaining time to live (negative if expired).
+     *
+     * Always returns stale values, if their info is found in the cache, so be
+     * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
+     * if relevant.
+     */
+    info(key) {
+        const i = this.#keyMap.get(key);
+        if (i === undefined)
+            return undefined;
+        const v = this.#valList[i];
+        const value = this.#isBackgroundFetch(v)
+            ? v.__staleWhileFetching
+            : v;
+        if (value === undefined)
+            return undefined;
+        const entry = { value };
+        if (this.#ttls && this.#starts) {
+            const ttl = this.#ttls[i];
+            const start = this.#starts[i];
+            if (ttl && start) {
+                const remain = ttl - (perf.now() - start);
+                entry.ttl = remain;
+                entry.start = Date.now();
             }
         }
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-            // aggressive optimization for the purpose of fs walking
-            globParts = this.firstPhasePreProcess(globParts);
-            globParts = this.secondPhasePreProcess(globParts);
-        }
-        else if (optimizationLevel >= 1) {
-            // just basic optimizations to remove some .. parts
-            globParts = this.levelOneOptimize(globParts);
-        }
-        else {
-            // just collapse multiple ** portions into one
-            globParts = this.adjascentGlobstarOptimize(globParts);
+        if (this.#sizes) {
+            entry.size = this.#sizes[i];
         }
-        return globParts;
+        return entry;
     }
-    // just get rid of adjascent ** portions
-    adjascentGlobstarOptimize(globParts) {
-        return globParts.map(parts => {
-            let gs = -1;
-            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
-                let i = gs;
-                while (parts[i + 1] === '**') {
-                    i++;
-                }
-                if (i !== gs) {
-                    parts.splice(gs, i - gs);
-                }
+    /**
+     * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
+     * passed to {@link LRLUCache#load}.
+     *
+     * The `start` fields are calculated relative to a portable `Date.now()`
+     * timestamp, even if `performance.now()` is available.
+     *
+     * Stale entries are always included in the `dump`, even if
+     * {@link LRUCache.OptionsBase.allowStale} is false.
+     *
+     * Note: this returns an actual array, not a generator, so it can be more
+     * easily passed around.
+     */
+    dump() {
+        const arr = [];
+        for (const i of this.#indexes({ allowStale: true })) {
+            const key = this.#keyList[i];
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined || key === undefined)
+                continue;
+            const entry = { value };
+            if (this.#ttls && this.#starts) {
+                entry.ttl = this.#ttls[i];
+                // always dump the start relative to a portable timestamp
+                // it's ok for this to be a bit slow, it's a rare operation.
+                const age = perf.now() - this.#starts[i];
+                entry.start = Math.floor(Date.now() - age);
             }
-            return parts;
-        });
+            if (this.#sizes) {
+                entry.size = this.#sizes[i];
+            }
+            arr.unshift([key, entry]);
+        }
+        return arr;
     }
-    // get rid of adjascent ** and resolve .. portions
-    levelOneOptimize(globParts) {
-        return globParts.map(parts => {
-            parts = parts.reduce((set, part) => {
-                const prev = set[set.length - 1];
-                if (part === '**' && prev === '**') {
-                    return set;
-                }
-                if (part === '..') {
-                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
-                        set.pop();
-                        return set;
-                    }
-                }
-                set.push(part);
-                return set;
-            }, []);
-            return parts.length === 0 ? [''] : parts;
-        });
+    /**
+     * Reset the cache and load in the items in entries in the order listed.
+     *
+     * The shape of the resulting cache may be different if the same options are
+     * not used in both caches.
+     *
+     * The `start` fields are assumed to be calculated relative to a portable
+     * `Date.now()` timestamp, even if `performance.now()` is available.
+     */
+    load(arr) {
+        this.clear();
+        for (const [key, entry] of arr) {
+            if (entry.start) {
+                // entry.start is a portable timestamp, but we may be using
+                // node's performance.now(), so calculate the offset, so that
+                // we get the intended remaining TTL, no matter how long it's
+                // been on ice.
+                //
+                // it's ok for this to be a bit slow, it's a rare operation.
+                const age = Date.now() - entry.start;
+                entry.start = perf.now() - age;
+            }
+            this.set(key, entry.value, entry);
+        }
     }
-    levelTwoFileOptimize(parts) {
-        if (!Array.isArray(parts)) {
-            parts = this.slashSplit(parts);
+    /**
+     * Add a value to the cache.
+     *
+     * Note: if `undefined` is specified as a value, this is an alias for
+     * {@link LRUCache#delete}
+     *
+     * Fields on the {@link LRUCache.SetOptions} options param will override
+     * their corresponding values in the constructor options for the scope
+     * of this single `set()` operation.
+     *
+     * If `start` is provided, then that will set the effective start
+     * time for the TTL calculation. Note that this must be a previous
+     * value of `performance.now()` if supported, or a previous value of
+     * `Date.now()` if not.
+     *
+     * Options object may also include `size`, which will prevent
+     * calling the `sizeCalculation` function and just use the specified
+     * number if it is a positive integer, and `noDisposeOnSet` which
+     * will prevent calling a `dispose` function in the case of
+     * overwrites.
+     *
+     * If the `size` (or return value of `sizeCalculation`) for a given
+     * entry is greater than `maxEntrySize`, then the item will not be
+     * added to the cache.
+     *
+     * Will update the recency of the entry.
+     *
+     * If the value is `undefined`, then this is an alias for
+     * `cache.delete(key)`. `undefined` is never stored in the cache.
+     */
+    set(k, v, setOptions = {}) {
+        if (v === undefined) {
+            this.delete(k);
+            return this;
         }
-        let didSomething = false;
-        do {
-            didSomething = false;
-            // 
// -> 
/
-            if (!this.preserveMultipleSlashes) {
-                for (let i = 1; i < parts.length - 1; i++) {
-                    const p = parts[i];
-                    // don't squeeze out UNC patterns
-                    if (i === 1 && p === '' && parts[0] === '')
-                        continue;
-                    if (p === '.' || p === '') {
-                        didSomething = true;
-                        parts.splice(i, 1);
-                        i--;
-                    }
-                }
-                if (parts[0] === '.' &&
-                    parts.length === 2 &&
-                    (parts[1] === '.' || parts[1] === '')) {
-                    didSomething = true;
-                    parts.pop();
-                }
-            }
-            // 
/

/../ ->

/
-            let dd = 0;
-            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
-                const p = parts[dd - 1];
-                if (p && p !== '.' && p !== '..' && p !== '**') {
-                    didSomething = true;
-                    parts.splice(dd - 1, 2);
-                    dd -= 2;
-                }
+        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
+        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
+        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
+        // if the item doesn't fit, don't do anything
+        // NB: maxEntrySize set to maxSize by default
+        if (this.maxEntrySize && size > this.maxEntrySize) {
+            if (status) {
+                status.set = 'miss';
+                status.maxEntrySizeExceeded = true;
             }
-        } while (didSomething);
-        return parts.length === 0 ? [''] : parts;
-    }
-    // First phase: single-pattern processing
-    // 
 is 1 or more portions
-    //  is 1 or more portions
-    // 

is any portion other than ., .., '', or ** - // is . or '' - // - // **/.. is *brutal* for filesystem walking performance, because - // it effectively resets the recursive walk each time it occurs, - // and ** cannot be reduced out by a .. pattern part like a regexp - // or most strings (other than .., ., and '') can be. - // - //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} - //

// -> 
/
-    // 
/

/../ ->

/
-    // **/**/ -> **/
-    //
-    // **/*/ -> */**/ <== not valid because ** doesn't follow
-    // this WOULD be allowed if ** did follow symlinks, or * didn't
-    firstPhasePreProcess(globParts) {
-        let didSomething = false;
-        do {
-            didSomething = false;
-            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} - for (let parts of globParts) { - let gs = -1; - while (-1 !== (gs = parts.indexOf('**', gs + 1))) { - let gss = gs; - while (parts[gss + 1] === '**') { - //

/**/**/ -> 
/**/
-                        gss++;
-                    }
-                    // eg, if gs is 2 and gss is 4, that means we have 3 **
-                    // parts, and can remove 2 of them.
-                    if (gss > gs) {
-                        parts.splice(gs + 1, gss - gs);
-                    }
-                    let next = parts[gs + 1];
-                    const p = parts[gs + 2];
-                    const p2 = parts[gs + 3];
-                    if (next !== '..')
-                        continue;
-                    if (!p ||
-                        p === '.' ||
-                        p === '..' ||
-                        !p2 ||
-                        p2 === '.' ||
-                        p2 === '..') {
-                        continue;
-                    }
-                    didSomething = true;
-                    // edit parts in place, and push the new one
-                    parts.splice(gs, 1);
-                    const other = parts.slice(0);
-                    other[gs] = '**';
-                    globParts.push(other);
-                    gs--;
-                }
-                // 
// -> 
/
-                if (!this.preserveMultipleSlashes) {
-                    for (let i = 1; i < parts.length - 1; i++) {
-                        const p = parts[i];
-                        // don't squeeze out UNC patterns
-                        if (i === 1 && p === '' && parts[0] === '')
-                            continue;
-                        if (p === '.' || p === '') {
-                            didSomething = true;
-                            parts.splice(i, 1);
-                            i--;
+            // have to delete, in case something is there already.
+            this.#delete(k, 'set');
+            return this;
+        }
+        let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
+        if (index === undefined) {
+            // addition
+            index = (this.#size === 0
+                ? this.#tail
+                : this.#free.length !== 0
+                    ? this.#free.pop()
+                    : this.#size === this.#max
+                        ? this.#evict(false)
+                        : 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);
+            if (status)
+                status.set = 'add';
+            noUpdateTTL = false;
+        }
+        else {
+            // update
+            this.#moveToTail(index);
+            const oldVal = this.#valList[index];
+            if (v !== oldVal) {
+                if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
+                    oldVal.__abortController.abort(new Error('replaced'));
+                    const { __staleWhileFetching: s } = oldVal;
+                    if (s !== undefined && !noDisposeOnSet) {
+                        if (this.#hasDispose) {
+                            this.#dispose?.(s, k, 'set');
+                        }
+                        if (this.#hasDisposeAfter) {
+                            this.#disposed?.push([s, k, 'set']);
                         }
                     }
-                    if (parts[0] === '.' &&
-                        parts.length === 2 &&
-                        (parts[1] === '.' || parts[1] === '')) {
-                        didSomething = true;
-                        parts.pop();
-                    }
                 }
-                // 
/

/../ ->

/
-                let dd = 0;
-                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
-                    const p = parts[dd - 1];
-                    if (p && p !== '.' && p !== '..' && p !== '**') {
-                        didSomething = true;
-                        const needDot = dd === 1 && parts[dd + 1] === '**';
-                        const splin = needDot ? ['.'] : [];
-                        parts.splice(dd - 1, 2, ...splin);
-                        if (parts.length === 0)
-                            parts.push('');
-                        dd -= 2;
+                else if (!noDisposeOnSet) {
+                    if (this.#hasDispose) {
+                        this.#dispose?.(oldVal, k, 'set');
+                    }
+                    if (this.#hasDisposeAfter) {
+                        this.#disposed?.push([oldVal, k, 'set']);
                     }
                 }
-            }
-        } while (didSomething);
-        return globParts;
-    }
-    // second phase: multi-pattern dedupes
-    // {
/*/,
/

/} ->

/*/
-    // {
/,
/} -> 
/
-    // {
/**/,
/} -> 
/**/
-    //
-    // {
/**/,
/**/

/} ->

/**/
-    // ^-- not valid because ** doens't follow symlinks
-    secondPhasePreProcess(globParts) {
-        for (let i = 0; i < globParts.length - 1; i++) {
-            for (let j = i + 1; j < globParts.length; j++) {
-                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
-                if (matched) {
-                    globParts[i] = [];
-                    globParts[j] = matched;
-                    break;
+                this.#removeItemSize(index);
+                this.#addItemSize(index, size, status);
+                this.#valList[index] = v;
+                if (status) {
+                    status.set = 'replace';
+                    const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
+                        ? oldVal.__staleWhileFetching
+                        : oldVal;
+                    if (oldValue !== undefined)
+                        status.oldValue = oldValue;
                 }
             }
-        }
-        return globParts.filter(gs => gs.length);
-    }
-    partsMatch(a, b, emptyGSMatch = false) {
-        let ai = 0;
-        let bi = 0;
-        let result = [];
-        let which = '';
-        while (ai < a.length && bi < b.length) {
-            if (a[ai] === b[bi]) {
-                result.push(which === 'b' ? b[bi] : a[ai]);
-                ai++;
-                bi++;
-            }
-            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
-                result.push(a[ai]);
-                ai++;
-            }
-            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
-                result.push(b[bi]);
-                bi++;
-            }
-            else if (a[ai] === '*' &&
-                b[bi] &&
-                (this.options.dot || !b[bi].startsWith('.')) &&
-                b[bi] !== '**') {
-                if (which === 'b')
-                    return false;
-                which = 'a';
-                result.push(a[ai]);
-                ai++;
-                bi++;
-            }
-            else if (b[bi] === '*' &&
-                a[ai] &&
-                (this.options.dot || !a[ai].startsWith('.')) &&
-                a[ai] !== '**') {
-                if (which === 'a')
-                    return false;
-                which = 'b';
-                result.push(b[bi]);
-                ai++;
-                bi++;
-            }
-            else {
-                return false;
+            else if (status) {
+                status.set = 'update';
             }
         }
-        // if we fall out of the loop, it means they two are identical
-        // as long as their lengths match
-        return a.length === b.length && result;
-    }
-    parseNegate() {
-        if (this.nonegate)
-            return;
-        const pattern = this.pattern;
-        let negate = false;
-        let negateOffset = 0;
-        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
-            negate = !negate;
-            negateOffset++;
+        if (ttl !== 0 && !this.#ttls) {
+            this.#initializeTTLTracking();
         }
-        if (negateOffset)
-            this.pattern = pattern.slice(negateOffset);
-        this.negate = negate;
-    }
-    // set partial to true to test if, for example,
-    // "/a/b" matches the start of "/*/b/*/d"
-    // Partial means, if you run out of file before you run
-    // out of pattern, then that's fine, as long as all
-    // the parts match.
-    matchOne(file, pattern, partial = false) {
-        const options = this.options;
-        // UNC paths like //?/X:/... can match X:/... and vice versa
-        // Drive letters in absolute drive or unc paths are always compared
-        // case-insensitively.
-        if (this.isWindows) {
-            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
-            const fileUNC = !fileDrive &&
-                file[0] === '' &&
-                file[1] === '' &&
-                file[2] === '?' &&
-                /^[a-z]:$/i.test(file[3]);
-            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
-            const patternUNC = !patternDrive &&
-                pattern[0] === '' &&
-                pattern[1] === '' &&
-                pattern[2] === '?' &&
-                typeof pattern[3] === 'string' &&
-                /^[a-z]:$/i.test(pattern[3]);
-            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
-            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
-            if (typeof fdi === 'number' && typeof pdi === 'number') {
-                const [fd, pd] = [file[fdi], pattern[pdi]];
-                if (fd.toLowerCase() === pd.toLowerCase()) {
-                    pattern[pdi] = fd;
-                    if (pdi > fdi) {
-                        pattern = pattern.slice(pdi);
-                    }
-                    else if (fdi > pdi) {
-                        file = file.slice(fdi);
-                    }
-                }
+        if (this.#ttls) {
+            if (!noUpdateTTL) {
+                this.#setItemTTL(index, ttl, start);
             }
+            if (status)
+                this.#statusTTL(status, index);
         }
-        // resolve and reduce . and .. portions in the file as well.
-        // dont' need to do the second phase, because it's only one string[]
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-            file = this.levelTwoFileOptimize(file);
-        }
-        this.debug('matchOne', this, { file, pattern });
-        this.debug('matchOne', file.length, pattern.length);
-        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
-            this.debug('matchOne loop');
-            var p = pattern[pi];
-            var f = file[fi];
-            this.debug(pattern, p, f);
-            // should be impossible.
-            // some invalid regexp stuff in the set.
-            /* c8 ignore start */
-            if (p === false) {
-                return false;
+        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
-            /* c8 ignore stop */
-            if (p === exports.GLOBSTAR) {
-                this.debug('GLOBSTAR', [pattern, p, f]);
-                // "**"
-                // a/**/b/**/c would match the following:
-                // a/b/x/y/z/c
-                // a/x/y/z/b/c
-                // a/b/x/b/x/c
-                // a/b/c
-                // To do this, take the rest of the pattern after
-                // the **, and see if it would match the file remainder.
-                // If so, return success.
-                // If not, the ** "swallows" a segment, and try again.
-                // This is recursively awful.
-                //
-                // a/**/b/**/c matching a/b/x/y/z/c
-                // - a matches a
-                // - doublestar
-                //   - matchOne(b/x/y/z/c, b/**/c)
-                //     - b matches b
-                //     - doublestar
-                //       - matchOne(x/y/z/c, c) -> no
-                //       - matchOne(y/z/c, c) -> no
-                //       - matchOne(z/c, c) -> no
-                //       - matchOne(c, c) yes, hit
-                var fr = fi;
-                var pr = pi + 1;
-                if (pr === pl) {
-                    this.debug('** at the end');
-                    // a ** at the end will just swallow the rest.
-                    // We have found a match.
-                    // however, it will not swallow /.x, unless
-                    // options.dot is set.
-                    // . and .. are *never* matched by **, for explosively
-                    // exponential reasons.
-                    for (; fi < fl; fi++) {
-                        if (file[fi] === '.' ||
-                            file[fi] === '..' ||
-                            (!options.dot && file[fi].charAt(0) === '.'))
-                            return false;
+        }
+        return this;
+    }
+    /**
+     * Evict the least recently used item, returning its value or
+     * `undefined` if cache is empty.
+     */
+    pop() {
+        try {
+            while (this.#size) {
+                const val = this.#valList[this.#head];
+                this.#evict(true);
+                if (this.#isBackgroundFetch(val)) {
+                    if (val.__staleWhileFetching) {
+                        return val.__staleWhileFetching;
                     }
-                    return true;
                 }
-                // ok, let's see if we can swallow whatever we can.
-                while (fr < fl) {
-                    var swallowee = file[fr];
-                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
-                    // XXX remove this slice.  Just pass the start index.
-                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
-                        this.debug('globstar found match!', fr, fl, swallowee);
-                        // found a match.
-                        return true;
-                    }
-                    else {
-                        // can't swallow "." or ".." ever.
-                        // can only swallow ".foo" when explicitly asked.
-                        if (swallowee === '.' ||
-                            swallowee === '..' ||
-                            (!options.dot && swallowee.charAt(0) === '.')) {
-                            this.debug('dot detected!', file, fr, pattern, pr);
-                            break;
-                        }
-                        // ** swallows a segment, and continue.
-                        this.debug('globstar swallow a segment, and continue');
-                        fr++;
-                    }
+                else if (val !== undefined) {
+                    return val;
                 }
-                // no match was found.
-                // However, in partial mode, we can't say this is necessarily over.
-                /* c8 ignore start */
-                if (partial) {
-                    // ran out of file
-                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
-                    if (fr === fl) {
-                        return true;
-                    }
+            }
+        }
+        finally {
+            if (this.#hasDisposeAfter && this.#disposed) {
+                const dt = this.#disposed;
+                let task;
+                while ((task = dt?.shift())) {
+                    this.#disposeAfter?.(...task);
                 }
-                /* c8 ignore stop */
-                return false;
             }
-            // something other than **
-            // non-magic patterns just have to match exactly
-            // patterns with magic have been turned into regexps.
-            let hit;
-            if (typeof p === 'string') {
-                hit = f === p;
-                this.debug('string match', p, f, hit);
+        }
+    }
+    #evict(free) {
+        const head = this.#head;
+        const k = this.#keyList[head];
+        const v = this.#valList[head];
+        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
+            v.__abortController.abort(new Error('evicted'));
+        }
+        else if (this.#hasDispose || this.#hasDisposeAfter) {
+            if (this.#hasDispose) {
+                this.#dispose?.(v, k, 'evict');
             }
-            else {
-                hit = p.test(f);
-                this.debug('pattern match', p, f, hit);
+            if (this.#hasDisposeAfter) {
+                this.#disposed?.push([v, k, 'evict']);
             }
-            if (!hit)
-                return false;
-        }
-        // Note: ending in / means that we'll get a final ""
-        // at the end of the pattern.  This can only match a
-        // corresponding "" at the end of the file.
-        // If the file ends in /, then it can only match a
-        // a pattern that ends in /, unless the pattern just
-        // doesn't have any more for it. But, a/b/ should *not*
-        // match "a/b/*", even though "" matches against the
-        // [^/]*? pattern, except in partial mode, where it might
-        // simply not be reached yet.
-        // However, a/b/ should still satisfy a/*
-        // now either we fell off the end of the pattern, or we're done.
-        if (fi === fl && pi === pl) {
-            // ran out of pattern and filename at the same time.
-            // an exact hit!
-            return true;
         }
-        else if (fi === fl) {
-            // ran out of file, but still had pattern left.
-            // this is ok if we're doing the match as part of
-            // a glob fs traversal.
-            return partial;
+        this.#removeItemSize(head);
+        // if we aren't about to use the index, then null these out
+        if (free) {
+            this.#keyList[head] = undefined;
+            this.#valList[head] = undefined;
+            this.#free.push(head);
         }
-        else if (pi === pl) {
-            // ran out of pattern, still have file left.
-            // this is only acceptable if we're on the very last
-            // empty segment of a file with a trailing slash.
-            // a/* should match a/b/
-            return fi === fl - 1 && file[fi] === '';
-            /* c8 ignore start */
+        if (this.#size === 1) {
+            this.#head = this.#tail = 0;
+            this.#free.length = 0;
         }
         else {
-            // should be unreachable.
-            throw new Error('wtf?');
+            this.#head = this.#next[head];
         }
-        /* c8 ignore stop */
-    }
-    braceExpand() {
-        return (0, exports.braceExpand)(this.pattern, this.options);
+        this.#keyMap.delete(k);
+        this.#size--;
+        return head;
     }
-    parse(pattern) {
-        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-        const options = this.options;
-        // shortcuts
-        if (pattern === '**')
-            return exports.GLOBSTAR;
-        if (pattern === '')
-            return '';
-        // far and away, the most common glob pattern parts are
-        // *, *.*, and *.  Add a fast check method for those.
-        let m;
-        let fastTest = null;
-        if ((m = pattern.match(starRE))) {
-            fastTest = options.dot ? starTestDot : starTest;
-        }
-        else if ((m = pattern.match(starDotExtRE))) {
-            fastTest = (options.nocase
-                ? options.dot
-                    ? starDotExtTestNocaseDot
-                    : starDotExtTestNocase
-                : options.dot
-                    ? starDotExtTestDot
-                    : starDotExtTest)(m[1]);
-        }
-        else if ((m = pattern.match(qmarksRE))) {
-            fastTest = (options.nocase
-                ? options.dot
-                    ? qmarksTestNocaseDot
-                    : qmarksTestNocase
-                : options.dot
-                    ? qmarksTestDot
-                    : qmarksTest)(m);
-        }
-        else if ((m = pattern.match(starDotStarRE))) {
-            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+    /**
+     * 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.
+     *
+     * Check if a key is in the cache, without updating the recency of
+     * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
+     * to `true` in either the options or the constructor.
+     *
+     * Will return `false` if the item is stale, even though it is technically in
+     * the cache. The difference can be determined (if it matters) by using a
+     * `status` argument, and inspecting the `has` field.
+     *
+     * Will not update item age unless
+     * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
+     */
+    has(k, hasOptions = {}) {
+        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== undefined) {
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v) &&
+                v.__staleWhileFetching === undefined) {
+                return false;
+            }
+            if (!this.#isStale(index)) {
+                if (updateAgeOnHas) {
+                    this.#updateItemAge(index);
+                }
+                if (status) {
+                    status.has = 'hit';
+                    this.#statusTTL(status, index);
+                }
+                return true;
+            }
+            else if (status) {
+                status.has = 'stale';
+                this.#statusTTL(status, index);
+            }
         }
-        else if ((m = pattern.match(dotStarRE))) {
-            fastTest = dotStarTest;
+        else if (status) {
+            status.has = 'miss';
         }
-        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
-        if (fastTest && typeof re === 'object') {
-            // Avoids overriding in frozen environments
-            Reflect.defineProperty(re, 'test', { value: fastTest });
+        return false;
+    }
+    /**
+     * 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 = {}) {
+        const { allowStale = this.allowStale } = peekOptions;
+        const index = this.#keyMap.get(k);
+        if (index === undefined ||
+            (!allowStale && this.#isStale(index))) {
+            return;
         }
-        return re;
+        const v = this.#valList[index];
+        // either stale and allowed, or forcing a refresh of non-stale value
+        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
     }
-    makeRe() {
-        if (this.regexp || this.regexp === false)
-            return this.regexp;
-        // at this point, this.set is a 2d array of partial
-        // pattern strings, or "**".
-        //
-        // It's better to use .match().  This function shouldn't
-        // be used, really, but it's pretty convenient sometimes,
-        // when you just want to work with a regex.
-        const set = this.set;
-        if (!set.length) {
-            this.regexp = false;
-            return this.regexp;
+    #backgroundFetch(k, index, options, context) {
+        const v = index === undefined ? undefined : this.#valList[index];
+        if (this.#isBackgroundFetch(v)) {
+            return v;
         }
-        const options = this.options;
-        const twoStar = options.noglobstar
-            ? star
-            : options.dot
-                ? twoStarDot
-                : twoStarNoDot;
-        const flags = new Set(options.nocase ? ['i'] : []);
-        // regexpify non-globstar patterns
-        // if ** is only item, then we just do one twoStar
-        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
-        // if ** is last, append (\/twoStar|) to previous
-        // if ** is in the middle, append (\/|\/twoStar\/) to previous
-        // then filter out GLOBSTAR symbols
-        let re = set
-            .map(pattern => {
-            const pp = pattern.map(p => {
-                if (p instanceof RegExp) {
-                    for (const f of p.flags.split(''))
-                        flags.add(f);
+        const ac = new AC();
+        const { signal } = options;
+        // when/if our AC signals, then stop listening to theirs.
+        signal?.addEventListener('abort', () => ac.abort(signal.reason), {
+            signal: ac.signal,
+        });
+        const fetchOpts = {
+            signal: ac.signal,
+            options,
+            context,
+        };
+        const cb = (v, updateCache = false) => {
+            const { aborted } = ac.signal;
+            const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
+            if (options.status) {
+                if (aborted && !updateCache) {
+                    options.status.fetchAborted = true;
+                    options.status.fetchError = ac.signal.reason;
+                    if (ignoreAbort)
+                        options.status.fetchAbortIgnored = true;
                 }
-                return typeof p === 'string'
-                    ? regExpEscape(p)
-                    : p === exports.GLOBSTAR
-                        ? exports.GLOBSTAR
-                        : p._src;
-            });
-            pp.forEach((p, i) => {
-                const next = pp[i + 1];
-                const prev = pp[i - 1];
-                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
-                    return;
+                else {
+                    options.status.fetchResolved = true;
                 }
-                if (prev === undefined) {
-                    if (next !== undefined && next !== exports.GLOBSTAR) {
-                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
+            }
+            if (aborted && !ignoreAbort && !updateCache) {
+                return fetchFail(ac.signal.reason);
+            }
+            // either we didn't abort, and are still here, or we did, and ignored
+            const bf = p;
+            if (this.#valList[index] === p) {
+                if (v === undefined) {
+                    if (bf.__staleWhileFetching) {
+                        this.#valList[index] = bf.__staleWhileFetching;
                     }
                     else {
-                        pp[i] = twoStar;
+                        this.#delete(k, 'fetch');
                     }
                 }
-                else if (next === undefined) {
-                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                else {
+                    if (options.status)
+                        options.status.fetchUpdated = true;
+                    this.set(k, v, fetchOpts.options);
                 }
-                else if (next !== exports.GLOBSTAR) {
-                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
-                    pp[i + 1] = exports.GLOBSTAR;
+            }
+            return v;
+        };
+        const eb = (er) => {
+            if (options.status) {
+                options.status.fetchRejected = true;
+                options.status.fetchError = er;
+            }
+            return fetchFail(er);
+        };
+        const fetchFail = (er) => {
+            const { aborted } = ac.signal;
+            const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
+            const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
+            const noDelete = allowStale || options.noDeleteOnFetchRejection;
+            const bf = p;
+            if (this.#valList[index] === p) {
+                // if we allow stale on fetch rejections, then we need to ensure that
+                // the stale value is not removed from the cache when the fetch fails.
+                const del = !noDelete || bf.__staleWhileFetching === undefined;
+                if (del) {
+                    this.#delete(k, 'fetch');
+                }
+                else if (!allowStaleAborted) {
+                    // still replace the *promise* with the stale value,
+                    // since we are done with the promise at this point.
+                    // leave it untouched if we're still waiting for an
+                    // aborted background fetch that hasn't yet returned.
+                    this.#valList[index] = bf.__staleWhileFetching;
+                }
+            }
+            if (allowStale) {
+                if (options.status && bf.__staleWhileFetching !== undefined) {
+                    options.status.returnedStale = true;
+                }
+                return bf.__staleWhileFetching;
+            }
+            else if (bf.__returned === bf) {
+                throw er;
+            }
+        };
+        const pcall = (res, rej) => {
+            const fmp = this.#fetchMethod?.(k, v, fetchOpts);
+            if (fmp && fmp instanceof Promise) {
+                fmp.then(v => res(v === undefined ? undefined : v), rej);
+            }
+            // ignored, we go until we finish, regardless.
+            // defer check until we are actually aborting,
+            // so fetchMethod can override.
+            ac.signal.addEventListener('abort', () => {
+                if (!options.ignoreFetchAbort ||
+                    options.allowStaleOnFetchAbort) {
+                    res(undefined);
+                    // when it eventually resolves, update the cache.
+                    if (options.allowStaleOnFetchAbort) {
+                        res = v => cb(v, true);
+                    }
                 }
             });
-            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
-        })
-            .join('|');
-        // need to wrap in parens if we had more than one thing with |,
-        // otherwise only the first will be anchored to ^ and the last to $
-        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
-        // must match entire pattern
-        // ending in a * or ** will make it less strict.
-        re = '^' + open + re + close + '$';
-        // can match anything, as long as it's not this.
-        if (this.negate)
-            re = '^(?!' + re + ').+$';
-        try {
-            this.regexp = new RegExp(re, [...flags].join(''));
-            /* c8 ignore start */
+        };
+        if (options.status)
+            options.status.fetchDispatched = true;
+        const p = new Promise(pcall).then(cb, eb);
+        const bf = Object.assign(p, {
+            __abortController: ac,
+            __staleWhileFetching: v,
+            __returned: undefined,
+        });
+        if (index === undefined) {
+            // internal, don't expose status.
+            this.set(k, bf, { ...fetchOpts.options, status: undefined });
+            index = this.#keyMap.get(k);
         }
-        catch (ex) {
-            // should be impossible
-            this.regexp = false;
+        else {
+            this.#valList[index] = bf;
         }
-        /* c8 ignore stop */
-        return this.regexp;
+        return bf;
     }
-    slashSplit(p) {
-        // if p starts with // on windows, we preserve that
-        // so that UNC paths aren't broken.  Otherwise, any number of
-        // / characters are coalesced into one, unless
-        // preserveMultipleSlashes is set to true.
-        if (this.preserveMultipleSlashes) {
-            return p.split('/');
+    #isBackgroundFetch(p) {
+        if (!this.#hasFetchMethod)
+            return false;
+        const b = p;
+        return (!!b &&
+            b instanceof Promise &&
+            b.hasOwnProperty('__staleWhileFetching') &&
+            b.__abortController instanceof AC);
+    }
+    async fetch(k, fetchOptions = {}) {
+        const { 
+        // 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 = false, status, signal, } = fetchOptions;
+        if (!this.#hasFetchMethod) {
+            if (status)
+                status.fetch = 'get';
+            return this.get(k, {
+                allowStale,
+                updateAgeOnGet,
+                noDeleteOnStaleGet,
+                status,
+            });
         }
-        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
-            // add an extra '' for the one we lose
-            return ['', ...p.split(/\/+/)];
+        const options = {
+            allowStale,
+            updateAgeOnGet,
+            noDeleteOnStaleGet,
+            ttl,
+            noDisposeOnSet,
+            size,
+            sizeCalculation,
+            noUpdateTTL,
+            noDeleteOnFetchRejection,
+            allowStaleOnFetchRejection,
+            allowStaleOnFetchAbort,
+            ignoreFetchAbort,
+            status,
+            signal,
+        };
+        let index = this.#keyMap.get(k);
+        if (index === undefined) {
+            if (status)
+                status.fetch = 'miss';
+            const p = this.#backgroundFetch(k, index, options, context);
+            return (p.__returned = p);
         }
         else {
-            return p.split(/\/+/);
+            // in cache, maybe already fetching
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                const stale = allowStale && v.__staleWhileFetching !== undefined;
+                if (status) {
+                    status.fetch = 'inflight';
+                    if (stale)
+                        status.returnedStale = true;
+                }
+                return stale ? v.__staleWhileFetching : (v.__returned = v);
+            }
+            // if we force a refresh, that means do NOT serve the cached value,
+            // unless we are already in the process of refreshing the cache.
+            const isStale = this.#isStale(index);
+            if (!forceRefresh && !isStale) {
+                if (status)
+                    status.fetch = 'hit';
+                this.#moveToTail(index);
+                if (updateAgeOnGet) {
+                    this.#updateItemAge(index);
+                }
+                if (status)
+                    this.#statusTTL(status, index);
+                return v;
+            }
+            // ok, it is stale or a forced refresh, and not already fetching.
+            // refresh the cache.
+            const p = this.#backgroundFetch(k, index, options, context);
+            const hasStale = p.__staleWhileFetching !== undefined;
+            const staleVal = hasStale && allowStale;
+            if (status) {
+                status.fetch = isStale ? 'stale' : 'refresh';
+                if (staleVal && isStale)
+                    status.returnedStale = true;
+            }
+            return staleVal ? p.__staleWhileFetching : (p.__returned = p);
         }
     }
-    match(f, partial = this.partial) {
-        this.debug('match', f, this.pattern);
-        // short-circuit in the case of busted things.
-        // comments, etc.
-        if (this.comment) {
-            return false;
+    async forceFetch(k, fetchOptions = {}) {
+        const v = await this.fetch(k, fetchOptions);
+        if (v === undefined)
+            throw new Error('fetch() returned undefined');
+        return v;
+    }
+    memo(k, memoOptions = {}) {
+        const memoMethod = this.#memoMethod;
+        if (!memoMethod) {
+            throw new Error('no memoMethod provided to constructor');
         }
-        if (this.empty) {
-            return f === '';
+        const { context, forceRefresh, ...options } = memoOptions;
+        const v = this.get(k, options);
+        if (!forceRefresh && v !== undefined)
+            return v;
+        const vv = memoMethod(k, v, {
+            options,
+            context,
+        });
+        this.set(k, vv, options);
+        return vv;
+    }
+    /**
+     * 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 = {}) {
+        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== undefined) {
+            const value = this.#valList[index];
+            const fetching = this.#isBackgroundFetch(value);
+            if (status)
+                this.#statusTTL(status, index);
+            if (this.#isStale(index)) {
+                if (status)
+                    status.get = 'stale';
+                // delete only if not an in-flight background fetch
+                if (!fetching) {
+                    if (!noDeleteOnStaleGet) {
+                        this.#delete(k, 'expire');
+                    }
+                    if (status && allowStale)
+                        status.returnedStale = true;
+                    return allowStale ? value : undefined;
+                }
+                else {
+                    if (status &&
+                        allowStale &&
+                        value.__staleWhileFetching !== undefined) {
+                        status.returnedStale = true;
+                    }
+                    return allowStale ? value.__staleWhileFetching : undefined;
+                }
+            }
+            else {
+                if (status)
+                    status.get = 'hit';
+                // if we're currently fetching it, we don't actually have it yet
+                // it's not stale, which means this isn't a staleWhileRefetching.
+                // If it's not stale, and fetching, AND has a __staleWhileFetching
+                // value, then that means the user fetched with {forceRefresh:true},
+                // so it's safe to return that value.
+                if (fetching) {
+                    return value.__staleWhileFetching;
+                }
+                this.#moveToTail(index);
+                if (updateAgeOnGet) {
+                    this.#updateItemAge(index);
+                }
+                return value;
+            }
         }
-        if (f === '/' && partial) {
-            return true;
+        else if (status) {
+            status.get = 'miss';
         }
-        const options = this.options;
-        // windows: need to use /, not \
-        if (this.isWindows) {
-            f = f.split('\\').join('/');
+    }
+    #connect(p, n) {
+        this.#prev[n] = p;
+        this.#next[p] = n;
+    }
+    #moveToTail(index) {
+        // if tail already, nothing to do
+        // if head, move head to next[index]
+        // else
+        //   move next[prev[index]] to next[index] (head has no prev)
+        //   move prev[next[index]] to prev[index]
+        // prev[index] = tail
+        // next[tail] = index
+        // tail = index
+        if (index !== this.#tail) {
+            if (index === this.#head) {
+                this.#head = this.#next[index];
+            }
+            else {
+                this.#connect(this.#prev[index], this.#next[index]);
+            }
+            this.#connect(this.#tail, index);
+            this.#tail = index;
         }
-        // treat the test path as a set of pathparts.
-        const ff = this.slashSplit(f);
-        this.debug(this.pattern, 'split', ff);
-        // just ONE of the pattern sets in this.set needs to match
-        // in order for it to be valid.  If negating, then just one
-        // match means that we have failed.
-        // Either way, return on the first hit.
-        const set = this.set;
-        this.debug(this.pattern, 'set', set);
-        // Find the basename of the path by looking for the last non-empty segment
-        let filename = ff[ff.length - 1];
-        if (!filename) {
-            for (let i = ff.length - 2; !filename && i >= 0; i--) {
-                filename = ff[i];
+    }
+    /**
+     * Deletes a key out of the cache.
+     *
+     * Returns true if the key was deleted, false otherwise.
+     */
+    delete(k) {
+        return this.#delete(k, 'delete');
+    }
+    #delete(k, reason) {
+        let deleted = false;
+        if (this.#size !== 0) {
+            const index = this.#keyMap.get(k);
+            if (index !== undefined) {
+                deleted = true;
+                if (this.#size === 1) {
+                    this.#clear(reason);
+                }
+                else {
+                    this.#removeItemSize(index);
+                    const v = this.#valList[index];
+                    if (this.#isBackgroundFetch(v)) {
+                        v.__abortController.abort(new Error('deleted'));
+                    }
+                    else if (this.#hasDispose || this.#hasDisposeAfter) {
+                        if (this.#hasDispose) {
+                            this.#dispose?.(v, k, reason);
+                        }
+                        if (this.#hasDisposeAfter) {
+                            this.#disposed?.push([v, k, reason]);
+                        }
+                    }
+                    this.#keyMap.delete(k);
+                    this.#keyList[index] = undefined;
+                    this.#valList[index] = undefined;
+                    if (index === this.#tail) {
+                        this.#tail = this.#prev[index];
+                    }
+                    else if (index === this.#head) {
+                        this.#head = this.#next[index];
+                    }
+                    else {
+                        const pi = this.#prev[index];
+                        this.#next[pi] = this.#next[index];
+                        const ni = this.#next[index];
+                        this.#prev[ni] = this.#prev[index];
+                    }
+                    this.#size--;
+                    this.#free.push(index);
+                }
             }
         }
-        for (let i = 0; i < set.length; i++) {
-            const pattern = set[i];
-            let file = ff;
-            if (options.matchBase && pattern.length === 1) {
-                file = [filename];
+        if (this.#hasDisposeAfter && this.#disposed?.length) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
-            const hit = this.matchOne(file, pattern, partial);
-            if (hit) {
-                if (options.flipNegate) {
-                    return true;
+        }
+        return deleted;
+    }
+    /**
+     * Clear the cache entirely, throwing away all values.
+     */
+    clear() {
+        return this.#clear('delete');
+    }
+    #clear(reason) {
+        for (const index of this.#rindexes({ allowStale: true })) {
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                v.__abortController.abort(new Error('deleted'));
+            }
+            else {
+                const k = this.#keyList[index];
+                if (this.#hasDispose) {
+                    this.#dispose?.(v, k, reason);
+                }
+                if (this.#hasDisposeAfter) {
+                    this.#disposed?.push([v, k, reason]);
                 }
-                return !this.negate;
             }
         }
-        // didn't get any hits.  this is success if it's a negative
-        // pattern, failure otherwise.
-        if (options.flipNegate) {
-            return false;
+        this.#keyMap.clear();
+        this.#valList.fill(undefined);
+        this.#keyList.fill(undefined);
+        if (this.#ttls && this.#starts) {
+            this.#ttls.fill(0);
+            this.#starts.fill(0);
+        }
+        if (this.#sizes) {
+            this.#sizes.fill(0);
+        }
+        this.#head = 0;
+        this.#tail = 0;
+        this.#free.length = 0;
+        this.#calculatedSize = 0;
+        this.#size = 0;
+        if (this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
+            }
         }
-        return this.negate;
-    }
-    static defaults(def) {
-        return exports.minimatch.defaults(def).Minimatch;
     }
 }
-exports.Minimatch = Minimatch;
-/* c8 ignore start */
-var ast_js_2 = __nccwpck_require__(6215);
-Object.defineProperty(exports, "AST", ({ enumerable: true, get: function () { return ast_js_2.AST; } }));
-var escape_js_2 = __nccwpck_require__(96076);
-Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return escape_js_2.escape; } }));
-var unescape_js_2 = __nccwpck_require__(18047);
-Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return unescape_js_2.unescape; } }));
-/* c8 ignore stop */
-exports.minimatch.AST = ast_js_1.AST;
-exports.minimatch.Minimatch = Minimatch;
-exports.minimatch.escape = escape_js_1.escape;
-exports.minimatch.unescape = unescape_js_1.unescape;
+exports.LRUCache = LRUCache;
 //# sourceMappingURL=index.js.map
 
 /***/ }),
 
-/***/ 18047:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.unescape = void 0;
-/**
- * Un-escape a string that has been escaped with {@link escape}.
- *
- * If the {@link windowsPathsNoEscape} option is used, then square-brace
- * escapes are removed, but not backslash escapes.  For example, it will turn
- * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
- * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
- *
- * When `windowsPathsNoEscape` is not set, then both brace escapes and
- * backslash escapes are removed.
- *
- * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
- * or unescaped.
- */
-const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
-    return windowsPathsNoEscape
-        ? s.replace(/\[([^\/\\])\]/g, '$1')
-        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
-};
-exports.unescape = unescape;
-//# sourceMappingURL=unescape.js.map
-
-/***/ }),
-
 /***/ 78275:
 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
diff --git a/src/attest.ts b/src/attest.ts
index 3b59cdbab..7e5edb8aa 100644
--- a/src/attest.ts
+++ b/src/attest.ts
@@ -6,21 +6,23 @@ const OCI_TIMEOUT = 30000
 const OCI_RETRY = 3
 
 export type SigstoreInstance = 'public-good' | 'github'
+export type CreateAttestationOptions = {
+  sigstoreInstance: SigstoreInstance
+  pushToRegistry: boolean
+  githubToken: string
+}
 export type AttestResult = Attestation & {
   attestationDigest?: string
+  attestationSubjects: Subject[]
 }
 
 export const createAttestation = async (
   subjects: Subject[],
   predicate: Predicate,
-  opts: {
-    sigstoreInstance: SigstoreInstance
-    pushToRegistry: boolean
-    githubToken: string
-  }
+  opts: CreateAttestationOptions
 ): Promise => {
   // Sign provenance w/ Sigstore
-  const attestation = await attest({
+  const attestation: Attestation = await attest({
     subjects,
     predicateType: predicate.type,
     predicate: predicate.params,
@@ -28,7 +30,10 @@ export const createAttestation = async (
     token: opts.githubToken
   })
 
-  const result: AttestResult = attestation
+  const result: AttestResult = {
+    ...attestation,
+    attestationSubjects: subjects
+  }
 
   if (subjects.length === 1 && opts.pushToRegistry) {
     const subject = subjects[0]
diff --git a/src/index.ts b/src/index.ts
index a4de2b8ce..872e21668 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -15,6 +15,9 @@ const inputs: RunInputs = {
   pushToRegistry: core.getBooleanInput('push-to-registry'),
   showSummary: core.getBooleanInput('show-summary'),
   githubToken: core.getInput('github-token'),
+  singleSubjectAttestations: core.getBooleanInput(
+    'single-subject-attestations'
+  ),
   // undocumented -- not part of public interface
   privateSigning: ['true', 'True', 'TRUE', '1'].includes(
     core.getInput('private-signing')
diff --git a/src/main.ts b/src/main.ts
index fcc5c93d0..9a56b0602 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -3,7 +3,12 @@ import * as github from '@actions/github'
 import fs from 'fs'
 import os from 'os'
 import path from 'path'
-import { AttestResult, SigstoreInstance, createAttestation } from './attest'
+import {
+  AttestResult,
+  SigstoreInstance,
+  createAttestation,
+  CreateAttestationOptions
+} from './attest'
 import { SEARCH_PUBLIC_GOOD_URL } from './endpoints'
 import { PredicateInputs, predicateFromInputs } from './predicate'
 import * as style from './style'
@@ -13,7 +18,7 @@ import {
   subjectFromInputs
 } from './subject'
 
-import type { Subject } from '@actions/attest'
+import type { Predicate, Subject } from '@actions/attest'
 
 const ATTESTATION_FILE_NAME = 'attestation.json'
 
@@ -22,6 +27,8 @@ export type RunInputs = SubjectInputs &
     pushToRegistry: boolean
     githubToken: string
     showSummary: boolean
+    singleSubjectAttestations: boolean
+    // undocumented -- not part of public interface
     privateSigning: boolean
   }
 
@@ -65,27 +72,31 @@ export async function run(inputs: RunInputs): Promise {
     const outputPath = path.join(tempDir(), ATTESTATION_FILE_NAME)
     core.setOutput('bundle-path', outputPath)
 
-    const att = await createAttestation(subjects, predicate, {
+    const opts: CreateAttestationOptions = {
       sigstoreInstance,
       pushToRegistry: inputs.pushToRegistry,
       githubToken: inputs.githubToken
-    })
+    }
 
-    logAttestation(subjects, att, sigstoreInstance)
+    let atts: AttestResult[]
+    if (inputs.singleSubjectAttestations) {
+      atts = await createSingleSubjectAttestations(subjects, predicate, opts)
+    } else {
+      atts = await createMultiSubjectAttestation(subjects, predicate, opts)
+    }
 
-    // Write attestation bundle to output file
-    fs.writeFileSync(outputPath, JSON.stringify(att.bundle) + os.EOL, {
-      encoding: 'utf-8',
-      flag: 'a'
-    })
+    for (const att of atts) {
+      logAttestation(att, sigstoreInstance)
 
-    if (att.attestationID) {
-      core.setOutput('attestation-id', att.attestationID)
-      core.setOutput('attestation-url', attestationURL(att.attestationID))
+      // Write attestation bundle to output file
+      fs.writeFileSync(outputPath, JSON.stringify(att.bundle) + os.EOL, {
+        encoding: 'utf-8',
+        flag: 'a'
+      })
     }
 
     if (inputs.showSummary) {
-      await logSummary(att)
+      await logSummary(atts)
     }
   } catch (err) {
     // Fail the workflow run if an error occurs
@@ -108,12 +119,41 @@ export async function run(inputs: RunInputs): Promise {
   }
 }
 
+const createSingleSubjectAttestations = async (
+  subjects: Subject[],
+  predicate: Predicate,
+  opts: CreateAttestationOptions
+): Promise => {
+  const atts: AttestResult[] = []
+  // Generate one attestation for each subject
+  for (const subject of subjects) {
+    const att = await createAttestation([subject], predicate, opts)
+    atts.push(att)
+  }
+  return atts
+}
+
+const createMultiSubjectAttestation = async (
+  subjects: Subject[],
+  predicate: Predicate,
+  opts: CreateAttestationOptions
+): Promise => {
+  const att = await createAttestation(subjects, predicate, opts)
+
+  if (att.attestationID) {
+    core.setOutput('attestation-id', att.attestationID)
+    core.setOutput('attestation-url', attestationURL(att.attestationID))
+  }
+
+  return [att]
+}
+
 // Log details about the attestation to the GitHub Actions run
 const logAttestation = (
-  subjects: Subject[],
   attestation: AttestResult,
   sigstoreInstance: SigstoreInstance
 ): void => {
+  const subjects = attestation.attestationSubjects
   if (subjects.length === 1) {
     core.info(
       `Attestation created for ${subjects[0].name}@${formatSubjectDigest(subjects[0])}`
@@ -153,13 +193,26 @@ const logAttestation = (
 }
 
 // Attach summary information to the GitHub Actions run
-const logSummary = async (attestation: AttestResult): Promise => {
-  const { attestationID } = attestation
-
-  if (attestationID) {
-    const url = attestationURL(attestationID)
-    core.summary.addHeading('Attestation Created', 3)
-    core.summary.addList([`${url}`])
+const logSummary = async (attestations: AttestResult[]): Promise => {
+  if (attestations.length > 0) {
+    core.summary.addHeading(
+      /* istanbul ignore next */
+      attestations.length !== 1
+        ? 'Attestations Created'
+        : 'Attestation Created',
+      3
+    )
+    const listItems: string[] = []
+    for (const attestation of attestations) {
+      if (attestation.attestationID) {
+        const url = attestationURL(attestation.attestationID)
+        for (const subject of attestation.attestationSubjects) {
+          const digest = formatSubjectDigest(subject)
+          listItems.push(`${subject.name}@${digest}`)
+        }
+      }
+    }
+    core.summary.addList(listItems)
     await core.summary.write()
   }
 }
diff --git a/src/subject.ts b/src/subject.ts
index b977f18fa..9a426b372 100644
--- a/src/subject.ts
+++ b/src/subject.ts
@@ -18,6 +18,7 @@ export type SubjectInputs = {
   subjectName: string
   subjectDigest: string
   subjectChecksums: string
+  singleSubjectAttestations: boolean
   downcaseName?: boolean
 }
 // Returns the subject specified by the action's inputs. The subject may be

From c74ab23b642f9d2cdc83520425b293fc7f26389c Mon Sep 17 00:00:00 2001
From: Adam Turner <9087854+aa-turner@users.noreply.github.com>
Date: Sat, 1 Mar 2025 01:53:38 +0000
Subject: [PATCH 2/7] Revert dist/index.js

---
 dist/index.js | 68771 ++++++++++++++++++++++++------------------------
 1 file changed, 34366 insertions(+), 34405 deletions(-)

diff --git a/dist/index.js b/dist/index.js
index 96188759f..bf50d285b 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -5487,7 +5487,7 @@ module.exports = class Agent extends AgentBase {
 "use strict";
 
 
-const { LRUCache } = __nccwpck_require__(32477)
+const { LRUCache } = __nccwpck_require__(32638)
 const dns = __nccwpck_require__(72250)
 
 // this is a factory so that each request can have its own opts (i.e. ttl)
@@ -5617,7 +5617,7 @@ module.exports = {
 "use strict";
 
 
-const { LRUCache } = __nccwpck_require__(32477)
+const { LRUCache } = __nccwpck_require__(32638)
 const { normalizeOptions, cacheOptions } = __nccwpck_require__(46329)
 const { getProxy, proxyCache } = __nccwpck_require__(3799)
 const dns = __nccwpck_require__(42604)
@@ -5778,7 +5778,7 @@ module.exports = {
 const { HttpProxyAgent } = __nccwpck_require__(81970)
 const { HttpsProxyAgent } = __nccwpck_require__(3669)
 const { SocksProxyAgent } = __nccwpck_require__(53357)
-const { LRUCache } = __nccwpck_require__(32477)
+const { LRUCache } = __nccwpck_require__(32638)
 const { InvalidProxyProtocolError } = __nccwpck_require__(60260)
 
 const PROXY_CACHE = new LRUCache({ max: 20 })
@@ -5895,7 +5895,7 @@ module.exports = getOptions
 /***/ 6187:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-const semver = __nccwpck_require__(41437)
+const semver = __nccwpck_require__(62088)
 
 const satisfies = (range) => {
   return semver.satisfies(process.version, range, { includePrerelease: true })
@@ -6689,3796 +6689,1236 @@ module.exports = withTempDir
 
 /***/ }),
 
-/***/ 39768:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 77864:
+/***/ ((module) => {
 
-const ANY = Symbol('SemVer ANY')
-// hoisted class for cyclic dependency
-class Comparator {
-  static get ANY () {
-    return ANY
+"use strict";
+
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
   }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
 
-  constructor (comp, options) {
-    options = parseOptions(options)
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  createTokenAuth: () => createTokenAuth
+});
+module.exports = __toCommonJS(dist_src_exports);
 
-    if (comp instanceof Comparator) {
-      if (comp.loose === !!options.loose) {
-        return comp
-      } else {
-        comp = comp.value
-      }
-    }
+// pkg/dist-src/auth.js
+var REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
+var REGEX_IS_INSTALLATION = /^ghs_/;
+var REGEX_IS_USER_TO_SERVER = /^ghu_/;
+async function auth(token) {
+  const isApp = token.split(/\./).length === 3;
+  const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
+  const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
+  const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
+  return {
+    type: "token",
+    token,
+    tokenType
+  };
+}
 
-    comp = comp.trim().split(/\s+/).join(' ')
-    debug('comparator', comp, options)
-    this.options = options
-    this.loose = !!options.loose
-    this.parse(comp)
+// pkg/dist-src/with-authorization-prefix.js
+function withAuthorizationPrefix(token) {
+  if (token.split(/\./).length === 3) {
+    return `bearer ${token}`;
+  }
+  return `token ${token}`;
+}
 
-    if (this.semver === ANY) {
-      this.value = ''
-    } else {
-      this.value = this.operator + this.semver.version
-    }
+// pkg/dist-src/hook.js
+async function hook(token, request, route, parameters) {
+  const endpoint = request.endpoint.merge(
+    route,
+    parameters
+  );
+  endpoint.headers.authorization = withAuthorizationPrefix(token);
+  return request(endpoint);
+}
 
-    debug('comp', this)
+// pkg/dist-src/index.js
+var createTokenAuth = function createTokenAuth2(token) {
+  if (!token) {
+    throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
+  }
+  if (typeof token !== "string") {
+    throw new Error(
+      "[@octokit/auth-token] Token passed to createTokenAuth is not a string"
+    );
   }
+  token = token.replace(/^(token|bearer) +/i, "");
+  return Object.assign(auth.bind(null, token), {
+    hook: hook.bind(null, token)
+  });
+};
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
 
-  parse (comp) {
-    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
-    const m = comp.match(r)
 
-    if (!m) {
-      throw new TypeError(`Invalid comparator: ${comp}`)
-    }
+/***/ }),
 
-    this.operator = m[1] !== undefined ? m[1] : ''
-    if (this.operator === '=') {
-      this.operator = ''
-    }
+/***/ 61897:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    // if it literally is just '>' or '' then allow anything.
-    if (!m[2]) {
-      this.semver = ANY
-    } else {
-      this.semver = new SemVer(m[2], this.options.loose)
-    }
-  }
+"use strict";
 
-  toString () {
-    return this.value
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
   }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
 
-  test (version) {
-    debug('Comparator.test', version, this.options.loose)
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  Octokit: () => Octokit
+});
+module.exports = __toCommonJS(dist_src_exports);
+var import_universal_user_agent = __nccwpck_require__(33843);
+var import_before_after_hook = __nccwpck_require__(52732);
+var import_request = __nccwpck_require__(66255);
+var import_graphql = __nccwpck_require__(70007);
+var import_auth_token = __nccwpck_require__(77864);
 
-    if (this.semver === ANY || version === ANY) {
-      return true
-    }
+// pkg/dist-src/version.js
+var VERSION = "5.1.0";
 
-    if (typeof version === 'string') {
-      try {
-        version = new SemVer(version, this.options)
-      } catch (er) {
-        return false
+// pkg/dist-src/index.js
+var noop = () => {
+};
+var consoleWarn = console.warn.bind(console);
+var consoleError = console.error.bind(console);
+var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;
+var Octokit = class {
+  static {
+    this.VERSION = VERSION;
+  }
+  static defaults(defaults) {
+    const OctokitWithDefaults = class extends this {
+      constructor(...args) {
+        const options = args[0] || {};
+        if (typeof defaults === "function") {
+          super(defaults(options));
+          return;
+        }
+        super(
+          Object.assign(
+            {},
+            defaults,
+            options,
+            options.userAgent && defaults.userAgent ? {
+              userAgent: `${options.userAgent} ${defaults.userAgent}`
+            } : null
+          )
+        );
       }
-    }
-
-    return cmp(version, this.operator, this.semver, this.options)
+    };
+    return OctokitWithDefaults;
   }
-
-  intersects (comp, options) {
-    if (!(comp instanceof Comparator)) {
-      throw new TypeError('a Comparator is required')
-    }
-
-    if (this.operator === '') {
-      if (this.value === '') {
-        return true
+  static {
+    this.plugins = [];
+  }
+  /**
+   * Attach a plugin (or many) to your Octokit instance.
+   *
+   * @example
+   * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
+   */
+  static plugin(...newPlugins) {
+    const currentPlugins = this.plugins;
+    const NewOctokit = class extends this {
+      static {
+        this.plugins = currentPlugins.concat(
+          newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
+        );
       }
-      return new Range(comp.value, options).test(this.value)
-    } else if (comp.operator === '') {
-      if (comp.value === '') {
-        return true
+    };
+    return NewOctokit;
+  }
+  constructor(options = {}) {
+    const hook = new import_before_after_hook.Collection();
+    const requestDefaults = {
+      baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl,
+      headers: {},
+      request: Object.assign({}, options.request, {
+        // @ts-ignore internal usage only, no need to type
+        hook: hook.bind(null, "request")
+      }),
+      mediaType: {
+        previews: [],
+        format: ""
       }
-      return new Range(this.value, options).test(comp.semver)
-    }
-
-    options = parseOptions(options)
-
-    // Special cases where nothing can possibly be lower
-    if (options.includePrerelease &&
-      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
-      return false
-    }
-    if (!options.includePrerelease &&
-      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
-      return false
-    }
-
-    // Same direction increasing (> or >=)
-    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
-      return true
+    };
+    requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;
+    if (options.baseUrl) {
+      requestDefaults.baseUrl = options.baseUrl;
     }
-    // Same direction decreasing (< or <=)
-    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
-      return true
+    if (options.previews) {
+      requestDefaults.mediaType.previews = options.previews;
     }
-    // same SemVer and both sides are inclusive (<= or >=)
-    if (
-      (this.semver.version === comp.semver.version) &&
-      this.operator.includes('=') && comp.operator.includes('=')) {
-      return true
+    if (options.timeZone) {
+      requestDefaults.headers["time-zone"] = options.timeZone;
     }
-    // opposite directions less than
-    if (cmp(this.semver, '<', comp.semver, options) &&
-      this.operator.startsWith('>') && comp.operator.startsWith('<')) {
-      return true
+    this.request = import_request.request.defaults(requestDefaults);
+    this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults);
+    this.log = Object.assign(
+      {
+        debug: noop,
+        info: noop,
+        warn: consoleWarn,
+        error: consoleError
+      },
+      options.log
+    );
+    this.hook = hook;
+    if (!options.authStrategy) {
+      if (!options.auth) {
+        this.auth = async () => ({
+          type: "unauthenticated"
+        });
+      } else {
+        const auth = (0, import_auth_token.createTokenAuth)(options.auth);
+        hook.wrap("request", auth.hook);
+        this.auth = auth;
+      }
+    } else {
+      const { authStrategy, ...otherOptions } = options;
+      const auth = authStrategy(
+        Object.assign(
+          {
+            request: this.request,
+            log: this.log,
+            // we pass the current octokit instance as well as its constructor options
+            // to allow for authentication strategies that return a new octokit instance
+            // that shares the same internal state as the current one. The original
+            // requirement for this was the "event-octokit" authentication strategy
+            // of https://github.com/probot/octokit-auth-probot.
+            octokit: this,
+            octokitOptions: otherOptions
+          },
+          options.auth
+        )
+      );
+      hook.wrap("request", auth.hook);
+      this.auth = auth;
     }
-    // opposite directions greater than
-    if (cmp(this.semver, '>', comp.semver, options) &&
-      this.operator.startsWith('<') && comp.operator.startsWith('>')) {
-      return true
+    const classConstructor = this.constructor;
+    for (let i = 0; i < classConstructor.plugins.length; ++i) {
+      Object.assign(this, classConstructor.plugins[i](this, options));
     }
-    return false
   }
-}
-
-module.exports = Comparator
-
-const parseOptions = __nccwpck_require__(65939)
-const { safeRe: re, t } = __nccwpck_require__(84894)
-const cmp = __nccwpck_require__(23991)
-const debug = __nccwpck_require__(86912)
-const SemVer = __nccwpck_require__(95548)
-const Range = __nccwpck_require__(60031)
+};
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
 
 
 /***/ }),
 
-/***/ 60031:
+/***/ 54471:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-const SPACE_CHARACTERS = /\s+/g
+"use strict";
 
-// hoisted class for cyclic dependency
-class Range {
-  constructor (range, options) {
-    options = parseOptions(options)
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
 
-    if (range instanceof Range) {
-      if (
-        range.loose === !!options.loose &&
-        range.includePrerelease === !!options.includePrerelease
-      ) {
-        return range
-      } else {
-        return new Range(range.raw, options)
-      }
-    }
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  endpoint: () => endpoint
+});
+module.exports = __toCommonJS(dist_src_exports);
 
-    if (range instanceof Comparator) {
-      // just put it in the set and return
-      this.raw = range.value
-      this.set = [[range]]
-      this.formatted = undefined
-      return this
-    }
+// pkg/dist-src/defaults.js
+var import_universal_user_agent = __nccwpck_require__(33843);
 
-    this.options = options
-    this.loose = !!options.loose
-    this.includePrerelease = !!options.includePrerelease
+// pkg/dist-src/version.js
+var VERSION = "9.0.4";
 
-    // First reduce all whitespace as much as possible so we do not have to rely
-    // on potentially slow regexes like \s*. This is then stored and used for
-    // future error messages as well.
-    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')
+// pkg/dist-src/defaults.js
+var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;
+var DEFAULTS = {
+  method: "GET",
+  baseUrl: "https://api.github.com",
+  headers: {
+    accept: "application/vnd.github.v3+json",
+    "user-agent": userAgent
+  },
+  mediaType: {
+    format: ""
+  }
+};
 
-    // First, split on ||
-    this.set = this.raw
-      .split('||')
-      // map the range to a 2d array of comparators
-      .map(r => this.parseRange(r.trim()))
-      // throw out any comparator lists that are empty
-      // this generally means that it was not a valid range, which is allowed
-      // in loose mode, but will still throw if the WHOLE range is invalid.
-      .filter(c => c.length)
+// pkg/dist-src/util/lowercase-keys.js
+function lowercaseKeys(object) {
+  if (!object) {
+    return {};
+  }
+  return Object.keys(object).reduce((newObj, key) => {
+    newObj[key.toLowerCase()] = object[key];
+    return newObj;
+  }, {});
+}
 
-    if (!this.set.length) {
-      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
-    }
+// pkg/dist-src/util/is-plain-object.js
+function isPlainObject(value) {
+  if (typeof value !== "object" || value === null)
+    return false;
+  if (Object.prototype.toString.call(value) !== "[object Object]")
+    return false;
+  const proto = Object.getPrototypeOf(value);
+  if (proto === null)
+    return true;
+  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
+  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
+}
 
-    // if we have any that are not the null set, throw out null sets.
-    if (this.set.length > 1) {
-      // keep the first one, in case they're all null sets
-      const first = this.set[0]
-      this.set = this.set.filter(c => !isNullSet(c[0]))
-      if (this.set.length === 0) {
-        this.set = [first]
-      } else if (this.set.length > 1) {
-        // if we have any that are *, then the range is just *
-        for (const c of this.set) {
-          if (c.length === 1 && isAny(c[0])) {
-            this.set = [c]
-            break
-          }
-        }
-      }
+// pkg/dist-src/util/merge-deep.js
+function mergeDeep(defaults, options) {
+  const result = Object.assign({}, defaults);
+  Object.keys(options).forEach((key) => {
+    if (isPlainObject(options[key])) {
+      if (!(key in defaults))
+        Object.assign(result, { [key]: options[key] });
+      else
+        result[key] = mergeDeep(defaults[key], options[key]);
+    } else {
+      Object.assign(result, { [key]: options[key] });
     }
+  });
+  return result;
+}
 
-    this.formatted = undefined
-  }
-
-  get range () {
-    if (this.formatted === undefined) {
-      this.formatted = ''
-      for (let i = 0; i < this.set.length; i++) {
-        if (i > 0) {
-          this.formatted += '||'
-        }
-        const comps = this.set[i]
-        for (let k = 0; k < comps.length; k++) {
-          if (k > 0) {
-            this.formatted += ' '
-          }
-          this.formatted += comps[k].toString().trim()
-        }
-      }
+// pkg/dist-src/util/remove-undefined-properties.js
+function removeUndefinedProperties(obj) {
+  for (const key in obj) {
+    if (obj[key] === void 0) {
+      delete obj[key];
     }
-    return this.formatted
-  }
-
-  format () {
-    return this.range
   }
+  return obj;
+}
 
-  toString () {
-    return this.range
+// pkg/dist-src/merge.js
+function merge(defaults, route, options) {
+  if (typeof route === "string") {
+    let [method, url] = route.split(" ");
+    options = Object.assign(url ? { method, url } : { url: method }, options);
+  } else {
+    options = Object.assign({}, route);
   }
-
-  parseRange (range) {
-    // memoize range parsing for performance.
-    // this is a very hot path, and fully deterministic.
-    const memoOpts =
-      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
-      (this.options.loose && FLAG_LOOSE)
-    const memoKey = memoOpts + ':' + range
-    const cached = cache.get(memoKey)
-    if (cached) {
-      return cached
+  options.headers = lowercaseKeys(options.headers);
+  removeUndefinedProperties(options);
+  removeUndefinedProperties(options.headers);
+  const mergedOptions = mergeDeep(defaults || {}, options);
+  if (options.url === "/graphql") {
+    if (defaults && defaults.mediaType.previews?.length) {
+      mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(
+        (preview) => !mergedOptions.mediaType.previews.includes(preview)
+      ).concat(mergedOptions.mediaType.previews);
     }
+    mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
+  }
+  return mergedOptions;
+}
 
-    const loose = this.options.loose
-    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
-    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
-    range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
-    debug('hyphen replace', range)
-
-    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
-    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
-    debug('comparator trim', range)
-
-    // `~ 1.2.3` => `~1.2.3`
-    range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
-    debug('tilde trim', range)
-
-    // `^ 1.2.3` => `^1.2.3`
-    range = range.replace(re[t.CARETTRIM], caretTrimReplace)
-    debug('caret trim', range)
-
-    // At this point, the range is completely trimmed and
-    // ready to be split into comparators.
+// pkg/dist-src/util/add-query-parameters.js
+function addQueryParameters(url, parameters) {
+  const separator = /\?/.test(url) ? "&" : "?";
+  const names = Object.keys(parameters);
+  if (names.length === 0) {
+    return url;
+  }
+  return url + separator + names.map((name) => {
+    if (name === "q") {
+      return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
+    }
+    return `${name}=${encodeURIComponent(parameters[name])}`;
+  }).join("&");
+}
 
-    let rangeList = range
-      .split(' ')
-      .map(comp => parseComparator(comp, this.options))
-      .join(' ')
-      .split(/\s+/)
-      // >=0.0.0 is equivalent to *
-      .map(comp => replaceGTE0(comp, this.options))
+// pkg/dist-src/util/extract-url-variable-names.js
+var urlVariableRegex = /\{[^}]+\}/g;
+function removeNonChars(variableName) {
+  return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
+}
+function extractUrlVariableNames(url) {
+  const matches = url.match(urlVariableRegex);
+  if (!matches) {
+    return [];
+  }
+  return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
+}
 
-    if (loose) {
-      // in loose mode, throw out any that are not valid comparators
-      rangeList = rangeList.filter(comp => {
-        debug('loose invalid filter', comp, this.options)
-        return !!comp.match(re[t.COMPARATORLOOSE])
-      })
+// pkg/dist-src/util/omit.js
+function omit(object, keysToOmit) {
+  const result = { __proto__: null };
+  for (const key of Object.keys(object)) {
+    if (keysToOmit.indexOf(key) === -1) {
+      result[key] = object[key];
     }
-    debug('range list', rangeList)
+  }
+  return result;
+}
 
-    // if any comparators are the null set, then replace with JUST null set
-    // if more than one comparator, remove any * comparators
-    // also, don't include the same comparator more than once
-    const rangeMap = new Map()
-    const comparators = rangeList.map(comp => new Comparator(comp, this.options))
-    for (const comp of comparators) {
-      if (isNullSet(comp)) {
-        return [comp]
+// pkg/dist-src/util/url-template.js
+function encodeReserved(str) {
+  return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
+    if (!/%[0-9A-Fa-f]/.test(part)) {
+      part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
+    }
+    return part;
+  }).join("");
+}
+function encodeUnreserved(str) {
+  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
+    return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+  });
+}
+function encodeValue(operator, value, key) {
+  value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
+  if (key) {
+    return encodeUnreserved(key) + "=" + value;
+  } else {
+    return value;
+  }
+}
+function isDefined(value) {
+  return value !== void 0 && value !== null;
+}
+function isKeyOperator(operator) {
+  return operator === ";" || operator === "&" || operator === "?";
+}
+function getValues(context, operator, key, modifier) {
+  var value = context[key], result = [];
+  if (isDefined(value) && value !== "") {
+    if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+      value = value.toString();
+      if (modifier && modifier !== "*") {
+        value = value.substring(0, parseInt(modifier, 10));
+      }
+      result.push(
+        encodeValue(operator, value, isKeyOperator(operator) ? key : "")
+      );
+    } else {
+      if (modifier === "*") {
+        if (Array.isArray(value)) {
+          value.filter(isDefined).forEach(function(value2) {
+            result.push(
+              encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
+            );
+          });
+        } else {
+          Object.keys(value).forEach(function(k) {
+            if (isDefined(value[k])) {
+              result.push(encodeValue(operator, value[k], k));
+            }
+          });
+        }
+      } else {
+        const tmp = [];
+        if (Array.isArray(value)) {
+          value.filter(isDefined).forEach(function(value2) {
+            tmp.push(encodeValue(operator, value2));
+          });
+        } else {
+          Object.keys(value).forEach(function(k) {
+            if (isDefined(value[k])) {
+              tmp.push(encodeUnreserved(k));
+              tmp.push(encodeValue(operator, value[k].toString()));
+            }
+          });
+        }
+        if (isKeyOperator(operator)) {
+          result.push(encodeUnreserved(key) + "=" + tmp.join(","));
+        } else if (tmp.length !== 0) {
+          result.push(tmp.join(","));
+        }
       }
-      rangeMap.set(comp.value, comp)
     }
-    if (rangeMap.size > 1 && rangeMap.has('')) {
-      rangeMap.delete('')
+  } else {
+    if (operator === ";") {
+      if (isDefined(value)) {
+        result.push(encodeUnreserved(key));
+      }
+    } else if (value === "" && (operator === "&" || operator === "?")) {
+      result.push(encodeUnreserved(key) + "=");
+    } else if (value === "") {
+      result.push("");
     }
-
-    const result = [...rangeMap.values()]
-    cache.set(memoKey, result)
-    return result
   }
-
-  intersects (range, options) {
-    if (!(range instanceof Range)) {
-      throw new TypeError('a Range is required')
+  return result;
+}
+function parseUrl(template) {
+  return {
+    expand: expand.bind(null, template)
+  };
+}
+function expand(template, context) {
+  var operators = ["+", "#", ".", "/", ";", "?", "&"];
+  template = template.replace(
+    /\{([^\{\}]+)\}|([^\{\}]+)/g,
+    function(_, expression, literal) {
+      if (expression) {
+        let operator = "";
+        const values = [];
+        if (operators.indexOf(expression.charAt(0)) !== -1) {
+          operator = expression.charAt(0);
+          expression = expression.substr(1);
+        }
+        expression.split(/,/g).forEach(function(variable) {
+          var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
+          values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
+        });
+        if (operator && operator !== "+") {
+          var separator = ",";
+          if (operator === "?") {
+            separator = "&";
+          } else if (operator !== "#") {
+            separator = operator;
+          }
+          return (values.length !== 0 ? operator : "") + values.join(separator);
+        } else {
+          return values.join(",");
+        }
+      } else {
+        return encodeReserved(literal);
+      }
     }
-
-    return this.set.some((thisComparators) => {
-      return (
-        isSatisfiable(thisComparators, options) &&
-        range.set.some((rangeComparators) => {
-          return (
-            isSatisfiable(rangeComparators, options) &&
-            thisComparators.every((thisComparator) => {
-              return rangeComparators.every((rangeComparator) => {
-                return thisComparator.intersects(rangeComparator, options)
-              })
-            })
-          )
-        })
-      )
-    })
+  );
+  if (template === "/") {
+    return template;
+  } else {
+    return template.replace(/\/$/, "");
   }
+}
 
-  // if ANY of the sets match ALL of its comparators, then pass
-  test (version) {
-    if (!version) {
-      return false
+// pkg/dist-src/parse.js
+function parse(options) {
+  let method = options.method.toUpperCase();
+  let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
+  let headers = Object.assign({}, options.headers);
+  let body;
+  let parameters = omit(options, [
+    "method",
+    "baseUrl",
+    "url",
+    "headers",
+    "request",
+    "mediaType"
+  ]);
+  const urlVariableNames = extractUrlVariableNames(url);
+  url = parseUrl(url).expand(parameters);
+  if (!/^http/.test(url)) {
+    url = options.baseUrl + url;
+  }
+  const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
+  const remainingParameters = omit(parameters, omittedParameters);
+  const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
+  if (!isBinaryRequest) {
+    if (options.mediaType.format) {
+      headers.accept = headers.accept.split(/,/).map(
+        (format) => format.replace(
+          /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
+          `application/vnd$1$2.${options.mediaType.format}`
+        )
+      ).join(",");
     }
-
-    if (typeof version === 'string') {
-      try {
-        version = new SemVer(version, this.options)
-      } catch (er) {
-        return false
+    if (url.endsWith("/graphql")) {
+      if (options.mediaType.previews?.length) {
+        const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
+        headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
+          const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
+          return `application/vnd.github.${preview}-preview${format}`;
+        }).join(",");
       }
     }
-
-    for (let i = 0; i < this.set.length; i++) {
-      if (testSet(this.set[i], version, this.options)) {
-        return true
+  }
+  if (["GET", "HEAD"].includes(method)) {
+    url = addQueryParameters(url, remainingParameters);
+  } else {
+    if ("data" in remainingParameters) {
+      body = remainingParameters.data;
+    } else {
+      if (Object.keys(remainingParameters).length) {
+        body = remainingParameters;
       }
     }
-    return false
   }
+  if (!headers["content-type"] && typeof body !== "undefined") {
+    headers["content-type"] = "application/json; charset=utf-8";
+  }
+  if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
+    body = "";
+  }
+  return Object.assign(
+    { method, url, headers },
+    typeof body !== "undefined" ? { body } : null,
+    options.request ? { request: options.request } : null
+  );
 }
 
-module.exports = Range
-
-const LRU = __nccwpck_require__(35986)
-const cache = new LRU()
-
-const parseOptions = __nccwpck_require__(65939)
-const Comparator = __nccwpck_require__(39768)
-const debug = __nccwpck_require__(86912)
-const SemVer = __nccwpck_require__(95548)
-const {
-  safeRe: re,
-  t,
-  comparatorTrimReplace,
-  tildeTrimReplace,
-  caretTrimReplace,
-} = __nccwpck_require__(84894)
-const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(83074)
+// pkg/dist-src/endpoint-with-defaults.js
+function endpointWithDefaults(defaults, route, options) {
+  return parse(merge(defaults, route, options));
+}
 
-const isNullSet = c => c.value === '<0.0.0-0'
-const isAny = c => c.value === ''
+// pkg/dist-src/with-defaults.js
+function withDefaults(oldDefaults, newDefaults) {
+  const DEFAULTS2 = merge(oldDefaults, newDefaults);
+  const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
+  return Object.assign(endpoint2, {
+    DEFAULTS: DEFAULTS2,
+    defaults: withDefaults.bind(null, DEFAULTS2),
+    merge: merge.bind(null, DEFAULTS2),
+    parse
+  });
+}
 
-// take a set of comparators and determine whether there
-// exists a version which can satisfy it
-const isSatisfiable = (comparators, options) => {
-  let result = true
-  const remainingComparators = comparators.slice()
-  let testComparator = remainingComparators.pop()
+// pkg/dist-src/index.js
+var endpoint = withDefaults(null, DEFAULTS);
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
 
-  while (result && remainingComparators.length) {
-    result = remainingComparators.every((otherComparator) => {
-      return testComparator.intersects(otherComparator, options)
-    })
 
-    testComparator = remainingComparators.pop()
-  }
+/***/ }),
 
-  return result
-}
+/***/ 70007:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-// comprised of xranges, tildes, stars, and gtlt's at this point.
-// already replaced the hyphen ranges
-// turn into a set of JUST comparators.
-const parseComparator = (comp, options) => {
-  debug('comp', comp, options)
-  comp = replaceCarets(comp, options)
-  debug('caret', comp)
-  comp = replaceTildes(comp, options)
-  debug('tildes', comp)
-  comp = replaceXRanges(comp, options)
-  debug('xrange', comp)
-  comp = replaceStars(comp, options)
-  debug('stars', comp)
-  return comp
-}
+"use strict";
 
-const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
 
-// ~, ~> --> * (any, kinda silly)
-// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
-// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
-// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
-// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
-// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
-// ~0.0.1 --> >=0.0.1 <0.1.0-0
-const replaceTildes = (comp, options) => {
-  return comp
-    .trim()
-    .split(/\s+/)
-    .map((c) => replaceTilde(c, options))
-    .join(' ')
-}
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  GraphqlResponseError: () => GraphqlResponseError,
+  graphql: () => graphql2,
+  withCustomRequest: () => withCustomRequest
+});
+module.exports = __toCommonJS(dist_src_exports);
+var import_request3 = __nccwpck_require__(66255);
+var import_universal_user_agent = __nccwpck_require__(33843);
 
-const replaceTilde = (comp, options) => {
-  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
-  return comp.replace(r, (_, M, m, p, pr) => {
-    debug('tilde', comp, _, M, m, p, pr)
-    let ret
+// pkg/dist-src/version.js
+var VERSION = "7.0.2";
 
-    if (isX(M)) {
-      ret = ''
-    } else if (isX(m)) {
-      ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
-    } else if (isX(p)) {
-      // ~1.2 == >=1.2.0 <1.3.0-0
-      ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
-    } else if (pr) {
-      debug('replaceTilde pr', pr)
-      ret = `>=${M}.${m}.${p}-${pr
-      } <${M}.${+m + 1}.0-0`
-    } else {
-      // ~1.2.3 == >=1.2.3 <1.3.0-0
-      ret = `>=${M}.${m}.${p
-      } <${M}.${+m + 1}.0-0`
-    }
+// pkg/dist-src/with-defaults.js
+var import_request2 = __nccwpck_require__(66255);
 
-    debug('tilde return', ret)
-    return ret
-  })
-}
+// pkg/dist-src/graphql.js
+var import_request = __nccwpck_require__(66255);
 
-// ^ --> * (any, kinda silly)
-// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
-// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
-// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
-// ^1.2.3 --> >=1.2.3 <2.0.0-0
-// ^1.2.0 --> >=1.2.0 <2.0.0-0
-// ^0.0.1 --> >=0.0.1 <0.0.2-0
-// ^0.1.0 --> >=0.1.0 <0.2.0-0
-const replaceCarets = (comp, options) => {
-  return comp
-    .trim()
-    .split(/\s+/)
-    .map((c) => replaceCaret(c, options))
-    .join(' ')
+// pkg/dist-src/error.js
+function _buildMessageForResponseErrors(data) {
+  return `Request failed due to following response errors:
+` + data.errors.map((e) => ` - ${e.message}`).join("\n");
 }
+var GraphqlResponseError = class extends Error {
+  constructor(request2, headers, response) {
+    super(_buildMessageForResponseErrors(response));
+    this.request = request2;
+    this.headers = headers;
+    this.response = response;
+    this.name = "GraphqlResponseError";
+    this.errors = response.errors;
+    this.data = response.data;
+    if (Error.captureStackTrace) {
+      Error.captureStackTrace(this, this.constructor);
+    }
+  }
+};
 
-const replaceCaret = (comp, options) => {
-  debug('caret', comp, options)
-  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
-  const z = options.includePrerelease ? '-0' : ''
-  return comp.replace(r, (_, M, m, p, pr) => {
-    debug('caret', comp, _, M, m, p, pr)
-    let ret
-
-    if (isX(M)) {
-      ret = ''
-    } else if (isX(m)) {
-      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
-    } else if (isX(p)) {
-      if (M === '0') {
-        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
-      } else {
-        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
-      }
-    } else if (pr) {
-      debug('replaceCaret pr', pr)
-      if (M === '0') {
-        if (m === '0') {
-          ret = `>=${M}.${m}.${p}-${pr
-          } <${M}.${m}.${+p + 1}-0`
-        } else {
-          ret = `>=${M}.${m}.${p}-${pr
-          } <${M}.${+m + 1}.0-0`
-        }
-      } else {
-        ret = `>=${M}.${m}.${p}-${pr
-        } <${+M + 1}.0.0-0`
-      }
-    } else {
-      debug('no pr')
-      if (M === '0') {
-        if (m === '0') {
-          ret = `>=${M}.${m}.${p
-          }${z} <${M}.${m}.${+p + 1}-0`
-        } else {
-          ret = `>=${M}.${m}.${p
-          }${z} <${M}.${+m + 1}.0-0`
-        }
-      } else {
-        ret = `>=${M}.${m}.${p
-        } <${+M + 1}.0.0-0`
-      }
-    }
-
-    debug('caret return', ret)
-    return ret
-  })
-}
-
-const replaceXRanges = (comp, options) => {
-  debug('replaceXRanges', comp, options)
-  return comp
-    .split(/\s+/)
-    .map((c) => replaceXRange(c, options))
-    .join(' ')
-}
-
-const replaceXRange = (comp, options) => {
-  comp = comp.trim()
-  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
-  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
-    debug('xRange', comp, ret, gtlt, M, m, p, pr)
-    const xM = isX(M)
-    const xm = xM || isX(m)
-    const xp = xm || isX(p)
-    const anyX = xp
-
-    if (gtlt === '=' && anyX) {
-      gtlt = ''
+// pkg/dist-src/graphql.js
+var NON_VARIABLE_OPTIONS = [
+  "method",
+  "baseUrl",
+  "url",
+  "headers",
+  "request",
+  "query",
+  "mediaType"
+];
+var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
+var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
+function graphql(request2, query, options) {
+  if (options) {
+    if (typeof query === "string" && "query" in options) {
+      return Promise.reject(
+        new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
+      );
     }
-
-    // if we're including prereleases in the match, then we need
-    // to fix this to -0, the lowest possible prerelease value
-    pr = options.includePrerelease ? '-0' : ''
-
-    if (xM) {
-      if (gtlt === '>' || gtlt === '<') {
-        // nothing is allowed
-        ret = '<0.0.0-0'
-      } else {
-        // nothing is forbidden
-        ret = '*'
-      }
-    } else if (gtlt && anyX) {
-      // we know patch is an x, because we have any x at all.
-      // replace X with 0
-      if (xm) {
-        m = 0
-      }
-      p = 0
-
-      if (gtlt === '>') {
-        // >1 => >=2.0.0
-        // >1.2 => >=1.3.0
-        gtlt = '>='
-        if (xm) {
-          M = +M + 1
-          m = 0
-          p = 0
-        } else {
-          m = +m + 1
-          p = 0
-        }
-      } else if (gtlt === '<=') {
-        // <=0.7.x is actually <0.8.0, since any 0.7.x should
-        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
-        gtlt = '<'
-        if (xm) {
-          M = +M + 1
-        } else {
-          m = +m + 1
-        }
-      }
-
-      if (gtlt === '<') {
-        pr = '-0'
-      }
-
-      ret = `${gtlt + M}.${m}.${p}${pr}`
-    } else if (xm) {
-      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
-    } else if (xp) {
-      ret = `>=${M}.${m}.0${pr
-      } <${M}.${+m + 1}.0-0`
+    for (const key in options) {
+      if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
+        continue;
+      return Promise.reject(
+        new Error(
+          `[@octokit/graphql] "${key}" cannot be used as variable name`
+        )
+      );
     }
-
-    debug('xRange return', ret)
-
-    return ret
-  })
-}
-
-// Because * is AND-ed with everything else in the comparator,
-// and '' means "any version", just remove the *s entirely.
-const replaceStars = (comp, options) => {
-  debug('replaceStars', comp, options)
-  // Looseness is ignored here.  star is always as loose as it gets!
-  return comp
-    .trim()
-    .replace(re[t.STAR], '')
-}
-
-const replaceGTE0 = (comp, options) => {
-  debug('replaceGTE0', comp, options)
-  return comp
-    .trim()
-    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
-}
-
-// This function is passed to string.replace(re[t.HYPHENRANGE])
-// M, m, patch, prerelease, build
-// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
-// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
-// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
-// TODO build?
-const hyphenReplace = incPr => ($0,
-  from, fM, fm, fp, fpr, fb,
-  to, tM, tm, tp, tpr) => {
-  if (isX(fM)) {
-    from = ''
-  } else if (isX(fm)) {
-    from = `>=${fM}.0.0${incPr ? '-0' : ''}`
-  } else if (isX(fp)) {
-    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
-  } else if (fpr) {
-    from = `>=${from}`
-  } else {
-    from = `>=${from}${incPr ? '-0' : ''}`
-  }
-
-  if (isX(tM)) {
-    to = ''
-  } else if (isX(tm)) {
-    to = `<${+tM + 1}.0.0-0`
-  } else if (isX(tp)) {
-    to = `<${tM}.${+tm + 1}.0-0`
-  } else if (tpr) {
-    to = `<=${tM}.${tm}.${tp}-${tpr}`
-  } else if (incPr) {
-    to = `<${tM}.${tm}.${+tp + 1}-0`
-  } else {
-    to = `<=${to}`
   }
-
-  return `${from} ${to}`.trim()
-}
-
-const testSet = (set, version, options) => {
-  for (let i = 0; i < set.length; i++) {
-    if (!set[i].test(version)) {
-      return false
+  const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
+  const requestOptions = Object.keys(
+    parsedOptions
+  ).reduce((result, key) => {
+    if (NON_VARIABLE_OPTIONS.includes(key)) {
+      result[key] = parsedOptions[key];
+      return result;
+    }
+    if (!result.variables) {
+      result.variables = {};
     }
+    result.variables[key] = parsedOptions[key];
+    return result;
+  }, {});
+  const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;
+  if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
+    requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
   }
-
-  if (version.prerelease.length && !options.includePrerelease) {
-    // Find the set of versions that are allowed to have prereleases
-    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
-    // That should allow `1.2.3-pr.2` to pass.
-    // However, `1.2.4-alpha.notready` should NOT be allowed,
-    // even though it's within the range set by the comparators.
-    for (let i = 0; i < set.length; i++) {
-      debug(set[i].semver)
-      if (set[i].semver === Comparator.ANY) {
-        continue
-      }
-
-      if (set[i].semver.prerelease.length > 0) {
-        const allowed = set[i].semver
-        if (allowed.major === version.major &&
-            allowed.minor === version.minor &&
-            allowed.patch === version.patch) {
-          return true
-        }
+  return request2(requestOptions).then((response) => {
+    if (response.data.errors) {
+      const headers = {};
+      for (const key of Object.keys(response.headers)) {
+        headers[key] = response.headers[key];
       }
+      throw new GraphqlResponseError(
+        requestOptions,
+        headers,
+        response.data
+      );
     }
+    return response.data.data;
+  });
+}
 
-    // Version has a -pre, but it's not one of the ones we like.
-    return false
-  }
+// pkg/dist-src/with-defaults.js
+function withDefaults(request2, newDefaults) {
+  const newRequest = request2.defaults(newDefaults);
+  const newApi = (query, options) => {
+    return graphql(newRequest, query, options);
+  };
+  return Object.assign(newApi, {
+    defaults: withDefaults.bind(null, newRequest),
+    endpoint: newRequest.endpoint
+  });
+}
 
-  return true
+// pkg/dist-src/index.js
+var graphql2 = withDefaults(import_request3.request, {
+  headers: {
+    "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
+  },
+  method: "POST",
+  url: "/graphql"
+});
+function withCustomRequest(customRequest) {
+  return withDefaults(customRequest, {
+    method: "POST",
+    url: "/graphql"
+  });
 }
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
 
 
 /***/ }),
 
-/***/ 95548:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const debug = __nccwpck_require__(86912)
-const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(83074)
-const { safeRe: re, safeSrc: src, t } = __nccwpck_require__(84894)
-
-const parseOptions = __nccwpck_require__(65939)
-const { compareIdentifiers } = __nccwpck_require__(98219)
-class SemVer {
-  constructor (version, options) {
-    options = parseOptions(options)
-
-    if (version instanceof SemVer) {
-      if (version.loose === !!options.loose &&
-        version.includePrerelease === !!options.includePrerelease) {
-        return version
-      } else {
-        version = version.version
-      }
-    } else if (typeof version !== 'string') {
-      throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
-    }
-
-    if (version.length > MAX_LENGTH) {
-      throw new TypeError(
-        `version is longer than ${MAX_LENGTH} characters`
-      )
-    }
-
-    debug('SemVer', version, options)
-    this.options = options
-    this.loose = !!options.loose
-    // this isn't actually relevant for versions, but keep it so that we
-    // don't run into trouble passing this.options around.
-    this.includePrerelease = !!options.includePrerelease
-
-    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
-
-    if (!m) {
-      throw new TypeError(`Invalid Version: ${version}`)
-    }
-
-    this.raw = version
-
-    // these are actually numbers
-    this.major = +m[1]
-    this.minor = +m[2]
-    this.patch = +m[3]
+/***/ 38082:
+/***/ ((module) => {
 
-    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
-      throw new TypeError('Invalid major version')
-    }
+"use strict";
 
-    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
-      throw new TypeError('Invalid minor version')
-    }
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
 
-    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
-      throw new TypeError('Invalid patch version')
-    }
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  composePaginateRest: () => composePaginateRest,
+  isPaginatingEndpoint: () => isPaginatingEndpoint,
+  paginateRest: () => paginateRest,
+  paginatingEndpoints: () => paginatingEndpoints
+});
+module.exports = __toCommonJS(dist_src_exports);
 
-    // numberify any prerelease numeric ids
-    if (!m[4]) {
-      this.prerelease = []
-    } else {
-      this.prerelease = m[4].split('.').map((id) => {
-        if (/^[0-9]+$/.test(id)) {
-          const num = +id
-          if (num >= 0 && num < MAX_SAFE_INTEGER) {
-            return num
-          }
-        }
-        return id
-      })
-    }
+// pkg/dist-src/version.js
+var VERSION = "9.2.2";
 
-    this.build = m[5] ? m[5].split('.') : []
-    this.format()
+// pkg/dist-src/normalize-paginated-list-response.js
+function normalizePaginatedListResponse(response) {
+  if (!response.data) {
+    return {
+      ...response,
+      data: []
+    };
   }
-
-  format () {
-    this.version = `${this.major}.${this.minor}.${this.patch}`
-    if (this.prerelease.length) {
-      this.version += `-${this.prerelease.join('.')}`
-    }
-    return this.version
+  const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
+  if (!responseNeedsNormalization)
+    return response;
+  const incompleteResults = response.data.incomplete_results;
+  const repositorySelection = response.data.repository_selection;
+  const totalCount = response.data.total_count;
+  delete response.data.incomplete_results;
+  delete response.data.repository_selection;
+  delete response.data.total_count;
+  const namespaceKey = Object.keys(response.data)[0];
+  const data = response.data[namespaceKey];
+  response.data = data;
+  if (typeof incompleteResults !== "undefined") {
+    response.data.incomplete_results = incompleteResults;
   }
-
-  toString () {
-    return this.version
+  if (typeof repositorySelection !== "undefined") {
+    response.data.repository_selection = repositorySelection;
   }
+  response.data.total_count = totalCount;
+  return response;
+}
 
-  compare (other) {
-    debug('SemVer.compare', this.version, this.options, other)
-    if (!(other instanceof SemVer)) {
-      if (typeof other === 'string' && other === this.version) {
-        return 0
+// pkg/dist-src/iterator.js
+function iterator(octokit, route, parameters) {
+  const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
+  const requestMethod = typeof route === "function" ? route : octokit.request;
+  const method = options.method;
+  const headers = options.headers;
+  let url = options.url;
+  return {
+    [Symbol.asyncIterator]: () => ({
+      async next() {
+        if (!url)
+          return { done: true };
+        try {
+          const response = await requestMethod({ method, url, headers });
+          const normalizedResponse = normalizePaginatedListResponse(response);
+          url = ((normalizedResponse.headers.link || "").match(
+            /<([^<>]+)>;\s*rel="next"/
+          ) || [])[1];
+          return { value: normalizedResponse };
+        } catch (error) {
+          if (error.status !== 409)
+            throw error;
+          url = "";
+          return {
+            value: {
+              status: 200,
+              headers: {},
+              data: []
+            }
+          };
+        }
       }
-      other = new SemVer(other, this.options)
-    }
-
-    if (other.version === this.version) {
-      return 0
-    }
+    })
+  };
+}
 
-    return this.compareMain(other) || this.comparePre(other)
+// pkg/dist-src/paginate.js
+function paginate(octokit, route, parameters, mapFn) {
+  if (typeof parameters === "function") {
+    mapFn = parameters;
+    parameters = void 0;
   }
-
-  compareMain (other) {
-    if (!(other instanceof SemVer)) {
-      other = new SemVer(other, this.options)
+  return gather(
+    octokit,
+    [],
+    iterator(octokit, route, parameters)[Symbol.asyncIterator](),
+    mapFn
+  );
+}
+function gather(octokit, results, iterator2, mapFn) {
+  return iterator2.next().then((result) => {
+    if (result.done) {
+      return results;
     }
-
-    return (
-      compareIdentifiers(this.major, other.major) ||
-      compareIdentifiers(this.minor, other.minor) ||
-      compareIdentifiers(this.patch, other.patch)
-    )
-  }
-
-  comparePre (other) {
-    if (!(other instanceof SemVer)) {
-      other = new SemVer(other, this.options)
+    let earlyExit = false;
+    function done() {
+      earlyExit = true;
     }
-
-    // NOT having a prerelease is > having one
-    if (this.prerelease.length && !other.prerelease.length) {
-      return -1
-    } else if (!this.prerelease.length && other.prerelease.length) {
-      return 1
-    } else if (!this.prerelease.length && !other.prerelease.length) {
-      return 0
+    results = results.concat(
+      mapFn ? mapFn(result.value, done) : result.value.data
+    );
+    if (earlyExit) {
+      return results;
     }
+    return gather(octokit, results, iterator2, mapFn);
+  });
+}
 
-    let i = 0
-    do {
-      const a = this.prerelease[i]
-      const b = other.prerelease[i]
-      debug('prerelease compare', i, a, b)
-      if (a === undefined && b === undefined) {
-        return 0
-      } else if (b === undefined) {
-        return 1
-      } else if (a === undefined) {
-        return -1
-      } else if (a === b) {
-        continue
-      } else {
-        return compareIdentifiers(a, b)
-      }
-    } while (++i)
-  }
-
-  compareBuild (other) {
-    if (!(other instanceof SemVer)) {
-      other = new SemVer(other, this.options)
-    }
-
-    let i = 0
-    do {
-      const a = this.build[i]
-      const b = other.build[i]
-      debug('build compare', i, a, b)
-      if (a === undefined && b === undefined) {
-        return 0
-      } else if (b === undefined) {
-        return 1
-      } else if (a === undefined) {
-        return -1
-      } else if (a === b) {
-        continue
-      } else {
-        return compareIdentifiers(a, b)
-      }
-    } while (++i)
-  }
-
-  // preminor will bump the version up to the next minor release, and immediately
-  // down to pre-release. premajor and prepatch work the same way.
-  inc (release, identifier, identifierBase) {
-    if (release.startsWith('pre')) {
-      if (!identifier && identifierBase === false) {
-        throw new Error('invalid increment argument: identifier is empty')
-      }
-      // Avoid an invalid semver results
-      if (identifier) {
-        const r = new RegExp(`^${this.options.loose ? src[t.PRERELEASELOOSE] : src[t.PRERELEASE]}$`)
-        const match = `-${identifier}`.match(r)
-        if (!match || match[1] !== identifier) {
-          throw new Error(`invalid identifier: ${identifier}`)
-        }
-      }
-    }
-
-    switch (release) {
-      case 'premajor':
-        this.prerelease.length = 0
-        this.patch = 0
-        this.minor = 0
-        this.major++
-        this.inc('pre', identifier, identifierBase)
-        break
-      case 'preminor':
-        this.prerelease.length = 0
-        this.patch = 0
-        this.minor++
-        this.inc('pre', identifier, identifierBase)
-        break
-      case 'prepatch':
-        // If this is already a prerelease, it will bump to the next version
-        // drop any prereleases that might already exist, since they are not
-        // relevant at this point.
-        this.prerelease.length = 0
-        this.inc('patch', identifier, identifierBase)
-        this.inc('pre', identifier, identifierBase)
-        break
-      // If the input is a non-prerelease version, this acts the same as
-      // prepatch.
-      case 'prerelease':
-        if (this.prerelease.length === 0) {
-          this.inc('patch', identifier, identifierBase)
-        }
-        this.inc('pre', identifier, identifierBase)
-        break
-      case 'release':
-        if (this.prerelease.length === 0) {
-          throw new Error(`version ${this.raw} is not a prerelease`)
-        }
-        this.prerelease.length = 0
-        break
+// pkg/dist-src/compose-paginate.js
+var composePaginateRest = Object.assign(paginate, {
+  iterator
+});
 
-      case 'major':
-        // If this is a pre-major version, bump up to the same major version.
-        // Otherwise increment major.
-        // 1.0.0-5 bumps to 1.0.0
-        // 1.1.0 bumps to 2.0.0
-        if (
-          this.minor !== 0 ||
-          this.patch !== 0 ||
-          this.prerelease.length === 0
-        ) {
-          this.major++
-        }
-        this.minor = 0
-        this.patch = 0
-        this.prerelease = []
-        break
-      case 'minor':
-        // If this is a pre-minor version, bump up to the same minor version.
-        // Otherwise increment minor.
-        // 1.2.0-5 bumps to 1.2.0
-        // 1.2.1 bumps to 1.3.0
-        if (this.patch !== 0 || this.prerelease.length === 0) {
-          this.minor++
-        }
-        this.patch = 0
-        this.prerelease = []
-        break
-      case 'patch':
-        // If this is not a pre-release version, it will increment the patch.
-        // If it is a pre-release it will bump up to the same patch version.
-        // 1.2.0-5 patches to 1.2.0
-        // 1.2.0 patches to 1.2.1
-        if (this.prerelease.length === 0) {
-          this.patch++
-        }
-        this.prerelease = []
-        break
-      // This probably shouldn't be used publicly.
-      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
-      case 'pre': {
-        const base = Number(identifierBase) ? 1 : 0
+// pkg/dist-src/generated/paginating-endpoints.js
+var paginatingEndpoints = [
+  "GET /advisories",
+  "GET /app/hook/deliveries",
+  "GET /app/installation-requests",
+  "GET /app/installations",
+  "GET /assignments/{assignment_id}/accepted_assignments",
+  "GET /classrooms",
+  "GET /classrooms/{classroom_id}/assignments",
+  "GET /enterprises/{enterprise}/dependabot/alerts",
+  "GET /enterprises/{enterprise}/secret-scanning/alerts",
+  "GET /events",
+  "GET /gists",
+  "GET /gists/public",
+  "GET /gists/starred",
+  "GET /gists/{gist_id}/comments",
+  "GET /gists/{gist_id}/commits",
+  "GET /gists/{gist_id}/forks",
+  "GET /installation/repositories",
+  "GET /issues",
+  "GET /licenses",
+  "GET /marketplace_listing/plans",
+  "GET /marketplace_listing/plans/{plan_id}/accounts",
+  "GET /marketplace_listing/stubbed/plans",
+  "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
+  "GET /networks/{owner}/{repo}/events",
+  "GET /notifications",
+  "GET /organizations",
+  "GET /orgs/{org}/actions/cache/usage-by-repository",
+  "GET /orgs/{org}/actions/permissions/repositories",
+  "GET /orgs/{org}/actions/runners",
+  "GET /orgs/{org}/actions/secrets",
+  "GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
+  "GET /orgs/{org}/actions/variables",
+  "GET /orgs/{org}/actions/variables/{name}/repositories",
+  "GET /orgs/{org}/blocks",
+  "GET /orgs/{org}/code-scanning/alerts",
+  "GET /orgs/{org}/codespaces",
+  "GET /orgs/{org}/codespaces/secrets",
+  "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories",
+  "GET /orgs/{org}/copilot/billing/seats",
+  "GET /orgs/{org}/dependabot/alerts",
+  "GET /orgs/{org}/dependabot/secrets",
+  "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
+  "GET /orgs/{org}/events",
+  "GET /orgs/{org}/failed_invitations",
+  "GET /orgs/{org}/hooks",
+  "GET /orgs/{org}/hooks/{hook_id}/deliveries",
+  "GET /orgs/{org}/installations",
+  "GET /orgs/{org}/invitations",
+  "GET /orgs/{org}/invitations/{invitation_id}/teams",
+  "GET /orgs/{org}/issues",
+  "GET /orgs/{org}/members",
+  "GET /orgs/{org}/members/{username}/codespaces",
+  "GET /orgs/{org}/migrations",
+  "GET /orgs/{org}/migrations/{migration_id}/repositories",
+  "GET /orgs/{org}/organization-roles/{role_id}/teams",
+  "GET /orgs/{org}/organization-roles/{role_id}/users",
+  "GET /orgs/{org}/outside_collaborators",
+  "GET /orgs/{org}/packages",
+  "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
+  "GET /orgs/{org}/personal-access-token-requests",
+  "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories",
+  "GET /orgs/{org}/personal-access-tokens",
+  "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories",
+  "GET /orgs/{org}/projects",
+  "GET /orgs/{org}/properties/values",
+  "GET /orgs/{org}/public_members",
+  "GET /orgs/{org}/repos",
+  "GET /orgs/{org}/rulesets",
+  "GET /orgs/{org}/rulesets/rule-suites",
+  "GET /orgs/{org}/secret-scanning/alerts",
+  "GET /orgs/{org}/security-advisories",
+  "GET /orgs/{org}/teams",
+  "GET /orgs/{org}/teams/{team_slug}/discussions",
+  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
+  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
+  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
+  "GET /orgs/{org}/teams/{team_slug}/invitations",
+  "GET /orgs/{org}/teams/{team_slug}/members",
+  "GET /orgs/{org}/teams/{team_slug}/projects",
+  "GET /orgs/{org}/teams/{team_slug}/repos",
+  "GET /orgs/{org}/teams/{team_slug}/teams",
+  "GET /projects/columns/{column_id}/cards",
+  "GET /projects/{project_id}/collaborators",
+  "GET /projects/{project_id}/columns",
+  "GET /repos/{owner}/{repo}/actions/artifacts",
+  "GET /repos/{owner}/{repo}/actions/caches",
+  "GET /repos/{owner}/{repo}/actions/organization-secrets",
+  "GET /repos/{owner}/{repo}/actions/organization-variables",
+  "GET /repos/{owner}/{repo}/actions/runners",
+  "GET /repos/{owner}/{repo}/actions/runs",
+  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
+  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
+  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
+  "GET /repos/{owner}/{repo}/actions/secrets",
+  "GET /repos/{owner}/{repo}/actions/variables",
+  "GET /repos/{owner}/{repo}/actions/workflows",
+  "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
+  "GET /repos/{owner}/{repo}/activity",
+  "GET /repos/{owner}/{repo}/assignees",
+  "GET /repos/{owner}/{repo}/branches",
+  "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
+  "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
+  "GET /repos/{owner}/{repo}/code-scanning/alerts",
+  "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
+  "GET /repos/{owner}/{repo}/code-scanning/analyses",
+  "GET /repos/{owner}/{repo}/codespaces",
+  "GET /repos/{owner}/{repo}/codespaces/devcontainers",
+  "GET /repos/{owner}/{repo}/codespaces/secrets",
+  "GET /repos/{owner}/{repo}/collaborators",
+  "GET /repos/{owner}/{repo}/comments",
+  "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
+  "GET /repos/{owner}/{repo}/commits",
+  "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
+  "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
+  "GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
+  "GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
+  "GET /repos/{owner}/{repo}/commits/{ref}/status",
+  "GET /repos/{owner}/{repo}/commits/{ref}/statuses",
+  "GET /repos/{owner}/{repo}/contributors",
+  "GET /repos/{owner}/{repo}/dependabot/alerts",
+  "GET /repos/{owner}/{repo}/dependabot/secrets",
+  "GET /repos/{owner}/{repo}/deployments",
+  "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
+  "GET /repos/{owner}/{repo}/environments",
+  "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies",
+  "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps",
+  "GET /repos/{owner}/{repo}/events",
+  "GET /repos/{owner}/{repo}/forks",
+  "GET /repos/{owner}/{repo}/hooks",
+  "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
+  "GET /repos/{owner}/{repo}/invitations",
+  "GET /repos/{owner}/{repo}/issues",
+  "GET /repos/{owner}/{repo}/issues/comments",
+  "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
+  "GET /repos/{owner}/{repo}/issues/events",
+  "GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
+  "GET /repos/{owner}/{repo}/issues/{issue_number}/events",
+  "GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
+  "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
+  "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
+  "GET /repos/{owner}/{repo}/keys",
+  "GET /repos/{owner}/{repo}/labels",
+  "GET /repos/{owner}/{repo}/milestones",
+  "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
+  "GET /repos/{owner}/{repo}/notifications",
+  "GET /repos/{owner}/{repo}/pages/builds",
+  "GET /repos/{owner}/{repo}/projects",
+  "GET /repos/{owner}/{repo}/pulls",
+  "GET /repos/{owner}/{repo}/pulls/comments",
+  "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
+  "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
+  "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
+  "GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
+  "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
+  "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
+  "GET /repos/{owner}/{repo}/releases",
+  "GET /repos/{owner}/{repo}/releases/{release_id}/assets",
+  "GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
+  "GET /repos/{owner}/{repo}/rules/branches/{branch}",
+  "GET /repos/{owner}/{repo}/rulesets",
+  "GET /repos/{owner}/{repo}/rulesets/rule-suites",
+  "GET /repos/{owner}/{repo}/secret-scanning/alerts",
+  "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
+  "GET /repos/{owner}/{repo}/security-advisories",
+  "GET /repos/{owner}/{repo}/stargazers",
+  "GET /repos/{owner}/{repo}/subscribers",
+  "GET /repos/{owner}/{repo}/tags",
+  "GET /repos/{owner}/{repo}/teams",
+  "GET /repos/{owner}/{repo}/topics",
+  "GET /repositories",
+  "GET /repositories/{repository_id}/environments/{environment_name}/secrets",
+  "GET /repositories/{repository_id}/environments/{environment_name}/variables",
+  "GET /search/code",
+  "GET /search/commits",
+  "GET /search/issues",
+  "GET /search/labels",
+  "GET /search/repositories",
+  "GET /search/topics",
+  "GET /search/users",
+  "GET /teams/{team_id}/discussions",
+  "GET /teams/{team_id}/discussions/{discussion_number}/comments",
+  "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
+  "GET /teams/{team_id}/discussions/{discussion_number}/reactions",
+  "GET /teams/{team_id}/invitations",
+  "GET /teams/{team_id}/members",
+  "GET /teams/{team_id}/projects",
+  "GET /teams/{team_id}/repos",
+  "GET /teams/{team_id}/teams",
+  "GET /user/blocks",
+  "GET /user/codespaces",
+  "GET /user/codespaces/secrets",
+  "GET /user/emails",
+  "GET /user/followers",
+  "GET /user/following",
+  "GET /user/gpg_keys",
+  "GET /user/installations",
+  "GET /user/installations/{installation_id}/repositories",
+  "GET /user/issues",
+  "GET /user/keys",
+  "GET /user/marketplace_purchases",
+  "GET /user/marketplace_purchases/stubbed",
+  "GET /user/memberships/orgs",
+  "GET /user/migrations",
+  "GET /user/migrations/{migration_id}/repositories",
+  "GET /user/orgs",
+  "GET /user/packages",
+  "GET /user/packages/{package_type}/{package_name}/versions",
+  "GET /user/public_emails",
+  "GET /user/repos",
+  "GET /user/repository_invitations",
+  "GET /user/social_accounts",
+  "GET /user/ssh_signing_keys",
+  "GET /user/starred",
+  "GET /user/subscriptions",
+  "GET /user/teams",
+  "GET /users",
+  "GET /users/{username}/events",
+  "GET /users/{username}/events/orgs/{org}",
+  "GET /users/{username}/events/public",
+  "GET /users/{username}/followers",
+  "GET /users/{username}/following",
+  "GET /users/{username}/gists",
+  "GET /users/{username}/gpg_keys",
+  "GET /users/{username}/keys",
+  "GET /users/{username}/orgs",
+  "GET /users/{username}/packages",
+  "GET /users/{username}/projects",
+  "GET /users/{username}/received_events",
+  "GET /users/{username}/received_events/public",
+  "GET /users/{username}/repos",
+  "GET /users/{username}/social_accounts",
+  "GET /users/{username}/ssh_signing_keys",
+  "GET /users/{username}/starred",
+  "GET /users/{username}/subscriptions"
+];
 
-        if (this.prerelease.length === 0) {
-          this.prerelease = [base]
-        } else {
-          let i = this.prerelease.length
-          while (--i >= 0) {
-            if (typeof this.prerelease[i] === 'number') {
-              this.prerelease[i]++
-              i = -2
-            }
-          }
-          if (i === -1) {
-            // didn't increment anything
-            if (identifier === this.prerelease.join('.') && identifierBase === false) {
-              throw new Error('invalid increment argument: identifier already exists')
-            }
-            this.prerelease.push(base)
-          }
-        }
-        if (identifier) {
-          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
-          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
-          let prerelease = [identifier, base]
-          if (identifierBase === false) {
-            prerelease = [identifier]
-          }
-          if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
-            if (isNaN(this.prerelease[1])) {
-              this.prerelease = prerelease
-            }
-          } else {
-            this.prerelease = prerelease
-          }
-        }
-        break
-      }
-      default:
-        throw new Error(`invalid increment argument: ${release}`)
-    }
-    this.raw = this.format()
-    if (this.build.length) {
-      this.raw += `+${this.build.join('.')}`
-    }
-    return this
+// pkg/dist-src/paginating-endpoints.js
+function isPaginatingEndpoint(arg) {
+  if (typeof arg === "string") {
+    return paginatingEndpoints.includes(arg);
+  } else {
+    return false;
   }
 }
 
-module.exports = SemVer
-
-
-/***/ }),
-
-/***/ 64510:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const parse = __nccwpck_require__(45240)
-const clean = (version, options) => {
-  const s = parse(version.trim().replace(/^[=v]+/, ''), options)
-  return s ? s.version : null
+// pkg/dist-src/index.js
+function paginateRest(octokit) {
+  return {
+    paginate: Object.assign(paginate.bind(null, octokit), {
+      iterator: iterator.bind(null, octokit)
+    })
+  };
 }
-module.exports = clean
+paginateRest.VERSION = VERSION;
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
 
 
 /***/ }),
 
-/***/ 23991:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const eq = __nccwpck_require__(5113)
-const neq = __nccwpck_require__(26487)
-const gt = __nccwpck_require__(35012)
-const gte = __nccwpck_require__(67745)
-const lt = __nccwpck_require__(63691)
-const lte = __nccwpck_require__(27672)
-
-const cmp = (a, op, b, loose) => {
-  switch (op) {
-    case '===':
-      if (typeof a === 'object') {
-        a = a.version
-      }
-      if (typeof b === 'object') {
-        b = b.version
-      }
-      return a === b
-
-    case '!==':
-      if (typeof a === 'object') {
-        a = a.version
-      }
-      if (typeof b === 'object') {
-        b = b.version
-      }
-      return a !== b
-
-    case '':
-    case '=':
-    case '==':
-      return eq(a, b, loose)
-
-    case '!=':
-      return neq(a, b, loose)
-
-    case '>':
-      return gt(a, b, loose)
-
-    case '>=':
-      return gte(a, b, loose)
-
-    case '<':
-      return lt(a, b, loose)
+/***/ 84935:
+/***/ ((module) => {
 
-    case '<=':
-      return lte(a, b, loose)
+"use strict";
 
-    default:
-      throw new TypeError(`Invalid operator: ${op}`)
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
   }
-}
-module.exports = cmp
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
 
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  legacyRestEndpointMethods: () => legacyRestEndpointMethods,
+  restEndpointMethods: () => restEndpointMethods
+});
+module.exports = __toCommonJS(dist_src_exports);
 
-/***/ }),
-
-/***/ 3346:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const parse = __nccwpck_require__(45240)
-const { safeRe: re, t } = __nccwpck_require__(84894)
-
-const coerce = (version, options) => {
-  if (version instanceof SemVer) {
-    return version
-  }
-
-  if (typeof version === 'number') {
-    version = String(version)
-  }
-
-  if (typeof version !== 'string') {
-    return null
-  }
-
-  options = options || {}
-
-  let match = null
-  if (!options.rtl) {
-    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
-  } else {
-    // Find the right-most coercible string that does not share
-    // a terminus with a more left-ward coercible string.
-    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
-    // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
-    //
-    // Walk through the string checking with a /g regexp
-    // Manually set the index so as to pick up overlapping matches.
-    // Stop when we get a match that ends at the string end, since no
-    // coercible string can be more right-ward without the same terminus.
-    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
-    let next
-    while ((next = coerceRtlRegex.exec(version)) &&
-        (!match || match.index + match[0].length !== version.length)
-    ) {
-      if (!match ||
-            next.index + next[0].length !== match.index + match[0].length) {
-        match = next
-      }
-      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
-    }
-    // leave it in a clean state
-    coerceRtlRegex.lastIndex = -1
-  }
-
-  if (match === null) {
-    return null
-  }
-
-  const major = match[2]
-  const minor = match[3] || '0'
-  const patch = match[4] || '0'
-  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
-  const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
-
-  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
-}
-module.exports = coerce
-
-
-/***/ }),
-
-/***/ 69685:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const compareBuild = (a, b, loose) => {
-  const versionA = new SemVer(a, loose)
-  const versionB = new SemVer(b, loose)
-  return versionA.compare(versionB) || versionA.compareBuild(versionB)
-}
-module.exports = compareBuild
-
-
-/***/ }),
-
-/***/ 90731:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const compareLoose = (a, b) => compare(a, b, true)
-module.exports = compareLoose
-
-
-/***/ }),
-
-/***/ 77304:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const compare = (a, b, loose) =>
-  new SemVer(a, loose).compare(new SemVer(b, loose))
-
-module.exports = compare
-
-
-/***/ }),
-
-/***/ 84048:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const parse = __nccwpck_require__(45240)
-
-const diff = (version1, version2) => {
-  const v1 = parse(version1, null, true)
-  const v2 = parse(version2, null, true)
-  const comparison = v1.compare(v2)
-
-  if (comparison === 0) {
-    return null
-  }
-
-  const v1Higher = comparison > 0
-  const highVersion = v1Higher ? v1 : v2
-  const lowVersion = v1Higher ? v2 : v1
-  const highHasPre = !!highVersion.prerelease.length
-  const lowHasPre = !!lowVersion.prerelease.length
-
-  if (lowHasPre && !highHasPre) {
-    // Going from prerelease -> no prerelease requires some special casing
-
-    // If the low version has only a major, then it will always be a major
-    // Some examples:
-    // 1.0.0-1 -> 1.0.0
-    // 1.0.0-1 -> 1.1.1
-    // 1.0.0-1 -> 2.0.0
-    if (!lowVersion.patch && !lowVersion.minor) {
-      return 'major'
-    }
-
-    // If the main part has no difference
-    if (lowVersion.compareMain(highVersion) === 0) {
-      if (lowVersion.minor && !lowVersion.patch) {
-        return 'minor'
-      }
-      return 'patch'
-    }
-  }
-
-  // add the `pre` prefix if we are going to a prerelease version
-  const prefix = highHasPre ? 'pre' : ''
-
-  if (v1.major !== v2.major) {
-    return prefix + 'major'
-  }
-
-  if (v1.minor !== v2.minor) {
-    return prefix + 'minor'
-  }
-
-  if (v1.patch !== v2.patch) {
-    return prefix + 'patch'
-  }
-
-  // high and low are preleases
-  return 'prerelease'
-}
-
-module.exports = diff
-
-
-/***/ }),
-
-/***/ 5113:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const eq = (a, b, loose) => compare(a, b, loose) === 0
-module.exports = eq
-
-
-/***/ }),
-
-/***/ 35012:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const gt = (a, b, loose) => compare(a, b, loose) > 0
-module.exports = gt
-
-
-/***/ }),
-
-/***/ 67745:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const gte = (a, b, loose) => compare(a, b, loose) >= 0
-module.exports = gte
-
-
-/***/ }),
-
-/***/ 55303:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-
-const inc = (version, release, options, identifier, identifierBase) => {
-  if (typeof (options) === 'string') {
-    identifierBase = identifier
-    identifier = options
-    options = undefined
-  }
-
-  try {
-    return new SemVer(
-      version instanceof SemVer ? version.version : version,
-      options
-    ).inc(release, identifier, identifierBase).version
-  } catch (er) {
-    return null
-  }
-}
-module.exports = inc
-
-
-/***/ }),
-
-/***/ 63691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const lt = (a, b, loose) => compare(a, b, loose) < 0
-module.exports = lt
-
-
-/***/ }),
-
-/***/ 27672:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const lte = (a, b, loose) => compare(a, b, loose) <= 0
-module.exports = lte
-
-
-/***/ }),
-
-/***/ 18610:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const major = (a, loose) => new SemVer(a, loose).major
-module.exports = major
-
-
-/***/ }),
-
-/***/ 8550:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const minor = (a, loose) => new SemVer(a, loose).minor
-module.exports = minor
-
-
-/***/ }),
-
-/***/ 26487:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const neq = (a, b, loose) => compare(a, b, loose) !== 0
-module.exports = neq
-
-
-/***/ }),
-
-/***/ 45240:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const parse = (version, options, throwErrors = false) => {
-  if (version instanceof SemVer) {
-    return version
-  }
-  try {
-    return new SemVer(version, options)
-  } catch (er) {
-    if (!throwErrors) {
-      return null
-    }
-    throw er
-  }
-}
-
-module.exports = parse
-
-
-/***/ }),
-
-/***/ 43413:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const patch = (a, loose) => new SemVer(a, loose).patch
-module.exports = patch
-
-
-/***/ }),
-
-/***/ 94729:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const parse = __nccwpck_require__(45240)
-const prerelease = (version, options) => {
-  const parsed = parse(version, options)
-  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
-}
-module.exports = prerelease
-
-
-/***/ }),
-
-/***/ 42810:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compare = __nccwpck_require__(77304)
-const rcompare = (a, b, loose) => compare(b, a, loose)
-module.exports = rcompare
-
-
-/***/ }),
-
-/***/ 91981:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compareBuild = __nccwpck_require__(69685)
-const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
-module.exports = rsort
-
-
-/***/ }),
-
-/***/ 10174:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const Range = __nccwpck_require__(60031)
-const satisfies = (version, range, options) => {
-  try {
-    range = new Range(range, options)
-  } catch (er) {
-    return false
-  }
-  return range.test(version)
-}
-module.exports = satisfies
-
-
-/***/ }),
-
-/***/ 43151:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const compareBuild = __nccwpck_require__(69685)
-const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
-module.exports = sort
-
-
-/***/ }),
-
-/***/ 37105:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const parse = __nccwpck_require__(45240)
-const valid = (version, options) => {
-  const v = parse(version, options)
-  return v ? v.version : null
-}
-module.exports = valid
-
-
-/***/ }),
-
-/***/ 41437:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// just pre-load all the stuff that index.js lazily exports
-const internalRe = __nccwpck_require__(84894)
-const constants = __nccwpck_require__(83074)
-const SemVer = __nccwpck_require__(95548)
-const identifiers = __nccwpck_require__(98219)
-const parse = __nccwpck_require__(45240)
-const valid = __nccwpck_require__(37105)
-const clean = __nccwpck_require__(64510)
-const inc = __nccwpck_require__(55303)
-const diff = __nccwpck_require__(84048)
-const major = __nccwpck_require__(18610)
-const minor = __nccwpck_require__(8550)
-const patch = __nccwpck_require__(43413)
-const prerelease = __nccwpck_require__(94729)
-const compare = __nccwpck_require__(77304)
-const rcompare = __nccwpck_require__(42810)
-const compareLoose = __nccwpck_require__(90731)
-const compareBuild = __nccwpck_require__(69685)
-const sort = __nccwpck_require__(43151)
-const rsort = __nccwpck_require__(91981)
-const gt = __nccwpck_require__(35012)
-const lt = __nccwpck_require__(63691)
-const eq = __nccwpck_require__(5113)
-const neq = __nccwpck_require__(26487)
-const gte = __nccwpck_require__(67745)
-const lte = __nccwpck_require__(27672)
-const cmp = __nccwpck_require__(23991)
-const coerce = __nccwpck_require__(3346)
-const Comparator = __nccwpck_require__(39768)
-const Range = __nccwpck_require__(60031)
-const satisfies = __nccwpck_require__(10174)
-const toComparators = __nccwpck_require__(9495)
-const maxSatisfying = __nccwpck_require__(9412)
-const minSatisfying = __nccwpck_require__(51670)
-const minVersion = __nccwpck_require__(52981)
-const validRange = __nccwpck_require__(61610)
-const outside = __nccwpck_require__(23915)
-const gtr = __nccwpck_require__(19691)
-const ltr = __nccwpck_require__(38598)
-const intersects = __nccwpck_require__(75956)
-const simplifyRange = __nccwpck_require__(82757)
-const subset = __nccwpck_require__(64)
-module.exports = {
-  parse,
-  valid,
-  clean,
-  inc,
-  diff,
-  major,
-  minor,
-  patch,
-  prerelease,
-  compare,
-  rcompare,
-  compareLoose,
-  compareBuild,
-  sort,
-  rsort,
-  gt,
-  lt,
-  eq,
-  neq,
-  gte,
-  lte,
-  cmp,
-  coerce,
-  Comparator,
-  Range,
-  satisfies,
-  toComparators,
-  maxSatisfying,
-  minSatisfying,
-  minVersion,
-  validRange,
-  outside,
-  gtr,
-  ltr,
-  intersects,
-  simplifyRange,
-  subset,
-  SemVer,
-  re: internalRe.re,
-  src: internalRe.src,
-  tokens: internalRe.t,
-  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
-  RELEASE_TYPES: constants.RELEASE_TYPES,
-  compareIdentifiers: identifiers.compareIdentifiers,
-  rcompareIdentifiers: identifiers.rcompareIdentifiers,
-}
-
-
-/***/ }),
-
-/***/ 83074:
-/***/ ((module) => {
-
-// Note: this is the semver.org version of the spec that it implements
-// Not necessarily the package version of this code.
-const SEMVER_SPEC_VERSION = '2.0.0'
-
-const MAX_LENGTH = 256
-const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
-/* istanbul ignore next */ 9007199254740991
-
-// Max safe segment length for coercion.
-const MAX_SAFE_COMPONENT_LENGTH = 16
-
-// Max safe length for a build identifier. The max length minus 6 characters for
-// the shortest version with a build 0.0.0+BUILD.
-const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
-
-const RELEASE_TYPES = [
-  'major',
-  'premajor',
-  'minor',
-  'preminor',
-  'patch',
-  'prepatch',
-  'prerelease',
-]
-
-module.exports = {
-  MAX_LENGTH,
-  MAX_SAFE_COMPONENT_LENGTH,
-  MAX_SAFE_BUILD_LENGTH,
-  MAX_SAFE_INTEGER,
-  RELEASE_TYPES,
-  SEMVER_SPEC_VERSION,
-  FLAG_INCLUDE_PRERELEASE: 0b001,
-  FLAG_LOOSE: 0b010,
-}
-
-
-/***/ }),
-
-/***/ 86912:
-/***/ ((module) => {
-
-const debug = (
-  typeof process === 'object' &&
-  process.env &&
-  process.env.NODE_DEBUG &&
-  /\bsemver\b/i.test(process.env.NODE_DEBUG)
-) ? (...args) => console.error('SEMVER', ...args)
-  : () => {}
-
-module.exports = debug
-
-
-/***/ }),
-
-/***/ 98219:
-/***/ ((module) => {
-
-const numeric = /^[0-9]+$/
-const compareIdentifiers = (a, b) => {
-  const anum = numeric.test(a)
-  const bnum = numeric.test(b)
-
-  if (anum && bnum) {
-    a = +a
-    b = +b
-  }
-
-  return a === b ? 0
-    : (anum && !bnum) ? -1
-    : (bnum && !anum) ? 1
-    : a < b ? -1
-    : 1
-}
-
-const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
-
-module.exports = {
-  compareIdentifiers,
-  rcompareIdentifiers,
-}
-
-
-/***/ }),
-
-/***/ 35986:
-/***/ ((module) => {
-
-class LRUCache {
-  constructor () {
-    this.max = 1000
-    this.map = new Map()
-  }
-
-  get (key) {
-    const value = this.map.get(key)
-    if (value === undefined) {
-      return undefined
-    } else {
-      // Remove the key from the map and add it to the end
-      this.map.delete(key)
-      this.map.set(key, value)
-      return value
-    }
-  }
-
-  delete (key) {
-    return this.map.delete(key)
-  }
-
-  set (key, value) {
-    const deleted = this.delete(key)
-
-    if (!deleted && value !== undefined) {
-      // If cache is full, delete the least recently used item
-      if (this.map.size >= this.max) {
-        const firstKey = this.map.keys().next().value
-        this.delete(firstKey)
-      }
-
-      this.map.set(key, value)
-    }
-
-    return this
-  }
-}
-
-module.exports = LRUCache
-
-
-/***/ }),
-
-/***/ 65939:
-/***/ ((module) => {
-
-// parse out just the options we care about
-const looseOption = Object.freeze({ loose: true })
-const emptyOpts = Object.freeze({ })
-const parseOptions = options => {
-  if (!options) {
-    return emptyOpts
-  }
-
-  if (typeof options !== 'object') {
-    return looseOption
-  }
-
-  return options
-}
-module.exports = parseOptions
-
-
-/***/ }),
-
-/***/ 84894:
-/***/ ((module, exports, __nccwpck_require__) => {
-
-const {
-  MAX_SAFE_COMPONENT_LENGTH,
-  MAX_SAFE_BUILD_LENGTH,
-  MAX_LENGTH,
-} = __nccwpck_require__(83074)
-const debug = __nccwpck_require__(86912)
-exports = module.exports = {}
-
-// The actual regexps go on exports.re
-const re = exports.re = []
-const safeRe = exports.safeRe = []
-const src = exports.src = []
-const safeSrc = exports.safeSrc = []
-const t = exports.t = {}
-let R = 0
-
-const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
-
-// Replace some greedy regex tokens to prevent regex dos issues. These regex are
-// used internally via the safeRe object since all inputs in this library get
-// normalized first to trim and collapse all extra whitespace. The original
-// regexes are exported for userland consumption and lower level usage. A
-// future breaking change could export the safer regex only with a note that
-// all input should have extra whitespace removed.
-const safeRegexReplacements = [
-  ['\\s', 1],
-  ['\\d', MAX_LENGTH],
-  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
-]
-
-const makeSafeRegex = (value) => {
-  for (const [token, max] of safeRegexReplacements) {
-    value = value
-      .split(`${token}*`).join(`${token}{0,${max}}`)
-      .split(`${token}+`).join(`${token}{1,${max}}`)
-  }
-  return value
-}
-
-const createToken = (name, value, isGlobal) => {
-  const safe = makeSafeRegex(value)
-  const index = R++
-  debug(name, index, value)
-  t[name] = index
-  src[index] = value
-  safeSrc[index] = safe
-  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
-  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
-}
-
-// The following Regular Expressions can be used for tokenizing,
-// validating, and parsing SemVer version strings.
-
-// ## Numeric Identifier
-// A single `0`, or a non-zero digit followed by zero or more digits.
-
-createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
-createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
-
-// ## Non-numeric Identifier
-// Zero or more digits, followed by a letter or hyphen, and then zero or
-// more letters, digits, or hyphens.
-
-createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
-
-// ## Main Version
-// Three dot-separated numeric identifiers.
-
-createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
-                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
-                   `(${src[t.NUMERICIDENTIFIER]})`)
-
-createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
-                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
-                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
-
-// ## Pre-release Version Identifier
-// A numeric identifier, or a non-numeric identifier.
-
-createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
-}|${src[t.NONNUMERICIDENTIFIER]})`)
-
-createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
-}|${src[t.NONNUMERICIDENTIFIER]})`)
-
-// ## Pre-release Version
-// Hyphen, followed by one or more dot-separated pre-release version
-// identifiers.
-
-createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
-}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
-
-createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
-}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
-
-// ## Build Metadata Identifier
-// Any combination of digits, letters, or hyphens.
-
-createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
-
-// ## Build Metadata
-// Plus sign, followed by one or more period-separated build metadata
-// identifiers.
-
-createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
-}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
-
-// ## Full Version String
-// A main version, followed optionally by a pre-release version and
-// build metadata.
-
-// Note that the only major, minor, patch, and pre-release sections of
-// the version string are capturing groups.  The build metadata is not a
-// capturing group, because it should not ever be used in version
-// comparison.
-
-createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
-}${src[t.PRERELEASE]}?${
-  src[t.BUILD]}?`)
-
-createToken('FULL', `^${src[t.FULLPLAIN]}$`)
-
-// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
-// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
-// common in the npm registry.
-createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
-}${src[t.PRERELEASELOOSE]}?${
-  src[t.BUILD]}?`)
-
-createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
-
-createToken('GTLT', '((?:<|>)?=?)')
-
-// Something like "2.*" or "1.2.x".
-// Note that "x.x" is a valid xRange identifer, meaning "any version"
-// Only the first item is strictly required.
-createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
-createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
-
-createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
-                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
-                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
-                   `(?:${src[t.PRERELEASE]})?${
-                     src[t.BUILD]}?` +
-                   `)?)?`)
-
-createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
-                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
-                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
-                        `(?:${src[t.PRERELEASELOOSE]})?${
-                          src[t.BUILD]}?` +
-                        `)?)?`)
-
-createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
-createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
-
-// Coercion.
-// Extract anything that could conceivably be a part of a valid semver
-createToken('COERCEPLAIN', `${'(^|[^\\d])' +
-              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
-              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
-              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
-createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
-createToken('COERCEFULL', src[t.COERCEPLAIN] +
-              `(?:${src[t.PRERELEASE]})?` +
-              `(?:${src[t.BUILD]})?` +
-              `(?:$|[^\\d])`)
-createToken('COERCERTL', src[t.COERCE], true)
-createToken('COERCERTLFULL', src[t.COERCEFULL], true)
-
-// Tilde ranges.
-// Meaning is "reasonably at or greater than"
-createToken('LONETILDE', '(?:~>?)')
-
-createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
-exports.tildeTrimReplace = '$1~'
-
-createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
-createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
-
-// Caret ranges.
-// Meaning is "at least and backwards compatible with"
-createToken('LONECARET', '(?:\\^)')
-
-createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
-exports.caretTrimReplace = '$1^'
-
-createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
-createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
-
-// A simple gt/lt/eq thing, or just "" to indicate "any version"
-createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
-createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
-
-// An expression to strip any whitespace between the gtlt and the thing
-// it modifies, so that `> 1.2.3` ==> `>1.2.3`
-createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
-}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
-exports.comparatorTrimReplace = '$1$2$3'
-
-// Something like `1.2.3 - 1.2.4`
-// Note that these all use the loose form, because they'll be
-// checked against either the strict or loose comparator form
-// later.
-createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
-                   `\\s+-\\s+` +
-                   `(${src[t.XRANGEPLAIN]})` +
-                   `\\s*$`)
-
-createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
-                        `\\s+-\\s+` +
-                        `(${src[t.XRANGEPLAINLOOSE]})` +
-                        `\\s*$`)
-
-// Star ranges basically just allow anything at all.
-createToken('STAR', '(<|>)?=?\\s*\\*')
-// >=0.0.0 is like a star
-createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
-createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
-
-
-/***/ }),
-
-/***/ 19691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// Determine if version is greater than all the versions possible in the range.
-const outside = __nccwpck_require__(23915)
-const gtr = (version, range, options) => outside(version, range, '>', options)
-module.exports = gtr
-
-
-/***/ }),
-
-/***/ 75956:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const Range = __nccwpck_require__(60031)
-const intersects = (r1, r2, options) => {
-  r1 = new Range(r1, options)
-  r2 = new Range(r2, options)
-  return r1.intersects(r2, options)
-}
-module.exports = intersects
-
-
-/***/ }),
-
-/***/ 38598:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const outside = __nccwpck_require__(23915)
-// Determine if version is less than all the versions possible in the range
-const ltr = (version, range, options) => outside(version, range, '<', options)
-module.exports = ltr
-
-
-/***/ }),
-
-/***/ 9412:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const Range = __nccwpck_require__(60031)
-
-const maxSatisfying = (versions, range, options) => {
-  let max = null
-  let maxSV = null
-  let rangeObj = null
-  try {
-    rangeObj = new Range(range, options)
-  } catch (er) {
-    return null
-  }
-  versions.forEach((v) => {
-    if (rangeObj.test(v)) {
-      // satisfies(v, range, options)
-      if (!max || maxSV.compare(v) === -1) {
-        // compare(max, v, true)
-        max = v
-        maxSV = new SemVer(max, options)
-      }
-    }
-  })
-  return max
-}
-module.exports = maxSatisfying
-
-
-/***/ }),
-
-/***/ 51670:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const Range = __nccwpck_require__(60031)
-const minSatisfying = (versions, range, options) => {
-  let min = null
-  let minSV = null
-  let rangeObj = null
-  try {
-    rangeObj = new Range(range, options)
-  } catch (er) {
-    return null
-  }
-  versions.forEach((v) => {
-    if (rangeObj.test(v)) {
-      // satisfies(v, range, options)
-      if (!min || minSV.compare(v) === 1) {
-        // compare(min, v, true)
-        min = v
-        minSV = new SemVer(min, options)
-      }
-    }
-  })
-  return min
-}
-module.exports = minSatisfying
-
-
-/***/ }),
-
-/***/ 52981:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const Range = __nccwpck_require__(60031)
-const gt = __nccwpck_require__(35012)
-
-const minVersion = (range, loose) => {
-  range = new Range(range, loose)
-
-  let minver = new SemVer('0.0.0')
-  if (range.test(minver)) {
-    return minver
-  }
-
-  minver = new SemVer('0.0.0-0')
-  if (range.test(minver)) {
-    return minver
-  }
-
-  minver = null
-  for (let i = 0; i < range.set.length; ++i) {
-    const comparators = range.set[i]
-
-    let setMin = null
-    comparators.forEach((comparator) => {
-      // Clone to avoid manipulating the comparator's semver object.
-      const compver = new SemVer(comparator.semver.version)
-      switch (comparator.operator) {
-        case '>':
-          if (compver.prerelease.length === 0) {
-            compver.patch++
-          } else {
-            compver.prerelease.push(0)
-          }
-          compver.raw = compver.format()
-          /* fallthrough */
-        case '':
-        case '>=':
-          if (!setMin || gt(compver, setMin)) {
-            setMin = compver
-          }
-          break
-        case '<':
-        case '<=':
-          /* Ignore maximum versions */
-          break
-        /* istanbul ignore next */
-        default:
-          throw new Error(`Unexpected operation: ${comparator.operator}`)
-      }
-    })
-    if (setMin && (!minver || gt(minver, setMin))) {
-      minver = setMin
-    }
-  }
-
-  if (minver && range.test(minver)) {
-    return minver
-  }
-
-  return null
-}
-module.exports = minVersion
-
-
-/***/ }),
-
-/***/ 23915:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const SemVer = __nccwpck_require__(95548)
-const Comparator = __nccwpck_require__(39768)
-const { ANY } = Comparator
-const Range = __nccwpck_require__(60031)
-const satisfies = __nccwpck_require__(10174)
-const gt = __nccwpck_require__(35012)
-const lt = __nccwpck_require__(63691)
-const lte = __nccwpck_require__(27672)
-const gte = __nccwpck_require__(67745)
-
-const outside = (version, range, hilo, options) => {
-  version = new SemVer(version, options)
-  range = new Range(range, options)
-
-  let gtfn, ltefn, ltfn, comp, ecomp
-  switch (hilo) {
-    case '>':
-      gtfn = gt
-      ltefn = lte
-      ltfn = lt
-      comp = '>'
-      ecomp = '>='
-      break
-    case '<':
-      gtfn = lt
-      ltefn = gte
-      ltfn = gt
-      comp = '<'
-      ecomp = '<='
-      break
-    default:
-      throw new TypeError('Must provide a hilo val of "<" or ">"')
-  }
-
-  // If it satisfies the range it is not outside
-  if (satisfies(version, range, options)) {
-    return false
-  }
-
-  // From now on, variable terms are as if we're in "gtr" mode.
-  // but note that everything is flipped for the "ltr" function.
-
-  for (let i = 0; i < range.set.length; ++i) {
-    const comparators = range.set[i]
-
-    let high = null
-    let low = null
-
-    comparators.forEach((comparator) => {
-      if (comparator.semver === ANY) {
-        comparator = new Comparator('>=0.0.0')
-      }
-      high = high || comparator
-      low = low || comparator
-      if (gtfn(comparator.semver, high.semver, options)) {
-        high = comparator
-      } else if (ltfn(comparator.semver, low.semver, options)) {
-        low = comparator
-      }
-    })
-
-    // If the edge version comparator has a operator then our version
-    // isn't outside it
-    if (high.operator === comp || high.operator === ecomp) {
-      return false
-    }
-
-    // If the lowest version comparator has an operator and our version
-    // is less than it then it isn't higher than the range
-    if ((!low.operator || low.operator === comp) &&
-        ltefn(version, low.semver)) {
-      return false
-    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
-      return false
-    }
-  }
-  return true
-}
-
-module.exports = outside
-
-
-/***/ }),
-
-/***/ 82757:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// given a set of versions and a range, create a "simplified" range
-// that includes the same versions that the original range does
-// If the original range is shorter than the simplified one, return that.
-const satisfies = __nccwpck_require__(10174)
-const compare = __nccwpck_require__(77304)
-module.exports = (versions, range, options) => {
-  const set = []
-  let first = null
-  let prev = null
-  const v = versions.sort((a, b) => compare(a, b, options))
-  for (const version of v) {
-    const included = satisfies(version, range, options)
-    if (included) {
-      prev = version
-      if (!first) {
-        first = version
-      }
-    } else {
-      if (prev) {
-        set.push([first, prev])
-      }
-      prev = null
-      first = null
-    }
-  }
-  if (first) {
-    set.push([first, null])
-  }
-
-  const ranges = []
-  for (const [min, max] of set) {
-    if (min === max) {
-      ranges.push(min)
-    } else if (!max && min === v[0]) {
-      ranges.push('*')
-    } else if (!max) {
-      ranges.push(`>=${min}`)
-    } else if (min === v[0]) {
-      ranges.push(`<=${max}`)
-    } else {
-      ranges.push(`${min} - ${max}`)
-    }
-  }
-  const simplified = ranges.join(' || ')
-  const original = typeof range.raw === 'string' ? range.raw : String(range)
-  return simplified.length < original.length ? simplified : range
-}
-
-
-/***/ }),
-
-/***/ 64:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const Range = __nccwpck_require__(60031)
-const Comparator = __nccwpck_require__(39768)
-const { ANY } = Comparator
-const satisfies = __nccwpck_require__(10174)
-const compare = __nccwpck_require__(77304)
-
-// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
-// - Every simple range `r1, r2, ...` is a null set, OR
-// - Every simple range `r1, r2, ...` which is not a null set is a subset of
-//   some `R1, R2, ...`
-//
-// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
-// - If c is only the ANY comparator
-//   - If C is only the ANY comparator, return true
-//   - Else if in prerelease mode, return false
-//   - else replace c with `[>=0.0.0]`
-// - If C is only the ANY comparator
-//   - if in prerelease mode, return true
-//   - else replace C with `[>=0.0.0]`
-// - Let EQ be the set of = comparators in c
-// - If EQ is more than one, return true (null set)
-// - Let GT be the highest > or >= comparator in c
-// - Let LT be the lowest < or <= comparator in c
-// - If GT and LT, and GT.semver > LT.semver, return true (null set)
-// - If any C is a = range, and GT or LT are set, return false
-// - If EQ
-//   - If GT, and EQ does not satisfy GT, return true (null set)
-//   - If LT, and EQ does not satisfy LT, return true (null set)
-//   - If EQ satisfies every C, return true
-//   - Else return false
-// - If GT
-//   - If GT.semver is lower than any > or >= comp in C, return false
-//   - If GT is >=, and GT.semver does not satisfy every C, return false
-//   - If GT.semver has a prerelease, and not in prerelease mode
-//     - If no C has a prerelease and the GT.semver tuple, return false
-// - If LT
-//   - If LT.semver is greater than any < or <= comp in C, return false
-//   - If LT is <=, and LT.semver does not satisfy every C, return false
-//   - If GT.semver has a prerelease, and not in prerelease mode
-//     - If no C has a prerelease and the LT.semver tuple, return false
-// - Else return true
-
-const subset = (sub, dom, options = {}) => {
-  if (sub === dom) {
-    return true
-  }
-
-  sub = new Range(sub, options)
-  dom = new Range(dom, options)
-  let sawNonNull = false
-
-  OUTER: for (const simpleSub of sub.set) {
-    for (const simpleDom of dom.set) {
-      const isSub = simpleSubset(simpleSub, simpleDom, options)
-      sawNonNull = sawNonNull || isSub !== null
-      if (isSub) {
-        continue OUTER
-      }
-    }
-    // the null set is a subset of everything, but null simple ranges in
-    // a complex range should be ignored.  so if we saw a non-null range,
-    // then we know this isn't a subset, but if EVERY simple range was null,
-    // then it is a subset.
-    if (sawNonNull) {
-      return false
-    }
-  }
-  return true
-}
-
-const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
-const minimumVersion = [new Comparator('>=0.0.0')]
-
-const simpleSubset = (sub, dom, options) => {
-  if (sub === dom) {
-    return true
-  }
-
-  if (sub.length === 1 && sub[0].semver === ANY) {
-    if (dom.length === 1 && dom[0].semver === ANY) {
-      return true
-    } else if (options.includePrerelease) {
-      sub = minimumVersionWithPreRelease
-    } else {
-      sub = minimumVersion
-    }
-  }
-
-  if (dom.length === 1 && dom[0].semver === ANY) {
-    if (options.includePrerelease) {
-      return true
-    } else {
-      dom = minimumVersion
-    }
-  }
-
-  const eqSet = new Set()
-  let gt, lt
-  for (const c of sub) {
-    if (c.operator === '>' || c.operator === '>=') {
-      gt = higherGT(gt, c, options)
-    } else if (c.operator === '<' || c.operator === '<=') {
-      lt = lowerLT(lt, c, options)
-    } else {
-      eqSet.add(c.semver)
-    }
-  }
-
-  if (eqSet.size > 1) {
-    return null
-  }
-
-  let gtltComp
-  if (gt && lt) {
-    gtltComp = compare(gt.semver, lt.semver, options)
-    if (gtltComp > 0) {
-      return null
-    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
-      return null
-    }
-  }
-
-  // will iterate one or zero times
-  for (const eq of eqSet) {
-    if (gt && !satisfies(eq, String(gt), options)) {
-      return null
-    }
-
-    if (lt && !satisfies(eq, String(lt), options)) {
-      return null
-    }
-
-    for (const c of dom) {
-      if (!satisfies(eq, String(c), options)) {
-        return false
-      }
-    }
-
-    return true
-  }
-
-  let higher, lower
-  let hasDomLT, hasDomGT
-  // if the subset has a prerelease, we need a comparator in the superset
-  // with the same tuple and a prerelease, or it's not a subset
-  let needDomLTPre = lt &&
-    !options.includePrerelease &&
-    lt.semver.prerelease.length ? lt.semver : false
-  let needDomGTPre = gt &&
-    !options.includePrerelease &&
-    gt.semver.prerelease.length ? gt.semver : false
-  // exception: <1.2.3-0 is the same as <1.2.3
-  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
-      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
-    needDomLTPre = false
-  }
-
-  for (const c of dom) {
-    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
-    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
-    if (gt) {
-      if (needDomGTPre) {
-        if (c.semver.prerelease && c.semver.prerelease.length &&
-            c.semver.major === needDomGTPre.major &&
-            c.semver.minor === needDomGTPre.minor &&
-            c.semver.patch === needDomGTPre.patch) {
-          needDomGTPre = false
-        }
-      }
-      if (c.operator === '>' || c.operator === '>=') {
-        higher = higherGT(gt, c, options)
-        if (higher === c && higher !== gt) {
-          return false
-        }
-      } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
-        return false
-      }
-    }
-    if (lt) {
-      if (needDomLTPre) {
-        if (c.semver.prerelease && c.semver.prerelease.length &&
-            c.semver.major === needDomLTPre.major &&
-            c.semver.minor === needDomLTPre.minor &&
-            c.semver.patch === needDomLTPre.patch) {
-          needDomLTPre = false
-        }
-      }
-      if (c.operator === '<' || c.operator === '<=') {
-        lower = lowerLT(lt, c, options)
-        if (lower === c && lower !== lt) {
-          return false
-        }
-      } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
-        return false
-      }
-    }
-    if (!c.operator && (lt || gt) && gtltComp !== 0) {
-      return false
-    }
-  }
-
-  // if there was a < or >, and nothing in the dom, then must be false
-  // UNLESS it was limited by another range in the other direction.
-  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
-  if (gt && hasDomLT && !lt && gtltComp !== 0) {
-    return false
-  }
-
-  if (lt && hasDomGT && !gt && gtltComp !== 0) {
-    return false
-  }
-
-  // we needed a prerelease range in a specific tuple, but didn't get one
-  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,
-  // because it includes prereleases in the 1.2.3 tuple
-  if (needDomGTPre || needDomLTPre) {
-    return false
-  }
-
-  return true
-}
-
-// >=1.2.3 is lower than >1.2.3
-const higherGT = (a, b, options) => {
-  if (!a) {
-    return b
-  }
-  const comp = compare(a.semver, b.semver, options)
-  return comp > 0 ? a
-    : comp < 0 ? b
-    : b.operator === '>' && a.operator === '>=' ? b
-    : a
-}
-
-// <=1.2.3 is higher than <1.2.3
-const lowerLT = (a, b, options) => {
-  if (!a) {
-    return b
-  }
-  const comp = compare(a.semver, b.semver, options)
-  return comp < 0 ? a
-    : comp > 0 ? b
-    : b.operator === '<' && a.operator === '<=' ? b
-    : a
-}
-
-module.exports = subset
-
-
-/***/ }),
-
-/***/ 9495:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const Range = __nccwpck_require__(60031)
-
-// Mostly just for testing and legacy API reasons
-const toComparators = (range, options) =>
-  new Range(range, options).set
-    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
-
-module.exports = toComparators
-
-
-/***/ }),
-
-/***/ 61610:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const Range = __nccwpck_require__(60031)
-const validRange = (range, options) => {
-  try {
-    // Return '*' instead of '' so that truthiness works.
-    // This will throw if it's invalid anyway
-    return new Range(range, options).range || '*'
-  } catch (er) {
-    return null
-  }
-}
-module.exports = validRange
-
-
-/***/ }),
-
-/***/ 77864:
-/***/ ((module) => {
-
-"use strict";
-
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  createTokenAuth: () => createTokenAuth
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/auth.js
-var REGEX_IS_INSTALLATION_LEGACY = /^v1\./;
-var REGEX_IS_INSTALLATION = /^ghs_/;
-var REGEX_IS_USER_TO_SERVER = /^ghu_/;
-async function auth(token) {
-  const isApp = token.split(/\./).length === 3;
-  const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token);
-  const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token);
-  const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth";
-  return {
-    type: "token",
-    token,
-    tokenType
-  };
-}
-
-// pkg/dist-src/with-authorization-prefix.js
-function withAuthorizationPrefix(token) {
-  if (token.split(/\./).length === 3) {
-    return `bearer ${token}`;
-  }
-  return `token ${token}`;
-}
-
-// pkg/dist-src/hook.js
-async function hook(token, request, route, parameters) {
-  const endpoint = request.endpoint.merge(
-    route,
-    parameters
-  );
-  endpoint.headers.authorization = withAuthorizationPrefix(token);
-  return request(endpoint);
-}
-
-// pkg/dist-src/index.js
-var createTokenAuth = function createTokenAuth2(token) {
-  if (!token) {
-    throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");
-  }
-  if (typeof token !== "string") {
-    throw new Error(
-      "[@octokit/auth-token] Token passed to createTokenAuth is not a string"
-    );
-  }
-  token = token.replace(/^(token|bearer) +/i, "");
-  return Object.assign(auth.bind(null, token), {
-    hook: hook.bind(null, token)
-  });
-};
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
-
-
-/***/ }),
-
-/***/ 61897:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  Octokit: () => Octokit
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_universal_user_agent = __nccwpck_require__(33843);
-var import_before_after_hook = __nccwpck_require__(52732);
-var import_request = __nccwpck_require__(66255);
-var import_graphql = __nccwpck_require__(70007);
-var import_auth_token = __nccwpck_require__(77864);
-
-// pkg/dist-src/version.js
-var VERSION = "5.1.0";
-
-// pkg/dist-src/index.js
-var noop = () => {
-};
-var consoleWarn = console.warn.bind(console);
-var consoleError = console.error.bind(console);
-var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;
-var Octokit = class {
-  static {
-    this.VERSION = VERSION;
-  }
-  static defaults(defaults) {
-    const OctokitWithDefaults = class extends this {
-      constructor(...args) {
-        const options = args[0] || {};
-        if (typeof defaults === "function") {
-          super(defaults(options));
-          return;
-        }
-        super(
-          Object.assign(
-            {},
-            defaults,
-            options,
-            options.userAgent && defaults.userAgent ? {
-              userAgent: `${options.userAgent} ${defaults.userAgent}`
-            } : null
-          )
-        );
-      }
-    };
-    return OctokitWithDefaults;
-  }
-  static {
-    this.plugins = [];
-  }
-  /**
-   * Attach a plugin (or many) to your Octokit instance.
-   *
-   * @example
-   * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)
-   */
-  static plugin(...newPlugins) {
-    const currentPlugins = this.plugins;
-    const NewOctokit = class extends this {
-      static {
-        this.plugins = currentPlugins.concat(
-          newPlugins.filter((plugin) => !currentPlugins.includes(plugin))
-        );
-      }
-    };
-    return NewOctokit;
-  }
-  constructor(options = {}) {
-    const hook = new import_before_after_hook.Collection();
-    const requestDefaults = {
-      baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl,
-      headers: {},
-      request: Object.assign({}, options.request, {
-        // @ts-ignore internal usage only, no need to type
-        hook: hook.bind(null, "request")
-      }),
-      mediaType: {
-        previews: [],
-        format: ""
-      }
-    };
-    requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;
-    if (options.baseUrl) {
-      requestDefaults.baseUrl = options.baseUrl;
-    }
-    if (options.previews) {
-      requestDefaults.mediaType.previews = options.previews;
-    }
-    if (options.timeZone) {
-      requestDefaults.headers["time-zone"] = options.timeZone;
-    }
-    this.request = import_request.request.defaults(requestDefaults);
-    this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults);
-    this.log = Object.assign(
-      {
-        debug: noop,
-        info: noop,
-        warn: consoleWarn,
-        error: consoleError
-      },
-      options.log
-    );
-    this.hook = hook;
-    if (!options.authStrategy) {
-      if (!options.auth) {
-        this.auth = async () => ({
-          type: "unauthenticated"
-        });
-      } else {
-        const auth = (0, import_auth_token.createTokenAuth)(options.auth);
-        hook.wrap("request", auth.hook);
-        this.auth = auth;
-      }
-    } else {
-      const { authStrategy, ...otherOptions } = options;
-      const auth = authStrategy(
-        Object.assign(
-          {
-            request: this.request,
-            log: this.log,
-            // we pass the current octokit instance as well as its constructor options
-            // to allow for authentication strategies that return a new octokit instance
-            // that shares the same internal state as the current one. The original
-            // requirement for this was the "event-octokit" authentication strategy
-            // of https://github.com/probot/octokit-auth-probot.
-            octokit: this,
-            octokitOptions: otherOptions
-          },
-          options.auth
-        )
-      );
-      hook.wrap("request", auth.hook);
-      this.auth = auth;
-    }
-    const classConstructor = this.constructor;
-    for (let i = 0; i < classConstructor.plugins.length; ++i) {
-      Object.assign(this, classConstructor.plugins[i](this, options));
-    }
-  }
-};
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
-
-
-/***/ }),
-
-/***/ 54471:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  endpoint: () => endpoint
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/defaults.js
-var import_universal_user_agent = __nccwpck_require__(33843);
-
-// pkg/dist-src/version.js
-var VERSION = "9.0.4";
-
-// pkg/dist-src/defaults.js
-var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`;
-var DEFAULTS = {
-  method: "GET",
-  baseUrl: "https://api.github.com",
-  headers: {
-    accept: "application/vnd.github.v3+json",
-    "user-agent": userAgent
-  },
-  mediaType: {
-    format: ""
-  }
-};
-
-// pkg/dist-src/util/lowercase-keys.js
-function lowercaseKeys(object) {
-  if (!object) {
-    return {};
-  }
-  return Object.keys(object).reduce((newObj, key) => {
-    newObj[key.toLowerCase()] = object[key];
-    return newObj;
-  }, {});
-}
-
-// pkg/dist-src/util/is-plain-object.js
-function isPlainObject(value) {
-  if (typeof value !== "object" || value === null)
-    return false;
-  if (Object.prototype.toString.call(value) !== "[object Object]")
-    return false;
-  const proto = Object.getPrototypeOf(value);
-  if (proto === null)
-    return true;
-  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
-  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
-}
-
-// pkg/dist-src/util/merge-deep.js
-function mergeDeep(defaults, options) {
-  const result = Object.assign({}, defaults);
-  Object.keys(options).forEach((key) => {
-    if (isPlainObject(options[key])) {
-      if (!(key in defaults))
-        Object.assign(result, { [key]: options[key] });
-      else
-        result[key] = mergeDeep(defaults[key], options[key]);
-    } else {
-      Object.assign(result, { [key]: options[key] });
-    }
-  });
-  return result;
-}
-
-// pkg/dist-src/util/remove-undefined-properties.js
-function removeUndefinedProperties(obj) {
-  for (const key in obj) {
-    if (obj[key] === void 0) {
-      delete obj[key];
-    }
-  }
-  return obj;
-}
-
-// pkg/dist-src/merge.js
-function merge(defaults, route, options) {
-  if (typeof route === "string") {
-    let [method, url] = route.split(" ");
-    options = Object.assign(url ? { method, url } : { url: method }, options);
-  } else {
-    options = Object.assign({}, route);
-  }
-  options.headers = lowercaseKeys(options.headers);
-  removeUndefinedProperties(options);
-  removeUndefinedProperties(options.headers);
-  const mergedOptions = mergeDeep(defaults || {}, options);
-  if (options.url === "/graphql") {
-    if (defaults && defaults.mediaType.previews?.length) {
-      mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(
-        (preview) => !mergedOptions.mediaType.previews.includes(preview)
-      ).concat(mergedOptions.mediaType.previews);
-    }
-    mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, ""));
-  }
-  return mergedOptions;
-}
-
-// pkg/dist-src/util/add-query-parameters.js
-function addQueryParameters(url, parameters) {
-  const separator = /\?/.test(url) ? "&" : "?";
-  const names = Object.keys(parameters);
-  if (names.length === 0) {
-    return url;
-  }
-  return url + separator + names.map((name) => {
-    if (name === "q") {
-      return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+");
-    }
-    return `${name}=${encodeURIComponent(parameters[name])}`;
-  }).join("&");
-}
-
-// pkg/dist-src/util/extract-url-variable-names.js
-var urlVariableRegex = /\{[^}]+\}/g;
-function removeNonChars(variableName) {
-  return variableName.replace(/^\W+|\W+$/g, "").split(/,/);
-}
-function extractUrlVariableNames(url) {
-  const matches = url.match(urlVariableRegex);
-  if (!matches) {
-    return [];
-  }
-  return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []);
-}
-
-// pkg/dist-src/util/omit.js
-function omit(object, keysToOmit) {
-  const result = { __proto__: null };
-  for (const key of Object.keys(object)) {
-    if (keysToOmit.indexOf(key) === -1) {
-      result[key] = object[key];
-    }
-  }
-  return result;
-}
-
-// pkg/dist-src/util/url-template.js
-function encodeReserved(str) {
-  return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {
-    if (!/%[0-9A-Fa-f]/.test(part)) {
-      part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]");
-    }
-    return part;
-  }).join("");
-}
-function encodeUnreserved(str) {
-  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
-    return "%" + c.charCodeAt(0).toString(16).toUpperCase();
-  });
-}
-function encodeValue(operator, value, key) {
-  value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value);
-  if (key) {
-    return encodeUnreserved(key) + "=" + value;
-  } else {
-    return value;
-  }
-}
-function isDefined(value) {
-  return value !== void 0 && value !== null;
-}
-function isKeyOperator(operator) {
-  return operator === ";" || operator === "&" || operator === "?";
-}
-function getValues(context, operator, key, modifier) {
-  var value = context[key], result = [];
-  if (isDefined(value) && value !== "") {
-    if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
-      value = value.toString();
-      if (modifier && modifier !== "*") {
-        value = value.substring(0, parseInt(modifier, 10));
-      }
-      result.push(
-        encodeValue(operator, value, isKeyOperator(operator) ? key : "")
-      );
-    } else {
-      if (modifier === "*") {
-        if (Array.isArray(value)) {
-          value.filter(isDefined).forEach(function(value2) {
-            result.push(
-              encodeValue(operator, value2, isKeyOperator(operator) ? key : "")
-            );
-          });
-        } else {
-          Object.keys(value).forEach(function(k) {
-            if (isDefined(value[k])) {
-              result.push(encodeValue(operator, value[k], k));
-            }
-          });
-        }
-      } else {
-        const tmp = [];
-        if (Array.isArray(value)) {
-          value.filter(isDefined).forEach(function(value2) {
-            tmp.push(encodeValue(operator, value2));
-          });
-        } else {
-          Object.keys(value).forEach(function(k) {
-            if (isDefined(value[k])) {
-              tmp.push(encodeUnreserved(k));
-              tmp.push(encodeValue(operator, value[k].toString()));
-            }
-          });
-        }
-        if (isKeyOperator(operator)) {
-          result.push(encodeUnreserved(key) + "=" + tmp.join(","));
-        } else if (tmp.length !== 0) {
-          result.push(tmp.join(","));
-        }
-      }
-    }
-  } else {
-    if (operator === ";") {
-      if (isDefined(value)) {
-        result.push(encodeUnreserved(key));
-      }
-    } else if (value === "" && (operator === "&" || operator === "?")) {
-      result.push(encodeUnreserved(key) + "=");
-    } else if (value === "") {
-      result.push("");
-    }
-  }
-  return result;
-}
-function parseUrl(template) {
-  return {
-    expand: expand.bind(null, template)
-  };
-}
-function expand(template, context) {
-  var operators = ["+", "#", ".", "/", ";", "?", "&"];
-  template = template.replace(
-    /\{([^\{\}]+)\}|([^\{\}]+)/g,
-    function(_, expression, literal) {
-      if (expression) {
-        let operator = "";
-        const values = [];
-        if (operators.indexOf(expression.charAt(0)) !== -1) {
-          operator = expression.charAt(0);
-          expression = expression.substr(1);
-        }
-        expression.split(/,/g).forEach(function(variable) {
-          var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
-          values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
-        });
-        if (operator && operator !== "+") {
-          var separator = ",";
-          if (operator === "?") {
-            separator = "&";
-          } else if (operator !== "#") {
-            separator = operator;
-          }
-          return (values.length !== 0 ? operator : "") + values.join(separator);
-        } else {
-          return values.join(",");
-        }
-      } else {
-        return encodeReserved(literal);
-      }
-    }
-  );
-  if (template === "/") {
-    return template;
-  } else {
-    return template.replace(/\/$/, "");
-  }
-}
-
-// pkg/dist-src/parse.js
-function parse(options) {
-  let method = options.method.toUpperCase();
-  let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
-  let headers = Object.assign({}, options.headers);
-  let body;
-  let parameters = omit(options, [
-    "method",
-    "baseUrl",
-    "url",
-    "headers",
-    "request",
-    "mediaType"
-  ]);
-  const urlVariableNames = extractUrlVariableNames(url);
-  url = parseUrl(url).expand(parameters);
-  if (!/^http/.test(url)) {
-    url = options.baseUrl + url;
-  }
-  const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
-  const remainingParameters = omit(parameters, omittedParameters);
-  const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
-  if (!isBinaryRequest) {
-    if (options.mediaType.format) {
-      headers.accept = headers.accept.split(/,/).map(
-        (format) => format.replace(
-          /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
-          `application/vnd$1$2.${options.mediaType.format}`
-        )
-      ).join(",");
-    }
-    if (url.endsWith("/graphql")) {
-      if (options.mediaType.previews?.length) {
-        const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
-        headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
-          const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
-          return `application/vnd.github.${preview}-preview${format}`;
-        }).join(",");
-      }
-    }
-  }
-  if (["GET", "HEAD"].includes(method)) {
-    url = addQueryParameters(url, remainingParameters);
-  } else {
-    if ("data" in remainingParameters) {
-      body = remainingParameters.data;
-    } else {
-      if (Object.keys(remainingParameters).length) {
-        body = remainingParameters;
-      }
-    }
-  }
-  if (!headers["content-type"] && typeof body !== "undefined") {
-    headers["content-type"] = "application/json; charset=utf-8";
-  }
-  if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
-    body = "";
-  }
-  return Object.assign(
-    { method, url, headers },
-    typeof body !== "undefined" ? { body } : null,
-    options.request ? { request: options.request } : null
-  );
-}
-
-// pkg/dist-src/endpoint-with-defaults.js
-function endpointWithDefaults(defaults, route, options) {
-  return parse(merge(defaults, route, options));
-}
-
-// pkg/dist-src/with-defaults.js
-function withDefaults(oldDefaults, newDefaults) {
-  const DEFAULTS2 = merge(oldDefaults, newDefaults);
-  const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);
-  return Object.assign(endpoint2, {
-    DEFAULTS: DEFAULTS2,
-    defaults: withDefaults.bind(null, DEFAULTS2),
-    merge: merge.bind(null, DEFAULTS2),
-    parse
-  });
-}
-
-// pkg/dist-src/index.js
-var endpoint = withDefaults(null, DEFAULTS);
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
-
-
-/***/ }),
-
-/***/ 70007:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  GraphqlResponseError: () => GraphqlResponseError,
-  graphql: () => graphql2,
-  withCustomRequest: () => withCustomRequest
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_request3 = __nccwpck_require__(66255);
-var import_universal_user_agent = __nccwpck_require__(33843);
-
-// pkg/dist-src/version.js
-var VERSION = "7.0.2";
-
-// pkg/dist-src/with-defaults.js
-var import_request2 = __nccwpck_require__(66255);
-
-// pkg/dist-src/graphql.js
-var import_request = __nccwpck_require__(66255);
-
-// pkg/dist-src/error.js
-function _buildMessageForResponseErrors(data) {
-  return `Request failed due to following response errors:
-` + data.errors.map((e) => ` - ${e.message}`).join("\n");
-}
-var GraphqlResponseError = class extends Error {
-  constructor(request2, headers, response) {
-    super(_buildMessageForResponseErrors(response));
-    this.request = request2;
-    this.headers = headers;
-    this.response = response;
-    this.name = "GraphqlResponseError";
-    this.errors = response.errors;
-    this.data = response.data;
-    if (Error.captureStackTrace) {
-      Error.captureStackTrace(this, this.constructor);
-    }
-  }
-};
-
-// pkg/dist-src/graphql.js
-var NON_VARIABLE_OPTIONS = [
-  "method",
-  "baseUrl",
-  "url",
-  "headers",
-  "request",
-  "query",
-  "mediaType"
-];
-var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"];
-var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/;
-function graphql(request2, query, options) {
-  if (options) {
-    if (typeof query === "string" && "query" in options) {
-      return Promise.reject(
-        new Error(`[@octokit/graphql] "query" cannot be used as variable name`)
-      );
-    }
-    for (const key in options) {
-      if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key))
-        continue;
-      return Promise.reject(
-        new Error(
-          `[@octokit/graphql] "${key}" cannot be used as variable name`
-        )
-      );
-    }
-  }
-  const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query;
-  const requestOptions = Object.keys(
-    parsedOptions
-  ).reduce((result, key) => {
-    if (NON_VARIABLE_OPTIONS.includes(key)) {
-      result[key] = parsedOptions[key];
-      return result;
-    }
-    if (!result.variables) {
-      result.variables = {};
-    }
-    result.variables[key] = parsedOptions[key];
-    return result;
-  }, {});
-  const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;
-  if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {
-    requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql");
-  }
-  return request2(requestOptions).then((response) => {
-    if (response.data.errors) {
-      const headers = {};
-      for (const key of Object.keys(response.headers)) {
-        headers[key] = response.headers[key];
-      }
-      throw new GraphqlResponseError(
-        requestOptions,
-        headers,
-        response.data
-      );
-    }
-    return response.data.data;
-  });
-}
-
-// pkg/dist-src/with-defaults.js
-function withDefaults(request2, newDefaults) {
-  const newRequest = request2.defaults(newDefaults);
-  const newApi = (query, options) => {
-    return graphql(newRequest, query, options);
-  };
-  return Object.assign(newApi, {
-    defaults: withDefaults.bind(null, newRequest),
-    endpoint: newRequest.endpoint
-  });
-}
-
-// pkg/dist-src/index.js
-var graphql2 = withDefaults(import_request3.request, {
-  headers: {
-    "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
-  },
-  method: "POST",
-  url: "/graphql"
-});
-function withCustomRequest(customRequest) {
-  return withDefaults(customRequest, {
-    method: "POST",
-    url: "/graphql"
-  });
-}
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
-
-
-/***/ }),
-
-/***/ 38082:
-/***/ ((module) => {
-
-"use strict";
-
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  composePaginateRest: () => composePaginateRest,
-  isPaginatingEndpoint: () => isPaginatingEndpoint,
-  paginateRest: () => paginateRest,
-  paginatingEndpoints: () => paginatingEndpoints
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/version.js
-var VERSION = "9.2.2";
-
-// pkg/dist-src/normalize-paginated-list-response.js
-function normalizePaginatedListResponse(response) {
-  if (!response.data) {
-    return {
-      ...response,
-      data: []
-    };
-  }
-  const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data);
-  if (!responseNeedsNormalization)
-    return response;
-  const incompleteResults = response.data.incomplete_results;
-  const repositorySelection = response.data.repository_selection;
-  const totalCount = response.data.total_count;
-  delete response.data.incomplete_results;
-  delete response.data.repository_selection;
-  delete response.data.total_count;
-  const namespaceKey = Object.keys(response.data)[0];
-  const data = response.data[namespaceKey];
-  response.data = data;
-  if (typeof incompleteResults !== "undefined") {
-    response.data.incomplete_results = incompleteResults;
-  }
-  if (typeof repositorySelection !== "undefined") {
-    response.data.repository_selection = repositorySelection;
-  }
-  response.data.total_count = totalCount;
-  return response;
-}
-
-// pkg/dist-src/iterator.js
-function iterator(octokit, route, parameters) {
-  const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);
-  const requestMethod = typeof route === "function" ? route : octokit.request;
-  const method = options.method;
-  const headers = options.headers;
-  let url = options.url;
-  return {
-    [Symbol.asyncIterator]: () => ({
-      async next() {
-        if (!url)
-          return { done: true };
-        try {
-          const response = await requestMethod({ method, url, headers });
-          const normalizedResponse = normalizePaginatedListResponse(response);
-          url = ((normalizedResponse.headers.link || "").match(
-            /<([^<>]+)>;\s*rel="next"/
-          ) || [])[1];
-          return { value: normalizedResponse };
-        } catch (error) {
-          if (error.status !== 409)
-            throw error;
-          url = "";
-          return {
-            value: {
-              status: 200,
-              headers: {},
-              data: []
-            }
-          };
-        }
-      }
-    })
-  };
-}
-
-// pkg/dist-src/paginate.js
-function paginate(octokit, route, parameters, mapFn) {
-  if (typeof parameters === "function") {
-    mapFn = parameters;
-    parameters = void 0;
-  }
-  return gather(
-    octokit,
-    [],
-    iterator(octokit, route, parameters)[Symbol.asyncIterator](),
-    mapFn
-  );
-}
-function gather(octokit, results, iterator2, mapFn) {
-  return iterator2.next().then((result) => {
-    if (result.done) {
-      return results;
-    }
-    let earlyExit = false;
-    function done() {
-      earlyExit = true;
-    }
-    results = results.concat(
-      mapFn ? mapFn(result.value, done) : result.value.data
-    );
-    if (earlyExit) {
-      return results;
-    }
-    return gather(octokit, results, iterator2, mapFn);
-  });
-}
-
-// pkg/dist-src/compose-paginate.js
-var composePaginateRest = Object.assign(paginate, {
-  iterator
-});
-
-// pkg/dist-src/generated/paginating-endpoints.js
-var paginatingEndpoints = [
-  "GET /advisories",
-  "GET /app/hook/deliveries",
-  "GET /app/installation-requests",
-  "GET /app/installations",
-  "GET /assignments/{assignment_id}/accepted_assignments",
-  "GET /classrooms",
-  "GET /classrooms/{classroom_id}/assignments",
-  "GET /enterprises/{enterprise}/dependabot/alerts",
-  "GET /enterprises/{enterprise}/secret-scanning/alerts",
-  "GET /events",
-  "GET /gists",
-  "GET /gists/public",
-  "GET /gists/starred",
-  "GET /gists/{gist_id}/comments",
-  "GET /gists/{gist_id}/commits",
-  "GET /gists/{gist_id}/forks",
-  "GET /installation/repositories",
-  "GET /issues",
-  "GET /licenses",
-  "GET /marketplace_listing/plans",
-  "GET /marketplace_listing/plans/{plan_id}/accounts",
-  "GET /marketplace_listing/stubbed/plans",
-  "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts",
-  "GET /networks/{owner}/{repo}/events",
-  "GET /notifications",
-  "GET /organizations",
-  "GET /orgs/{org}/actions/cache/usage-by-repository",
-  "GET /orgs/{org}/actions/permissions/repositories",
-  "GET /orgs/{org}/actions/runners",
-  "GET /orgs/{org}/actions/secrets",
-  "GET /orgs/{org}/actions/secrets/{secret_name}/repositories",
-  "GET /orgs/{org}/actions/variables",
-  "GET /orgs/{org}/actions/variables/{name}/repositories",
-  "GET /orgs/{org}/blocks",
-  "GET /orgs/{org}/code-scanning/alerts",
-  "GET /orgs/{org}/codespaces",
-  "GET /orgs/{org}/codespaces/secrets",
-  "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories",
-  "GET /orgs/{org}/copilot/billing/seats",
-  "GET /orgs/{org}/dependabot/alerts",
-  "GET /orgs/{org}/dependabot/secrets",
-  "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories",
-  "GET /orgs/{org}/events",
-  "GET /orgs/{org}/failed_invitations",
-  "GET /orgs/{org}/hooks",
-  "GET /orgs/{org}/hooks/{hook_id}/deliveries",
-  "GET /orgs/{org}/installations",
-  "GET /orgs/{org}/invitations",
-  "GET /orgs/{org}/invitations/{invitation_id}/teams",
-  "GET /orgs/{org}/issues",
-  "GET /orgs/{org}/members",
-  "GET /orgs/{org}/members/{username}/codespaces",
-  "GET /orgs/{org}/migrations",
-  "GET /orgs/{org}/migrations/{migration_id}/repositories",
-  "GET /orgs/{org}/organization-roles/{role_id}/teams",
-  "GET /orgs/{org}/organization-roles/{role_id}/users",
-  "GET /orgs/{org}/outside_collaborators",
-  "GET /orgs/{org}/packages",
-  "GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
-  "GET /orgs/{org}/personal-access-token-requests",
-  "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories",
-  "GET /orgs/{org}/personal-access-tokens",
-  "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories",
-  "GET /orgs/{org}/projects",
-  "GET /orgs/{org}/properties/values",
-  "GET /orgs/{org}/public_members",
-  "GET /orgs/{org}/repos",
-  "GET /orgs/{org}/rulesets",
-  "GET /orgs/{org}/rulesets/rule-suites",
-  "GET /orgs/{org}/secret-scanning/alerts",
-  "GET /orgs/{org}/security-advisories",
-  "GET /orgs/{org}/teams",
-  "GET /orgs/{org}/teams/{team_slug}/discussions",
-  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments",
-  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions",
-  "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions",
-  "GET /orgs/{org}/teams/{team_slug}/invitations",
-  "GET /orgs/{org}/teams/{team_slug}/members",
-  "GET /orgs/{org}/teams/{team_slug}/projects",
-  "GET /orgs/{org}/teams/{team_slug}/repos",
-  "GET /orgs/{org}/teams/{team_slug}/teams",
-  "GET /projects/columns/{column_id}/cards",
-  "GET /projects/{project_id}/collaborators",
-  "GET /projects/{project_id}/columns",
-  "GET /repos/{owner}/{repo}/actions/artifacts",
-  "GET /repos/{owner}/{repo}/actions/caches",
-  "GET /repos/{owner}/{repo}/actions/organization-secrets",
-  "GET /repos/{owner}/{repo}/actions/organization-variables",
-  "GET /repos/{owner}/{repo}/actions/runners",
-  "GET /repos/{owner}/{repo}/actions/runs",
-  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts",
-  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs",
-  "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs",
-  "GET /repos/{owner}/{repo}/actions/secrets",
-  "GET /repos/{owner}/{repo}/actions/variables",
-  "GET /repos/{owner}/{repo}/actions/workflows",
-  "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs",
-  "GET /repos/{owner}/{repo}/activity",
-  "GET /repos/{owner}/{repo}/assignees",
-  "GET /repos/{owner}/{repo}/branches",
-  "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations",
-  "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs",
-  "GET /repos/{owner}/{repo}/code-scanning/alerts",
-  "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances",
-  "GET /repos/{owner}/{repo}/code-scanning/analyses",
-  "GET /repos/{owner}/{repo}/codespaces",
-  "GET /repos/{owner}/{repo}/codespaces/devcontainers",
-  "GET /repos/{owner}/{repo}/codespaces/secrets",
-  "GET /repos/{owner}/{repo}/collaborators",
-  "GET /repos/{owner}/{repo}/comments",
-  "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions",
-  "GET /repos/{owner}/{repo}/commits",
-  "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments",
-  "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls",
-  "GET /repos/{owner}/{repo}/commits/{ref}/check-runs",
-  "GET /repos/{owner}/{repo}/commits/{ref}/check-suites",
-  "GET /repos/{owner}/{repo}/commits/{ref}/status",
-  "GET /repos/{owner}/{repo}/commits/{ref}/statuses",
-  "GET /repos/{owner}/{repo}/contributors",
-  "GET /repos/{owner}/{repo}/dependabot/alerts",
-  "GET /repos/{owner}/{repo}/dependabot/secrets",
-  "GET /repos/{owner}/{repo}/deployments",
-  "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses",
-  "GET /repos/{owner}/{repo}/environments",
-  "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies",
-  "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps",
-  "GET /repos/{owner}/{repo}/events",
-  "GET /repos/{owner}/{repo}/forks",
-  "GET /repos/{owner}/{repo}/hooks",
-  "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries",
-  "GET /repos/{owner}/{repo}/invitations",
-  "GET /repos/{owner}/{repo}/issues",
-  "GET /repos/{owner}/{repo}/issues/comments",
-  "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions",
-  "GET /repos/{owner}/{repo}/issues/events",
-  "GET /repos/{owner}/{repo}/issues/{issue_number}/comments",
-  "GET /repos/{owner}/{repo}/issues/{issue_number}/events",
-  "GET /repos/{owner}/{repo}/issues/{issue_number}/labels",
-  "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions",
-  "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline",
-  "GET /repos/{owner}/{repo}/keys",
-  "GET /repos/{owner}/{repo}/labels",
-  "GET /repos/{owner}/{repo}/milestones",
-  "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels",
-  "GET /repos/{owner}/{repo}/notifications",
-  "GET /repos/{owner}/{repo}/pages/builds",
-  "GET /repos/{owner}/{repo}/projects",
-  "GET /repos/{owner}/{repo}/pulls",
-  "GET /repos/{owner}/{repo}/pulls/comments",
-  "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions",
-  "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments",
-  "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits",
-  "GET /repos/{owner}/{repo}/pulls/{pull_number}/files",
-  "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews",
-  "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments",
-  "GET /repos/{owner}/{repo}/releases",
-  "GET /repos/{owner}/{repo}/releases/{release_id}/assets",
-  "GET /repos/{owner}/{repo}/releases/{release_id}/reactions",
-  "GET /repos/{owner}/{repo}/rules/branches/{branch}",
-  "GET /repos/{owner}/{repo}/rulesets",
-  "GET /repos/{owner}/{repo}/rulesets/rule-suites",
-  "GET /repos/{owner}/{repo}/secret-scanning/alerts",
-  "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations",
-  "GET /repos/{owner}/{repo}/security-advisories",
-  "GET /repos/{owner}/{repo}/stargazers",
-  "GET /repos/{owner}/{repo}/subscribers",
-  "GET /repos/{owner}/{repo}/tags",
-  "GET /repos/{owner}/{repo}/teams",
-  "GET /repos/{owner}/{repo}/topics",
-  "GET /repositories",
-  "GET /repositories/{repository_id}/environments/{environment_name}/secrets",
-  "GET /repositories/{repository_id}/environments/{environment_name}/variables",
-  "GET /search/code",
-  "GET /search/commits",
-  "GET /search/issues",
-  "GET /search/labels",
-  "GET /search/repositories",
-  "GET /search/topics",
-  "GET /search/users",
-  "GET /teams/{team_id}/discussions",
-  "GET /teams/{team_id}/discussions/{discussion_number}/comments",
-  "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions",
-  "GET /teams/{team_id}/discussions/{discussion_number}/reactions",
-  "GET /teams/{team_id}/invitations",
-  "GET /teams/{team_id}/members",
-  "GET /teams/{team_id}/projects",
-  "GET /teams/{team_id}/repos",
-  "GET /teams/{team_id}/teams",
-  "GET /user/blocks",
-  "GET /user/codespaces",
-  "GET /user/codespaces/secrets",
-  "GET /user/emails",
-  "GET /user/followers",
-  "GET /user/following",
-  "GET /user/gpg_keys",
-  "GET /user/installations",
-  "GET /user/installations/{installation_id}/repositories",
-  "GET /user/issues",
-  "GET /user/keys",
-  "GET /user/marketplace_purchases",
-  "GET /user/marketplace_purchases/stubbed",
-  "GET /user/memberships/orgs",
-  "GET /user/migrations",
-  "GET /user/migrations/{migration_id}/repositories",
-  "GET /user/orgs",
-  "GET /user/packages",
-  "GET /user/packages/{package_type}/{package_name}/versions",
-  "GET /user/public_emails",
-  "GET /user/repos",
-  "GET /user/repository_invitations",
-  "GET /user/social_accounts",
-  "GET /user/ssh_signing_keys",
-  "GET /user/starred",
-  "GET /user/subscriptions",
-  "GET /user/teams",
-  "GET /users",
-  "GET /users/{username}/events",
-  "GET /users/{username}/events/orgs/{org}",
-  "GET /users/{username}/events/public",
-  "GET /users/{username}/followers",
-  "GET /users/{username}/following",
-  "GET /users/{username}/gists",
-  "GET /users/{username}/gpg_keys",
-  "GET /users/{username}/keys",
-  "GET /users/{username}/orgs",
-  "GET /users/{username}/packages",
-  "GET /users/{username}/projects",
-  "GET /users/{username}/received_events",
-  "GET /users/{username}/received_events/public",
-  "GET /users/{username}/repos",
-  "GET /users/{username}/social_accounts",
-  "GET /users/{username}/ssh_signing_keys",
-  "GET /users/{username}/starred",
-  "GET /users/{username}/subscriptions"
-];
-
-// pkg/dist-src/paginating-endpoints.js
-function isPaginatingEndpoint(arg) {
-  if (typeof arg === "string") {
-    return paginatingEndpoints.includes(arg);
-  } else {
-    return false;
-  }
-}
-
-// pkg/dist-src/index.js
-function paginateRest(octokit) {
-  return {
-    paginate: Object.assign(paginate.bind(null, octokit), {
-      iterator: iterator.bind(null, octokit)
-    })
-  };
-}
-paginateRest.VERSION = VERSION;
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
-
-
-/***/ }),
-
-/***/ 84935:
-/***/ ((module) => {
-
-"use strict";
-
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  legacyRestEndpointMethods: () => legacyRestEndpointMethods,
-  restEndpointMethods: () => restEndpointMethods
-});
-module.exports = __toCommonJS(dist_src_exports);
-
-// pkg/dist-src/version.js
-var VERSION = "10.3.0";
+// pkg/dist-src/version.js
+var VERSION = "10.3.0";
 
 // pkg/dist-src/generated/endpoints.js
 var Endpoints = {
@@ -12424,610 +9864,3034 @@ var Endpoints = {
     updateAuthenticated: ["PATCH /user"]
   }
 };
-var endpoints_default = Endpoints;
+var endpoints_default = Endpoints;
+
+// pkg/dist-src/endpoints-to-methods.js
+var endpointMethodsMap = /* @__PURE__ */ new Map();
+for (const [scope, endpoints] of Object.entries(endpoints_default)) {
+  for (const [methodName, endpoint] of Object.entries(endpoints)) {
+    const [route, defaults, decorations] = endpoint;
+    const [method, url] = route.split(/ /);
+    const endpointDefaults = Object.assign(
+      {
+        method,
+        url
+      },
+      defaults
+    );
+    if (!endpointMethodsMap.has(scope)) {
+      endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());
+    }
+    endpointMethodsMap.get(scope).set(methodName, {
+      scope,
+      methodName,
+      endpointDefaults,
+      decorations
+    });
+  }
+}
+var handler = {
+  has({ scope }, methodName) {
+    return endpointMethodsMap.get(scope).has(methodName);
+  },
+  getOwnPropertyDescriptor(target, methodName) {
+    return {
+      value: this.get(target, methodName),
+      // ensures method is in the cache
+      configurable: true,
+      writable: true,
+      enumerable: true
+    };
+  },
+  defineProperty(target, methodName, descriptor) {
+    Object.defineProperty(target.cache, methodName, descriptor);
+    return true;
+  },
+  deleteProperty(target, methodName) {
+    delete target.cache[methodName];
+    return true;
+  },
+  ownKeys({ scope }) {
+    return [...endpointMethodsMap.get(scope).keys()];
+  },
+  set(target, methodName, value) {
+    return target.cache[methodName] = value;
+  },
+  get({ octokit, scope, cache }, methodName) {
+    if (cache[methodName]) {
+      return cache[methodName];
+    }
+    const method = endpointMethodsMap.get(scope).get(methodName);
+    if (!method) {
+      return void 0;
+    }
+    const { endpointDefaults, decorations } = method;
+    if (decorations) {
+      cache[methodName] = decorate(
+        octokit,
+        scope,
+        methodName,
+        endpointDefaults,
+        decorations
+      );
+    } else {
+      cache[methodName] = octokit.request.defaults(endpointDefaults);
+    }
+    return cache[methodName];
+  }
+};
+function endpointsToMethods(octokit) {
+  const newMethods = {};
+  for (const scope of endpointMethodsMap.keys()) {
+    newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);
+  }
+  return newMethods;
+}
+function decorate(octokit, scope, methodName, defaults, decorations) {
+  const requestWithDefaults = octokit.request.defaults(defaults);
+  function withDecorations(...args) {
+    let options = requestWithDefaults.endpoint.merge(...args);
+    if (decorations.mapToData) {
+      options = Object.assign({}, options, {
+        data: options[decorations.mapToData],
+        [decorations.mapToData]: void 0
+      });
+      return requestWithDefaults(options);
+    }
+    if (decorations.renamed) {
+      const [newScope, newMethodName] = decorations.renamed;
+      octokit.log.warn(
+        `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`
+      );
+    }
+    if (decorations.deprecated) {
+      octokit.log.warn(decorations.deprecated);
+    }
+    if (decorations.renamedParameters) {
+      const options2 = requestWithDefaults.endpoint.merge(...args);
+      for (const [name, alias] of Object.entries(
+        decorations.renamedParameters
+      )) {
+        if (name in options2) {
+          octokit.log.warn(
+            `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`
+          );
+          if (!(alias in options2)) {
+            options2[alias] = options2[name];
+          }
+          delete options2[name];
+        }
+      }
+      return requestWithDefaults(options2);
+    }
+    return requestWithDefaults(...args);
+  }
+  return Object.assign(withDecorations, requestWithDefaults);
+}
+
+// pkg/dist-src/index.js
+function restEndpointMethods(octokit) {
+  const api = endpointsToMethods(octokit);
+  return {
+    rest: api
+  };
+}
+restEndpointMethods.VERSION = VERSION;
+function legacyRestEndpointMethods(octokit) {
+  const api = endpointsToMethods(octokit);
+  return {
+    ...api,
+    rest: api
+  };
+}
+legacyRestEndpointMethods.VERSION = VERSION;
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+
+
+/***/ }),
+
+/***/ 33450:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__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: true }) : target,
+  mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  VERSION: () => VERSION,
+  retry: () => retry
+});
+module.exports = __toCommonJS(dist_src_exports);
+var import_core = __nccwpck_require__(61897);
+
+// pkg/dist-src/error-request.js
+async function errorRequest(state, octokit, error, options) {
+  if (!error.request || !error.request.request) {
+    throw error;
+  }
+  if (error.status >= 400 && !state.doNotRetry.includes(error.status)) {
+    const retries = options.request.retries != null ? options.request.retries : state.retries;
+    const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2);
+    throw octokit.retry.retryRequest(error, retries, retryAfter);
+  }
+  throw error;
+}
+
+// pkg/dist-src/wrap-request.js
+var import_light = __toESM(__nccwpck_require__(63251));
+var import_request_error = __nccwpck_require__(93708);
+async function wrapRequest(state, octokit, request, options) {
+  const limiter = new import_light.default();
+  limiter.on("failed", function(error, info) {
+    const maxRetries = ~~error.request.request.retries;
+    const after = ~~error.request.request.retryAfter;
+    options.request.retryCount = info.retryCount + 1;
+    if (maxRetries > info.retryCount) {
+      return after * state.retryAfterBaseValue;
+    }
+  });
+  return limiter.schedule(
+    requestWithGraphqlErrorHandling.bind(null, state, octokit, request),
+    options
+  );
+}
+async function requestWithGraphqlErrorHandling(state, octokit, request, options) {
+  const response = await request(request, options);
+  if (response.data && response.data.errors && /Something went wrong while executing your query/.test(
+    response.data.errors[0].message
+  )) {
+    const error = new import_request_error.RequestError(response.data.errors[0].message, 500, {
+      request: options,
+      response
+    });
+    return errorRequest(state, octokit, error, options);
+  }
+  return response;
+}
+
+// pkg/dist-src/index.js
+var VERSION = "6.0.1";
+function retry(octokit, octokitOptions) {
+  const state = Object.assign(
+    {
+      enabled: true,
+      retryAfterBaseValue: 1e3,
+      doNotRetry: [400, 401, 403, 404, 422, 451],
+      retries: 3
+    },
+    octokitOptions.retry
+  );
+  if (state.enabled) {
+    octokit.hook.error("request", errorRequest.bind(null, state, octokit));
+    octokit.hook.wrap("request", wrapRequest.bind(null, state, octokit));
+  }
+  return {
+    retry: {
+      retryRequest: (error, retries, retryAfter) => {
+        error.request.request = Object.assign({}, error.request.request, {
+          retries,
+          retryAfter
+        });
+        return error;
+      }
+    }
+  };
+}
+retry.VERSION = VERSION;
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+
+
+/***/ }),
+
+/***/ 93708:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__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: true }) : target,
+  mod
+));
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  RequestError: () => RequestError
+});
+module.exports = __toCommonJS(dist_src_exports);
+var import_deprecation = __nccwpck_require__(14150);
+var import_once = __toESM(__nccwpck_require__(55560));
+var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));
+var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));
+var RequestError = class extends Error {
+  constructor(message, statusCode, options) {
+    super(message);
+    if (Error.captureStackTrace) {
+      Error.captureStackTrace(this, this.constructor);
+    }
+    this.name = "HttpError";
+    this.status = statusCode;
+    let headers;
+    if ("headers" in options && typeof options.headers !== "undefined") {
+      headers = options.headers;
+    }
+    if ("response" in options) {
+      this.response = options.response;
+      headers = options.response.headers;
+    }
+    const requestCopy = Object.assign({}, options.request);
+    if (options.request.headers.authorization) {
+      requestCopy.headers = Object.assign({}, options.request.headers, {
+        authorization: options.request.headers.authorization.replace(
+          /(? {
+
+"use strict";
+
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __export = (target, all) => {
+  for (var name in all)
+    __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+  if (from && typeof from === "object" || typeof from === "function") {
+    for (let key of __getOwnPropNames(from))
+      if (!__hasOwnProp.call(to, key) && key !== except)
+        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+  }
+  return to;
+};
+var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+
+// pkg/dist-src/index.js
+var dist_src_exports = {};
+__export(dist_src_exports, {
+  request: () => request
+});
+module.exports = __toCommonJS(dist_src_exports);
+var import_endpoint = __nccwpck_require__(54471);
+var import_universal_user_agent = __nccwpck_require__(33843);
+
+// pkg/dist-src/version.js
+var VERSION = "8.2.0";
+
+// pkg/dist-src/is-plain-object.js
+function isPlainObject(value) {
+  if (typeof value !== "object" || value === null)
+    return false;
+  if (Object.prototype.toString.call(value) !== "[object Object]")
+    return false;
+  const proto = Object.getPrototypeOf(value);
+  if (proto === null)
+    return true;
+  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
+  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
+}
+
+// pkg/dist-src/fetch-wrapper.js
+var import_request_error = __nccwpck_require__(93708);
+
+// pkg/dist-src/get-buffer-response.js
+function getBufferResponse(response) {
+  return response.arrayBuffer();
+}
+
+// pkg/dist-src/fetch-wrapper.js
+function fetchWrapper(requestOptions) {
+  var _a, _b, _c;
+  const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
+  const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;
+  if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
+    requestOptions.body = JSON.stringify(requestOptions.body);
+  }
+  let headers = {};
+  let status;
+  let url;
+  let { fetch } = globalThis;
+  if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {
+    fetch = requestOptions.request.fetch;
+  }
+  if (!fetch) {
+    throw new Error(
+      "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing"
+    );
+  }
+  return fetch(requestOptions.url, {
+    method: requestOptions.method,
+    body: requestOptions.body,
+    headers: requestOptions.headers,
+    signal: (_c = requestOptions.request) == null ? void 0 : _c.signal,
+    // duplex must be set if request.body is ReadableStream or Async Iterables.
+    // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.
+    ...requestOptions.body && { duplex: "half" }
+  }).then(async (response) => {
+    url = response.url;
+    status = response.status;
+    for (const keyAndValue of response.headers) {
+      headers[keyAndValue[0]] = keyAndValue[1];
+    }
+    if ("deprecation" in headers) {
+      const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
+      const deprecationLink = matches && matches.pop();
+      log.warn(
+        `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
+      );
+    }
+    if (status === 204 || status === 205) {
+      return;
+    }
+    if (requestOptions.method === "HEAD") {
+      if (status < 400) {
+        return;
+      }
+      throw new import_request_error.RequestError(response.statusText, status, {
+        response: {
+          url,
+          status,
+          headers,
+          data: void 0
+        },
+        request: requestOptions
+      });
+    }
+    if (status === 304) {
+      throw new import_request_error.RequestError("Not modified", status, {
+        response: {
+          url,
+          status,
+          headers,
+          data: await getResponseData(response)
+        },
+        request: requestOptions
+      });
+    }
+    if (status >= 400) {
+      const data = await getResponseData(response);
+      const error = new import_request_error.RequestError(toErrorMessage(data), status, {
+        response: {
+          url,
+          status,
+          headers,
+          data
+        },
+        request: requestOptions
+      });
+      throw error;
+    }
+    return parseSuccessResponseBody ? await getResponseData(response) : response.body;
+  }).then((data) => {
+    return {
+      status,
+      url,
+      headers,
+      data
+    };
+  }).catch((error) => {
+    if (error instanceof import_request_error.RequestError)
+      throw error;
+    else if (error.name === "AbortError")
+      throw error;
+    let message = error.message;
+    if (error.name === "TypeError" && "cause" in error) {
+      if (error.cause instanceof Error) {
+        message = error.cause.message;
+      } else if (typeof error.cause === "string") {
+        message = error.cause;
+      }
+    }
+    throw new import_request_error.RequestError(message, 500, {
+      request: requestOptions
+    });
+  });
+}
+async function getResponseData(response) {
+  const contentType = response.headers.get("content-type");
+  if (/application\/json/.test(contentType)) {
+    return response.json().catch(() => response.text()).catch(() => "");
+  }
+  if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
+    return response.text();
+  }
+  return getBufferResponse(response);
+}
+function toErrorMessage(data) {
+  if (typeof data === "string")
+    return data;
+  let suffix;
+  if ("documentation_url" in data) {
+    suffix = ` - ${data.documentation_url}`;
+  } else {
+    suffix = "";
+  }
+  if ("message" in data) {
+    if (Array.isArray(data.errors)) {
+      return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`;
+    }
+    return `${data.message}${suffix}`;
+  }
+  return `Unknown error: ${JSON.stringify(data)}`;
+}
+
+// pkg/dist-src/with-defaults.js
+function withDefaults(oldEndpoint, newDefaults) {
+  const endpoint2 = oldEndpoint.defaults(newDefaults);
+  const newApi = function(route, parameters) {
+    const endpointOptions = endpoint2.merge(route, parameters);
+    if (!endpointOptions.request || !endpointOptions.request.hook) {
+      return fetchWrapper(endpoint2.parse(endpointOptions));
+    }
+    const request2 = (route2, parameters2) => {
+      return fetchWrapper(
+        endpoint2.parse(endpoint2.merge(route2, parameters2))
+      );
+    };
+    Object.assign(request2, {
+      endpoint: endpoint2,
+      defaults: withDefaults.bind(null, endpoint2)
+    });
+    return endpointOptions.request.hook(request2, endpointOptions);
+  };
+  return Object.assign(newApi, {
+    endpoint: endpoint2,
+    defaults: withDefaults.bind(null, endpoint2)
+  });
+}
+
+// pkg/dist-src/index.js
+var request = withDefaults(import_endpoint.endpoint, {
+  headers: {
+    "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
+  }
+});
+// Annotate the CommonJS export names for ESM import in node:
+0 && (0);
+
+
+/***/ }),
+
+/***/ 18456:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toMessageSignatureBundle = toMessageSignatureBundle;
+exports.toDSSEBundle = toDSSEBundle;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const protobuf_specs_1 = __nccwpck_require__(19654);
+const bundle_1 = __nccwpck_require__(37742);
+// Message signature bundle - $case: 'messageSignature'
+function toMessageSignatureBundle(options) {
+    return {
+        mediaType: options.certificateChain
+            ? bundle_1.BUNDLE_V02_MEDIA_TYPE
+            : bundle_1.BUNDLE_V03_MEDIA_TYPE,
+        content: {
+            $case: 'messageSignature',
+            messageSignature: {
+                messageDigest: {
+                    algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256,
+                    digest: options.digest,
+                },
+                signature: options.signature,
+            },
+        },
+        verificationMaterial: toVerificationMaterial(options),
+    };
+}
+// DSSE envelope bundle - $case: 'dsseEnvelope'
+function toDSSEBundle(options) {
+    return {
+        mediaType: options.certificateChain
+            ? bundle_1.BUNDLE_V02_MEDIA_TYPE
+            : bundle_1.BUNDLE_V03_MEDIA_TYPE,
+        content: {
+            $case: 'dsseEnvelope',
+            dsseEnvelope: toEnvelope(options),
+        },
+        verificationMaterial: toVerificationMaterial(options),
+    };
+}
+function toEnvelope(options) {
+    return {
+        payloadType: options.artifactType,
+        payload: options.artifact,
+        signatures: [toSignature(options)],
+    };
+}
+function toSignature(options) {
+    return {
+        keyid: options.keyHint || '',
+        sig: options.signature,
+    };
+}
+// Verification material
+function toVerificationMaterial(options) {
+    return {
+        content: toKeyContent(options),
+        tlogEntries: [],
+        timestampVerificationData: { rfc3161Timestamps: [] },
+    };
+}
+function toKeyContent(options) {
+    if (options.certificate) {
+        if (options.certificateChain) {
+            return {
+                $case: 'x509CertificateChain',
+                x509CertificateChain: {
+                    certificates: [{ rawBytes: options.certificate }],
+                },
+            };
+        }
+        else {
+            return {
+                $case: 'certificate',
+                certificate: { rawBytes: options.certificate },
+            };
+        }
+    }
+    else {
+        return {
+            $case: 'publicKey',
+            publicKey: {
+                hint: options.keyHint || '',
+            },
+        };
+    }
+}
+
+
+/***/ }),
+
+/***/ 37742:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0;
+exports.isBundleWithCertificateChain = isBundleWithCertificateChain;
+exports.isBundleWithPublicKey = isBundleWithPublicKey;
+exports.isBundleWithMessageSignature = isBundleWithMessageSignature;
+exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope;
+exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1';
+exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2';
+exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3';
+exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json';
+// Type guards for bundle variants.
+function isBundleWithCertificateChain(b) {
+    return b.verificationMaterial.content.$case === 'x509CertificateChain';
+}
+function isBundleWithPublicKey(b) {
+    return b.verificationMaterial.content.$case === 'publicKey';
+}
+function isBundleWithMessageSignature(b) {
+    return b.content.$case === 'messageSignature';
+}
+function isBundleWithDsseEnvelope(b) {
+    return b.content.$case === 'dsseEnvelope';
+}
+
+
+/***/ }),
+
+/***/ 47714:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ValidationError = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+class ValidationError extends Error {
+    constructor(message, fields) {
+        super(message);
+        this.fields = fields;
+    }
+}
+exports.ValidationError = ValidationError;
+
+
+/***/ }),
+
+/***/ 61040:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+var build_1 = __nccwpck_require__(18456);
+Object.defineProperty(exports, "toDSSEBundle", ({ enumerable: true, get: function () { return build_1.toDSSEBundle; } }));
+Object.defineProperty(exports, "toMessageSignatureBundle", ({ enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } }));
+var bundle_1 = __nccwpck_require__(37742);
+Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } }));
+Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } }));
+Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } }));
+Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } }));
+Object.defineProperty(exports, "isBundleWithCertificateChain", ({ enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } }));
+Object.defineProperty(exports, "isBundleWithDsseEnvelope", ({ enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } }));
+Object.defineProperty(exports, "isBundleWithMessageSignature", ({ enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } }));
+Object.defineProperty(exports, "isBundleWithPublicKey", ({ enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } }));
+var error_1 = __nccwpck_require__(47714);
+Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return error_1.ValidationError; } }));
+var serialized_1 = __nccwpck_require__(23404);
+Object.defineProperty(exports, "bundleFromJSON", ({ enumerable: true, get: function () { return serialized_1.bundleFromJSON; } }));
+Object.defineProperty(exports, "bundleToJSON", ({ enumerable: true, get: function () { return serialized_1.bundleToJSON; } }));
+Object.defineProperty(exports, "envelopeFromJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } }));
+Object.defineProperty(exports, "envelopeToJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeToJSON; } }));
+var validate_1 = __nccwpck_require__(9352);
+Object.defineProperty(exports, "assertBundle", ({ enumerable: true, get: function () { return validate_1.assertBundle; } }));
+Object.defineProperty(exports, "assertBundleLatest", ({ enumerable: true, get: function () { return validate_1.assertBundleLatest; } }));
+Object.defineProperty(exports, "assertBundleV01", ({ enumerable: true, get: function () { return validate_1.assertBundleV01; } }));
+Object.defineProperty(exports, "assertBundleV02", ({ enumerable: true, get: function () { return validate_1.assertBundleV02; } }));
+Object.defineProperty(exports, "isBundleV01", ({ enumerable: true, get: function () { return validate_1.isBundleV01; } }));
+
+
+/***/ }),
+
+/***/ 23404:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const protobuf_specs_1 = __nccwpck_require__(19654);
+const bundle_1 = __nccwpck_require__(37742);
+const validate_1 = __nccwpck_require__(9352);
+const bundleFromJSON = (obj) => {
+    const bundle = protobuf_specs_1.Bundle.fromJSON(obj);
+    switch (bundle.mediaType) {
+        case bundle_1.BUNDLE_V01_MEDIA_TYPE:
+            (0, validate_1.assertBundleV01)(bundle);
+            break;
+        case bundle_1.BUNDLE_V02_MEDIA_TYPE:
+            (0, validate_1.assertBundleV02)(bundle);
+            break;
+        default:
+            (0, validate_1.assertBundleLatest)(bundle);
+            break;
+    }
+    return bundle;
+};
+exports.bundleFromJSON = bundleFromJSON;
+const bundleToJSON = (bundle) => {
+    return protobuf_specs_1.Bundle.toJSON(bundle);
+};
+exports.bundleToJSON = bundleToJSON;
+const envelopeFromJSON = (obj) => {
+    return protobuf_specs_1.Envelope.fromJSON(obj);
+};
+exports.envelopeFromJSON = envelopeFromJSON;
+const envelopeToJSON = (envelope) => {
+    return protobuf_specs_1.Envelope.toJSON(envelope);
+};
+exports.envelopeToJSON = envelopeToJSON;
+
+
+/***/ }),
+
+/***/ 9352:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.assertBundle = assertBundle;
+exports.assertBundleV01 = assertBundleV01;
+exports.isBundleV01 = isBundleV01;
+exports.assertBundleV02 = assertBundleV02;
+exports.assertBundleLatest = assertBundleLatest;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const error_1 = __nccwpck_require__(47714);
+// Performs basic validation of a Sigstore bundle to ensure that all required
+// fields are populated. This is not a complete validation of the bundle, but
+// rather a check that the bundle is in a valid state to be processed by the
+// rest of the code.
+function assertBundle(b) {
+    const invalidValues = validateBundleBase(b);
+    if (invalidValues.length > 0) {
+        throw new error_1.ValidationError('invalid bundle', invalidValues);
+    }
+}
+// Asserts that the given bundle conforms to the v0.1 bundle format.
+function assertBundleV01(b) {
+    const invalidValues = [];
+    invalidValues.push(...validateBundleBase(b));
+    invalidValues.push(...validateInclusionPromise(b));
+    if (invalidValues.length > 0) {
+        throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues);
+    }
+}
+// Type guard to determine if Bundle is a v0.1 bundle.
+function isBundleV01(b) {
+    try {
+        assertBundleV01(b);
+        return true;
+    }
+    catch (e) {
+        return false;
+    }
+}
+// Asserts that the given bundle conforms to the v0.2 bundle format.
+function assertBundleV02(b) {
+    const invalidValues = [];
+    invalidValues.push(...validateBundleBase(b));
+    invalidValues.push(...validateInclusionProof(b));
+    if (invalidValues.length > 0) {
+        throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues);
+    }
+}
+// Asserts that the given bundle conforms to the newest (0.3) bundle format.
+function assertBundleLatest(b) {
+    const invalidValues = [];
+    invalidValues.push(...validateBundleBase(b));
+    invalidValues.push(...validateInclusionProof(b));
+    invalidValues.push(...validateNoCertificateChain(b));
+    if (invalidValues.length > 0) {
+        throw new error_1.ValidationError('invalid bundle', invalidValues);
+    }
+}
+function validateBundleBase(b) {
+    const invalidValues = [];
+    // Media type validation
+    if (b.mediaType === undefined ||
+        (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) &&
+            !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) {
+        invalidValues.push('mediaType');
+    }
+    // Content-related validation
+    if (b.content === undefined) {
+        invalidValues.push('content');
+    }
+    else {
+        switch (b.content.$case) {
+            case 'messageSignature':
+                if (b.content.messageSignature.messageDigest === undefined) {
+                    invalidValues.push('content.messageSignature.messageDigest');
+                }
+                else {
+                    if (b.content.messageSignature.messageDigest.digest.length === 0) {
+                        invalidValues.push('content.messageSignature.messageDigest.digest');
+                    }
+                }
+                if (b.content.messageSignature.signature.length === 0) {
+                    invalidValues.push('content.messageSignature.signature');
+                }
+                break;
+            case 'dsseEnvelope':
+                if (b.content.dsseEnvelope.payload.length === 0) {
+                    invalidValues.push('content.dsseEnvelope.payload');
+                }
+                if (b.content.dsseEnvelope.signatures.length !== 1) {
+                    invalidValues.push('content.dsseEnvelope.signatures');
+                }
+                else {
+                    if (b.content.dsseEnvelope.signatures[0].sig.length === 0) {
+                        invalidValues.push('content.dsseEnvelope.signatures[0].sig');
+                    }
+                }
+                break;
+        }
+    }
+    // Verification material-related validation
+    if (b.verificationMaterial === undefined) {
+        invalidValues.push('verificationMaterial');
+    }
+    else {
+        if (b.verificationMaterial.content === undefined) {
+            invalidValues.push('verificationMaterial.content');
+        }
+        else {
+            switch (b.verificationMaterial.content.$case) {
+                case 'x509CertificateChain':
+                    if (b.verificationMaterial.content.x509CertificateChain.certificates
+                        .length === 0) {
+                        invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates');
+                    }
+                    b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => {
+                        if (cert.rawBytes.length === 0) {
+                            invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`);
+                        }
+                    });
+                    break;
+                case 'certificate':
+                    if (b.verificationMaterial.content.certificate.rawBytes.length === 0) {
+                        invalidValues.push('verificationMaterial.content.certificate.rawBytes');
+                    }
+                    break;
+            }
+        }
+        if (b.verificationMaterial.tlogEntries === undefined) {
+            invalidValues.push('verificationMaterial.tlogEntries');
+        }
+        else {
+            if (b.verificationMaterial.tlogEntries.length > 0) {
+                b.verificationMaterial.tlogEntries.forEach((entry, i) => {
+                    if (entry.logId === undefined) {
+                        invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`);
+                    }
+                    if (entry.kindVersion === undefined) {
+                        invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`);
+                    }
+                });
+            }
+        }
+    }
+    return invalidValues;
+}
+// Necessary for V01 bundles
+function validateInclusionPromise(b) {
+    const invalidValues = [];
+    if (b.verificationMaterial &&
+        b.verificationMaterial.tlogEntries?.length > 0) {
+        b.verificationMaterial.tlogEntries.forEach((entry, i) => {
+            if (entry.inclusionPromise === undefined) {
+                invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`);
+            }
+        });
+    }
+    return invalidValues;
+}
+// Necessary for V02 and later bundles
+function validateInclusionProof(b) {
+    const invalidValues = [];
+    if (b.verificationMaterial &&
+        b.verificationMaterial.tlogEntries?.length > 0) {
+        b.verificationMaterial.tlogEntries.forEach((entry, i) => {
+            if (entry.inclusionProof === undefined) {
+                invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`);
+            }
+            else {
+                if (entry.inclusionProof.checkpoint === undefined) {
+                    invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`);
+                }
+            }
+        });
+    }
+    return invalidValues;
+}
+// Necessary for V03 and later bundles
+function validateNoCertificateChain(b) {
+    const invalidValues = [];
+    /* istanbul ignore next */
+    if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') {
+        invalidValues.push('verificationMaterial.content.$case');
+    }
+    return invalidValues;
+}
+
+
+/***/ }),
+
+/***/ 11121:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ASN1TypeError = exports.ASN1ParseError = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+class ASN1ParseError extends Error {
+}
+exports.ASN1ParseError = ASN1ParseError;
+class ASN1TypeError extends Error {
+}
+exports.ASN1TypeError = ASN1TypeError;
+
+
+/***/ }),
+
+/***/ 86027:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ASN1Obj = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+var obj_1 = __nccwpck_require__(50990);
+Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return obj_1.ASN1Obj; } }));
+
+
+/***/ }),
+
+/***/ 84243:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decodeLength = decodeLength;
+exports.encodeLength = encodeLength;
+const error_1 = __nccwpck_require__(11121);
+// Decodes the length of a DER-encoded ANS.1 element from the supplied stream.
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes
+function decodeLength(stream) {
+    const buf = stream.getUint8();
+    // If the most significant bit is UNSET the length is just the value of the
+    // byte.
+    if ((buf & 0x80) === 0x00) {
+        return buf;
+    }
+    // Otherwise, the lower 7 bits of the first byte indicate the number of bytes
+    // that follow to encode the length.
+    const byteCount = buf & 0x7f;
+    // Ensure the encoded length can safely fit in a JS number.
+    if (byteCount > 6) {
+        throw new error_1.ASN1ParseError('length exceeds 6 byte limit');
+    }
+    // Iterate over the bytes that encode the length.
+    let len = 0;
+    for (let i = 0; i < byteCount; i++) {
+        len = len * 256 + stream.getUint8();
+    }
+    // This is a valid ASN.1 length encoding, but we don't support it.
+    if (len === 0) {
+        throw new error_1.ASN1ParseError('indefinite length encoding not supported');
+    }
+    return len;
+}
+// Translates the supplied value to a DER-encoded length.
+function encodeLength(len) {
+    if (len < 128) {
+        return Buffer.from([len]);
+    }
+    // Bitwise operations on large numbers are not supported in JS, so we need to
+    // use BigInts.
+    let val = BigInt(len);
+    const bytes = [];
+    while (val > 0n) {
+        bytes.unshift(Number(val & 255n));
+        val = val >> 8n;
+    }
+    return Buffer.from([0x80 | bytes.length, ...bytes]);
+}
+
+
+/***/ }),
+
+/***/ 50990:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ASN1Obj = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const stream_1 = __nccwpck_require__(1673);
+const error_1 = __nccwpck_require__(11121);
+const length_1 = __nccwpck_require__(84243);
+const parse_1 = __nccwpck_require__(81044);
+const tag_1 = __nccwpck_require__(59343);
+class ASN1Obj {
+    constructor(tag, value, subs) {
+        this.tag = tag;
+        this.value = value;
+        this.subs = subs;
+    }
+    // Constructs an ASN.1 object from a Buffer of DER-encoded bytes.
+    static parseBuffer(buf) {
+        return parseStream(new stream_1.ByteStream(buf));
+    }
+    toDER() {
+        const valueStream = new stream_1.ByteStream();
+        if (this.subs.length > 0) {
+            for (const sub of this.subs) {
+                valueStream.appendView(sub.toDER());
+            }
+        }
+        else {
+            valueStream.appendView(this.value);
+        }
+        const value = valueStream.buffer;
+        // Concat tag/length/value
+        const obj = new stream_1.ByteStream();
+        obj.appendChar(this.tag.toDER());
+        obj.appendView((0, length_1.encodeLength)(value.length));
+        obj.appendView(value);
+        return obj.buffer;
+    }
+    /////////////////////////////////////////////////////////////////////////////
+    // Convenience methods for parsing ASN.1 primitives into JS types
+    // Returns the ASN.1 object's value as a boolean. Throws an error if the
+    // object is not a boolean.
+    toBoolean() {
+        if (!this.tag.isBoolean()) {
+            throw new error_1.ASN1TypeError('not a boolean');
+        }
+        return (0, parse_1.parseBoolean)(this.value);
+    }
+    // Returns the ASN.1 object's value as a BigInt. Throws an error if the
+    // object is not an integer.
+    toInteger() {
+        if (!this.tag.isInteger()) {
+            throw new error_1.ASN1TypeError('not an integer');
+        }
+        return (0, parse_1.parseInteger)(this.value);
+    }
+    // Returns the ASN.1 object's value as an OID string. Throws an error if the
+    // object is not an OID.
+    toOID() {
+        if (!this.tag.isOID()) {
+            throw new error_1.ASN1TypeError('not an OID');
+        }
+        return (0, parse_1.parseOID)(this.value);
+    }
+    // Returns the ASN.1 object's value as a Date. Throws an error if the object
+    // is not either a UTCTime or a GeneralizedTime.
+    toDate() {
+        switch (true) {
+            case this.tag.isUTCTime():
+                return (0, parse_1.parseTime)(this.value, true);
+            case this.tag.isGeneralizedTime():
+                return (0, parse_1.parseTime)(this.value, false);
+            default:
+                throw new error_1.ASN1TypeError('not a date');
+        }
+    }
+    // Returns the ASN.1 object's value as a number[] where each number is the
+    // value of a bit in the bit string. Throws an error if the object is not a
+    // bit string.
+    toBitString() {
+        if (!this.tag.isBitString()) {
+            throw new error_1.ASN1TypeError('not a bit string');
+        }
+        return (0, parse_1.parseBitString)(this.value);
+    }
+}
+exports.ASN1Obj = ASN1Obj;
+/////////////////////////////////////////////////////////////////////////////
+// Internal stream parsing functions
+function parseStream(stream) {
+    // Parse tag, length, and value from stream
+    const tag = new tag_1.ASN1Tag(stream.getUint8());
+    const len = (0, length_1.decodeLength)(stream);
+    const value = stream.slice(stream.position, len);
+    const start = stream.position;
+    let subs = [];
+    // If the object is constructed, parse its children. Sometimes, children
+    // are embedded in OCTESTRING objects, so we need to check those
+    // for children as well.
+    if (tag.constructed) {
+        subs = collectSubs(stream, len);
+    }
+    else if (tag.isOctetString()) {
+        // Attempt to parse children of OCTETSTRING objects. If anything fails,
+        // assume the object is not constructed and treat as primitive.
+        try {
+            subs = collectSubs(stream, len);
+        }
+        catch (e) {
+            // Fail silently and treat as primitive
+        }
+    }
+    // If there are no children, move stream cursor to the end of the object
+    if (subs.length === 0) {
+        stream.seek(start + len);
+    }
+    return new ASN1Obj(tag, value, subs);
+}
+function collectSubs(stream, len) {
+    // Calculate end of object content
+    const end = stream.position + len;
+    // Make sure there are enough bytes left in the stream. This should never
+    // happen, cause it'll get caught when the stream is sliced in parseStream.
+    // Leaving as an extra check just in case.
+    /* istanbul ignore if */
+    if (end > stream.length) {
+        throw new error_1.ASN1ParseError('invalid length');
+    }
+    // Parse all children
+    const subs = [];
+    while (stream.position < end) {
+        subs.push(parseStream(stream));
+    }
+    // When we're done parsing children, we should be at the end of the object
+    if (stream.position !== end) {
+        throw new error_1.ASN1ParseError('invalid length');
+    }
+    return subs;
+}
+
+
+/***/ }),
+
+/***/ 81044:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseInteger = parseInteger;
+exports.parseStringASCII = parseStringASCII;
+exports.parseTime = parseTime;
+exports.parseOID = parseOID;
+exports.parseBoolean = parseBoolean;
+exports.parseBitString = parseBitString;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/;
+const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/;
+// Parse a BigInt from the DER-encoded buffer
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer
+function parseInteger(buf) {
+    let pos = 0;
+    const end = buf.length;
+    let val = buf[pos];
+    const neg = val > 0x7f;
+    // Consume any padding bytes
+    const pad = neg ? 0xff : 0x00;
+    while (val == pad && ++pos < end) {
+        val = buf[pos];
+    }
+    // Calculate remaining bytes to read
+    const len = end - pos;
+    if (len === 0)
+        return BigInt(neg ? -1 : 0);
+    // Handle two's complement for negative numbers
+    val = neg ? val - 256 : val;
+    // Parse remaining bytes
+    let n = BigInt(val);
+    for (let i = pos + 1; i < end; ++i) {
+        n = n * BigInt(256) + BigInt(buf[i]);
+    }
+    return n;
+}
+// Parse an ASCII string from the DER-encoded buffer
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean
+function parseStringASCII(buf) {
+    return buf.toString('ascii');
+}
+// Parse a Date from the DER-encoded buffer
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1
+function parseTime(buf, shortYear) {
+    const timeStr = parseStringASCII(buf);
+    // Parse the time string into matches - captured groups start at index 1
+    const m = shortYear
+        ? RE_TIME_SHORT_YEAR.exec(timeStr)
+        : RE_TIME_LONG_YEAR.exec(timeStr);
+    if (!m) {
+        throw new Error('invalid time');
+    }
+    // Translate dates with a 2-digit year to 4 digits per the spec
+    if (shortYear) {
+        let year = Number(m[1]);
+        year += year >= 50 ? 1900 : 2000;
+        m[1] = year.toString();
+    }
+    // Translate to ISO8601 format and parse
+    return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`);
+}
+// Parse an OID from the DER-encoded buffer
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier
+function parseOID(buf) {
+    let pos = 0;
+    const end = buf.length;
+    // Consume first byte which encodes the first two OID components
+    let n = buf[pos++];
+    const first = Math.floor(n / 40);
+    const second = n % 40;
+    let oid = `${first}.${second}`;
+    // Consume remaining bytes
+    let val = 0;
+    for (; pos < end; ++pos) {
+        n = buf[pos];
+        val = (val << 7) + (n & 0x7f);
+        // If the left-most bit is NOT set, then this is the last byte in the
+        // sequence and we can add the value to the OID and reset the accumulator
+        if ((n & 0x80) === 0) {
+            oid += `.${val}`;
+            val = 0;
+        }
+    }
+    return oid;
+}
+// Parse a boolean from the DER-encoded buffer
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean
+function parseBoolean(buf) {
+    return buf[0] !== 0;
+}
+// Parse a bit string from the DER-encoded buffer
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string
+function parseBitString(buf) {
+    // First byte tell us how many unused bits are in the last byte
+    const unused = buf[0];
+    const start = 1;
+    const end = buf.length;
+    const bits = [];
+    for (let i = start; i < end; ++i) {
+        const byte = buf[i];
+        // The skip value is only used for the last byte
+        const skip = i === end - 1 ? unused : 0;
+        // Iterate over each bit in the byte (most significant first)
+        for (let j = 7; j >= skip; --j) {
+            // Read the bit and add it to the bit string
+            bits.push((byte >> j) & 0x01);
+        }
+    }
+    return bits;
+}
+
+
+/***/ }),
+
+/***/ 59343:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ASN1Tag = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const error_1 = __nccwpck_require__(11121);
+const UNIVERSAL_TAG = {
+    BOOLEAN: 0x01,
+    INTEGER: 0x02,
+    BIT_STRING: 0x03,
+    OCTET_STRING: 0x04,
+    OBJECT_IDENTIFIER: 0x06,
+    SEQUENCE: 0x10,
+    SET: 0x11,
+    PRINTABLE_STRING: 0x13,
+    UTC_TIME: 0x17,
+    GENERALIZED_TIME: 0x18,
+};
+const TAG_CLASS = {
+    UNIVERSAL: 0x00,
+    APPLICATION: 0x01,
+    CONTEXT_SPECIFIC: 0x02,
+    PRIVATE: 0x03,
+};
+// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes
+class ASN1Tag {
+    constructor(enc) {
+        // Bits 0 through 4 are the tag number
+        this.number = enc & 0x1f;
+        // Bit 5 is the constructed bit
+        this.constructed = (enc & 0x20) === 0x20;
+        // Bit 6 & 7 are the class
+        this.class = enc >> 6;
+        if (this.number === 0x1f) {
+            throw new error_1.ASN1ParseError('long form tags not supported');
+        }
+        if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) {
+            throw new error_1.ASN1ParseError('unsupported tag 0x00');
+        }
+    }
+    isUniversal() {
+        return this.class === TAG_CLASS.UNIVERSAL;
+    }
+    isContextSpecific(num) {
+        const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC;
+        return num !== undefined ? res && this.number === num : res;
+    }
+    isBoolean() {
+        return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN;
+    }
+    isInteger() {
+        return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER;
+    }
+    isBitString() {
+        return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING;
+    }
+    isOctetString() {
+        return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING;
+    }
+    isOID() {
+        return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER);
+    }
+    isUTCTime() {
+        return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME;
+    }
+    isGeneralizedTime() {
+        return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME;
+    }
+    toDER() {
+        return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6);
+    }
+}
+exports.ASN1Tag = ASN1Tag;
+
+
+/***/ }),
+
+/***/ 69368:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPublicKey = createPublicKey;
+exports.digest = digest;
+exports.verify = verify;
+exports.bufferEqual = bufferEqual;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const crypto_1 = __importDefault(__nccwpck_require__(76982));
+function createPublicKey(key, type = 'spki') {
+    if (typeof key === 'string') {
+        return crypto_1.default.createPublicKey(key);
+    }
+    else {
+        return crypto_1.default.createPublicKey({ key, format: 'der', type: type });
+    }
+}
+function digest(algorithm, ...data) {
+    const hash = crypto_1.default.createHash(algorithm);
+    for (const d of data) {
+        hash.update(d);
+    }
+    return hash.digest();
+}
+function verify(data, key, signature, algorithm) {
+    // The try/catch is to work around an issue in Node 14.x where verify throws
+    // an error in some scenarios if the signature is invalid.
+    try {
+        return crypto_1.default.verify(algorithm, data, key, signature);
+    }
+    catch (e) {
+        /* istanbul ignore next */
+        return false;
+    }
+}
+function bufferEqual(a, b) {
+    try {
+        return crypto_1.default.timingSafeEqual(a, b);
+    }
+    catch {
+        /* istanbul ignore next */
+        return false;
+    }
+}
+
+
+/***/ }),
+
+/***/ 49032:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.preAuthEncoding = preAuthEncoding;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const PAE_PREFIX = 'DSSEv1';
+// DSSE Pre-Authentication Encoding
+function preAuthEncoding(payloadType, payload) {
+    const prefix = [
+        PAE_PREFIX,
+        payloadType.length,
+        payloadType,
+        payload.length,
+        '',
+    ].join(' ');
+    return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]);
+}
+
+
+/***/ }),
+
+/***/ 52788:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.base64Encode = base64Encode;
+exports.base64Decode = base64Decode;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const BASE64_ENCODING = 'base64';
+const UTF8_ENCODING = 'utf-8';
+function base64Encode(str) {
+    return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING);
+}
+function base64Decode(str) {
+    return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING);
+}
+
+
+/***/ }),
+
+/***/ 83917:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+var asn1_1 = __nccwpck_require__(86027);
+Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return asn1_1.ASN1Obj; } }));
+exports.crypto = __importStar(__nccwpck_require__(69368));
+exports.dsse = __importStar(__nccwpck_require__(49032));
+exports.encoding = __importStar(__nccwpck_require__(52788));
+exports.json = __importStar(__nccwpck_require__(13327));
+exports.pem = __importStar(__nccwpck_require__(1055));
+var rfc3161_1 = __nccwpck_require__(20994);
+Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } }));
+var stream_1 = __nccwpck_require__(1673);
+Object.defineProperty(exports, "ByteStream", ({ enumerable: true, get: function () { return stream_1.ByteStream; } }));
+var x509_1 = __nccwpck_require__(49358);
+Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } }));
+Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return x509_1.X509Certificate; } }));
+Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return x509_1.X509SCTExtension; } }));
+
+
+/***/ }),
+
+/***/ 13327:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.canonicalize = canonicalize;
+// JSON canonicalization per https://github.com/cyberphone/json-canonicalization
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function canonicalize(object) {
+    let buffer = '';
+    if (object === null || typeof object !== 'object' || object.toJSON != null) {
+        // Primitives or toJSONable objects
+        buffer += JSON.stringify(object);
+    }
+    else if (Array.isArray(object)) {
+        // Array - maintain element order
+        buffer += '[';
+        let first = true;
+        object.forEach((element) => {
+            if (!first) {
+                buffer += ',';
+            }
+            first = false;
+            // recursive call
+            buffer += canonicalize(element);
+        });
+        buffer += ']';
+    }
+    else {
+        // Object - Sort properties before serializing
+        buffer += '{';
+        let first = true;
+        Object.keys(object)
+            .sort()
+            .forEach((property) => {
+            if (!first) {
+                buffer += ',';
+            }
+            first = false;
+            buffer += JSON.stringify(property);
+            buffer += ':';
+            // recursive call
+            buffer += canonicalize(object[property]);
+        });
+        buffer += '}';
+    }
+    return buffer;
+}
+
+
+/***/ }),
+
+/***/ 91817:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0;
+exports.ECDSA_SIGNATURE_ALGOS = {
+    '1.2.840.10045.4.3.1': 'sha224',
+    '1.2.840.10045.4.3.2': 'sha256',
+    '1.2.840.10045.4.3.3': 'sha384',
+    '1.2.840.10045.4.3.4': 'sha512',
+};
+exports.SHA2_HASH_ALGOS = {
+    '2.16.840.1.101.3.4.2.1': 'sha256',
+    '2.16.840.1.101.3.4.2.2': 'sha384',
+    '2.16.840.1.101.3.4.2.3': 'sha512',
+};
+
+
+/***/ }),
+
+/***/ 1055:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toDER = toDER;
+exports.fromDER = fromDER;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const PEM_HEADER = /-----BEGIN (.*)-----/;
+const PEM_FOOTER = /-----END (.*)-----/;
+function toDER(certificate) {
+    let der = '';
+    certificate.split('\n').forEach((line) => {
+        if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) {
+            return;
+        }
+        der += line;
+    });
+    return Buffer.from(der, 'base64');
+}
+// Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM
+// encoding dictates that each certificate should have a trailing newline after
+// the footer.
+function fromDER(certificate, type = 'CERTIFICATE') {
+    // Base64-encode the certificate.
+    const der = certificate.toString('base64');
+    // Split the certificate into lines of 64 characters.
+    const lines = der.match(/.{1,64}/g) || '';
+    return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`]
+        .join('\n')
+        .concat('\n');
+}
+
+
+/***/ }),
+
+/***/ 97512:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RFC3161TimestampVerificationError = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+class RFC3161TimestampVerificationError extends Error {
+}
+exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError;
+
+
+/***/ }),
+
+/***/ 20994:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RFC3161Timestamp = void 0;
+var timestamp_1 = __nccwpck_require__(92714);
+Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } }));
+
+
+/***/ }),
+
+/***/ 92714:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RFC3161Timestamp = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
 
-// pkg/dist-src/endpoints-to-methods.js
-var endpointMethodsMap = /* @__PURE__ */ new Map();
-for (const [scope, endpoints] of Object.entries(endpoints_default)) {
-  for (const [methodName, endpoint] of Object.entries(endpoints)) {
-    const [route, defaults, decorations] = endpoint;
-    const [method, url] = route.split(/ /);
-    const endpointDefaults = Object.assign(
-      {
-        method,
-        url
-      },
-      defaults
-    );
-    if (!endpointMethodsMap.has(scope)) {
-      endpointMethodsMap.set(scope, /* @__PURE__ */ new Map());
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const asn1_1 = __nccwpck_require__(86027);
+const crypto = __importStar(__nccwpck_require__(69368));
+const oid_1 = __nccwpck_require__(91817);
+const error_1 = __nccwpck_require__(97512);
+const tstinfo_1 = __nccwpck_require__(62925);
+const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2';
+const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4';
+const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4';
+class RFC3161Timestamp {
+    constructor(asn1) {
+        this.root = asn1;
     }
-    endpointMethodsMap.get(scope).set(methodName, {
-      scope,
-      methodName,
-      endpointDefaults,
-      decorations
-    });
-  }
-}
-var handler = {
-  has({ scope }, methodName) {
-    return endpointMethodsMap.get(scope).has(methodName);
-  },
-  getOwnPropertyDescriptor(target, methodName) {
-    return {
-      value: this.get(target, methodName),
-      // ensures method is in the cache
-      configurable: true,
-      writable: true,
-      enumerable: true
-    };
-  },
-  defineProperty(target, methodName, descriptor) {
-    Object.defineProperty(target.cache, methodName, descriptor);
-    return true;
-  },
-  deleteProperty(target, methodName) {
-    delete target.cache[methodName];
-    return true;
-  },
-  ownKeys({ scope }) {
-    return [...endpointMethodsMap.get(scope).keys()];
-  },
-  set(target, methodName, value) {
-    return target.cache[methodName] = value;
-  },
-  get({ octokit, scope, cache }, methodName) {
-    if (cache[methodName]) {
-      return cache[methodName];
+    static parse(der) {
+        const asn1 = asn1_1.ASN1Obj.parseBuffer(der);
+        return new RFC3161Timestamp(asn1);
     }
-    const method = endpointMethodsMap.get(scope).get(methodName);
-    if (!method) {
-      return void 0;
+    get status() {
+        return this.pkiStatusInfoObj.subs[0].toInteger();
     }
-    const { endpointDefaults, decorations } = method;
-    if (decorations) {
-      cache[methodName] = decorate(
-        octokit,
-        scope,
-        methodName,
-        endpointDefaults,
-        decorations
-      );
-    } else {
-      cache[methodName] = octokit.request.defaults(endpointDefaults);
+    get contentType() {
+        return this.contentTypeObj.toOID();
     }
-    return cache[methodName];
-  }
+    get eContentType() {
+        return this.eContentTypeObj.toOID();
+    }
+    get signingTime() {
+        return this.tstInfo.genTime;
+    }
+    get signerIssuer() {
+        return this.signerSidObj.subs[0].value;
+    }
+    get signerSerialNumber() {
+        return this.signerSidObj.subs[1].value;
+    }
+    get signerDigestAlgorithm() {
+        const oid = this.signerDigestAlgorithmObj.subs[0].toOID();
+        return oid_1.SHA2_HASH_ALGOS[oid];
+    }
+    get signatureAlgorithm() {
+        const oid = this.signatureAlgorithmObj.subs[0].toOID();
+        return oid_1.ECDSA_SIGNATURE_ALGOS[oid];
+    }
+    get signatureValue() {
+        return this.signatureValueObj.value;
+    }
+    get tstInfo() {
+        // Need to unpack tstInfo from an OCTET STRING
+        return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]);
+    }
+    verify(data, publicKey) {
+        if (!this.timeStampTokenObj) {
+            throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing');
+        }
+        // Check for expected ContentInfo content type
+        if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) {
+            throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`);
+        }
+        // Check for expected encapsulated content type
+        if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) {
+            throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`);
+        }
+        // Check that the tstInfo references the correct artifact
+        this.tstInfo.verify(data);
+        // Check that the signed message digest matches the tstInfo
+        this.verifyMessageDigest();
+        // Check that the signature is valid for the signed attributes
+        this.verifySignature(publicKey);
+    }
+    verifyMessageDigest() {
+        // Check that the tstInfo matches the signed data
+        const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw);
+        const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value;
+        if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) {
+            throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo');
+        }
+    }
+    verifySignature(key) {
+        // Encode the signed attributes for verification
+        const signedAttrs = this.signedAttrsObj.toDER();
+        signedAttrs[0] = 0x31; // Change context-specific tag to SET
+        // Check that the signature is valid for the signed attributes
+        const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm);
+        if (!verified) {
+            throw new error_1.RFC3161TimestampVerificationError('signature verification failed');
+        }
+    }
+    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
+    get pkiStatusInfoObj() {
+        // pkiStatusInfo is the first element of the timestamp response sequence
+        return this.root.subs[0];
+    }
+    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
+    get timeStampTokenObj() {
+        // timeStampToken is the first element of the timestamp response sequence
+        return this.root.subs[1];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-3
+    get contentTypeObj() {
+        return this.timeStampTokenObj.subs[0];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5652#section-3
+    get signedDataObj() {
+        const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00));
+        return obj.subs[0];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1
+    get encapContentInfoObj() {
+        return this.signedDataObj.subs[2];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1
+    get signerInfosObj() {
+        // SignerInfos is the last element of the signed data sequence
+        const sd = this.signedDataObj;
+        return sd.subs[sd.subs.length - 1];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5652#section-5.1
+    get signerInfoObj() {
+        // Only supporting one signer
+        return this.signerInfosObj.subs[0];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2
+    get eContentTypeObj() {
+        return this.encapContentInfoObj.subs[0];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2
+    get eContentObj() {
+        return this.encapContentInfoObj.subs[1];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
+    get signedAttrsObj() {
+        const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00));
+        return signedAttrs;
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
+    get messageDigestAttributeObj() {
+        const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() &&
+            sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY);
+        return messageDigest;
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
+    get signerSidObj() {
+        return this.signerInfoObj.subs[1];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
+    get signerDigestAlgorithmObj() {
+        // Signature is the 2nd element of the signerInfoObj object
+        return this.signerInfoObj.subs[2];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
+    get signatureAlgorithmObj() {
+        // Signature is the 4th element of the signerInfoObj object
+        return this.signerInfoObj.subs[4];
+    }
+    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
+    get signatureValueObj() {
+        // Signature is the 6th element of the signerInfoObj object
+        return this.signerInfoObj.subs[5];
+    }
+}
+exports.RFC3161Timestamp = RFC3161Timestamp;
+
+
+/***/ }),
+
+/***/ 62925:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
 };
-function endpointsToMethods(octokit) {
-  const newMethods = {};
-  for (const scope of endpointMethodsMap.keys()) {
-    newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);
-  }
-  return newMethods;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TSTInfo = void 0;
+const crypto = __importStar(__nccwpck_require__(69368));
+const oid_1 = __nccwpck_require__(91817);
+const error_1 = __nccwpck_require__(97512);
+class TSTInfo {
+    constructor(asn1) {
+        this.root = asn1;
+    }
+    get version() {
+        return this.root.subs[0].toInteger();
+    }
+    get genTime() {
+        return this.root.subs[4].toDate();
+    }
+    get messageImprintHashAlgorithm() {
+        const oid = this.messageImprintObj.subs[0].subs[0].toOID();
+        return oid_1.SHA2_HASH_ALGOS[oid];
+    }
+    get messageImprintHashedMessage() {
+        return this.messageImprintObj.subs[1].value;
+    }
+    get raw() {
+        return this.root.toDER();
+    }
+    verify(data) {
+        const digest = crypto.digest(this.messageImprintHashAlgorithm, data);
+        if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) {
+            throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact');
+        }
+    }
+    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
+    get messageImprintObj() {
+        return this.root.subs[2];
+    }
 }
-function decorate(octokit, scope, methodName, defaults, decorations) {
-  const requestWithDefaults = octokit.request.defaults(defaults);
-  function withDecorations(...args) {
-    let options = requestWithDefaults.endpoint.merge(...args);
-    if (decorations.mapToData) {
-      options = Object.assign({}, options, {
-        data: options[decorations.mapToData],
-        [decorations.mapToData]: void 0
-      });
-      return requestWithDefaults(options);
+exports.TSTInfo = TSTInfo;
+
+
+/***/ }),
+
+/***/ 1673:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ByteStream = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+class StreamError extends Error {
+}
+class ByteStream {
+    constructor(buffer) {
+        this.start = 0;
+        if (buffer) {
+            this.buf = buffer;
+            this.view = Buffer.from(buffer);
+        }
+        else {
+            this.buf = new ArrayBuffer(0);
+            this.view = Buffer.from(this.buf);
+        }
+    }
+    get buffer() {
+        return this.view.subarray(0, this.start);
+    }
+    get length() {
+        return this.view.byteLength;
+    }
+    get position() {
+        return this.start;
+    }
+    seek(position) {
+        this.start = position;
+    }
+    // Returns a Buffer containing the specified number of bytes starting at the
+    // given start position.
+    slice(start, len) {
+        const end = start + len;
+        if (end > this.length) {
+            throw new StreamError('request past end of buffer');
+        }
+        return this.view.subarray(start, end);
+    }
+    appendChar(char) {
+        this.ensureCapacity(1);
+        this.view[this.start] = char;
+        this.start += 1;
+    }
+    appendUint16(num) {
+        this.ensureCapacity(2);
+        const value = new Uint16Array([num]);
+        const view = new Uint8Array(value.buffer);
+        this.view[this.start] = view[1];
+        this.view[this.start + 1] = view[0];
+        this.start += 2;
+    }
+    appendUint24(num) {
+        this.ensureCapacity(3);
+        const value = new Uint32Array([num]);
+        const view = new Uint8Array(value.buffer);
+        this.view[this.start] = view[2];
+        this.view[this.start + 1] = view[1];
+        this.view[this.start + 2] = view[0];
+        this.start += 3;
+    }
+    appendView(view) {
+        this.ensureCapacity(view.length);
+        this.view.set(view, this.start);
+        this.start += view.length;
     }
-    if (decorations.renamed) {
-      const [newScope, newMethodName] = decorations.renamed;
-      octokit.log.warn(
-        `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`
-      );
+    getBlock(size) {
+        if (size <= 0) {
+            return Buffer.alloc(0);
+        }
+        if (this.start + size > this.view.length) {
+            throw new Error('request past end of buffer');
+        }
+        const result = this.view.subarray(this.start, this.start + size);
+        this.start += size;
+        return result;
     }
-    if (decorations.deprecated) {
-      octokit.log.warn(decorations.deprecated);
+    getUint8() {
+        return this.getBlock(1)[0];
     }
-    if (decorations.renamedParameters) {
-      const options2 = requestWithDefaults.endpoint.merge(...args);
-      for (const [name, alias] of Object.entries(
-        decorations.renamedParameters
-      )) {
-        if (name in options2) {
-          octokit.log.warn(
-            `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`
-          );
-          if (!(alias in options2)) {
-            options2[alias] = options2[name];
-          }
-          delete options2[name];
+    getUint16() {
+        const block = this.getBlock(2);
+        return (block[0] << 8) | block[1];
+    }
+    ensureCapacity(size) {
+        if (this.start + size > this.view.byteLength) {
+            const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0);
+            this.realloc(this.view.byteLength + blockSize);
         }
-      }
-      return requestWithDefaults(options2);
     }
-    return requestWithDefaults(...args);
-  }
-  return Object.assign(withDecorations, requestWithDefaults);
-}
-
-// pkg/dist-src/index.js
-function restEndpointMethods(octokit) {
-  const api = endpointsToMethods(octokit);
-  return {
-    rest: api
-  };
-}
-restEndpointMethods.VERSION = VERSION;
-function legacyRestEndpointMethods(octokit) {
-  const api = endpointsToMethods(octokit);
-  return {
-    ...api,
-    rest: api
-  };
+    realloc(size) {
+        const newArray = new ArrayBuffer(size);
+        const newView = Buffer.from(newArray);
+        // Copy the old buffer into the new one
+        newView.set(this.view);
+        this.buf = newArray;
+        this.view = newView;
+    }
 }
-legacyRestEndpointMethods.VERSION = VERSION;
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+exports.ByteStream = ByteStream;
+ByteStream.BLOCK_SIZE = 1024;
 
 
 /***/ }),
 
-/***/ 33450:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 83566:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
 };
-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: true }) : target,
-  mod
-));
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
 
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  VERSION: () => VERSION,
-  retry: () => retry
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_core = __nccwpck_require__(61897);
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
 
-// pkg/dist-src/error-request.js
-async function errorRequest(state, octokit, error, options) {
-  if (!error.request || !error.request.request) {
-    throw error;
-  }
-  if (error.status >= 400 && !state.doNotRetry.includes(error.status)) {
-    const retries = options.request.retries != null ? options.request.retries : state.retries;
-    const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2);
-    throw octokit.retry.retryRequest(error, retries, retryAfter);
-  }
-  throw error;
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const asn1_1 = __nccwpck_require__(86027);
+const crypto = __importStar(__nccwpck_require__(69368));
+const oid_1 = __nccwpck_require__(91817);
+const pem = __importStar(__nccwpck_require__(1055));
+const ext_1 = __nccwpck_require__(96389);
+const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14';
+const EXTENSION_OID_KEY_USAGE = '2.5.29.15';
+const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17';
+const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19';
+const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35';
+exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2';
+class X509Certificate {
+    constructor(asn1) {
+        this.root = asn1;
+    }
+    static parse(cert) {
+        const der = typeof cert === 'string' ? pem.toDER(cert) : cert;
+        const asn1 = asn1_1.ASN1Obj.parseBuffer(der);
+        return new X509Certificate(asn1);
+    }
+    get tbsCertificate() {
+        return this.tbsCertificateObj;
+    }
+    get version() {
+        // version number is the first element of the version context specific tag
+        const ver = this.versionObj.subs[0].toInteger();
+        return `v${(ver + BigInt(1)).toString()}`;
+    }
+    get serialNumber() {
+        return this.serialNumberObj.value;
+    }
+    get notBefore() {
+        // notBefore is the first element of the validity sequence
+        return this.validityObj.subs[0].toDate();
+    }
+    get notAfter() {
+        // notAfter is the second element of the validity sequence
+        return this.validityObj.subs[1].toDate();
+    }
+    get issuer() {
+        return this.issuerObj.value;
+    }
+    get subject() {
+        return this.subjectObj.value;
+    }
+    get publicKey() {
+        return this.subjectPublicKeyInfoObj.toDER();
+    }
+    get signatureAlgorithm() {
+        const oid = this.signatureAlgorithmObj.subs[0].toOID();
+        return oid_1.ECDSA_SIGNATURE_ALGOS[oid];
+    }
+    get signatureValue() {
+        // Signature value is a bit string, so we need to skip the first byte
+        return this.signatureValueObj.value.subarray(1);
+    }
+    get subjectAltName() {
+        const ext = this.extSubjectAltName;
+        return ext?.uri || /* istanbul ignore next */ ext?.rfc822Name;
+    }
+    get extensions() {
+        // The extension list is the first (and only) element of the extensions
+        // context specific tag
+        /* istanbul ignore next */
+        const extSeq = this.extensionsObj?.subs[0];
+        /* istanbul ignore next */
+        return extSeq?.subs || [];
+    }
+    get extKeyUsage() {
+        const ext = this.findExtension(EXTENSION_OID_KEY_USAGE);
+        return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined;
+    }
+    get extBasicConstraints() {
+        const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS);
+        return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined;
+    }
+    get extSubjectAltName() {
+        const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME);
+        return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined;
+    }
+    get extAuthorityKeyID() {
+        const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID);
+        return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined;
+    }
+    get extSubjectKeyID() {
+        const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID);
+        return ext
+            ? new ext_1.X509SubjectKeyIDExtension(ext)
+            : /* istanbul ignore next */ undefined;
+    }
+    get extSCT() {
+        const ext = this.findExtension(exports.EXTENSION_OID_SCT);
+        return ext ? new ext_1.X509SCTExtension(ext) : undefined;
+    }
+    get isCA() {
+        const ca = this.extBasicConstraints?.isCA || false;
+        // If the KeyUsage extension is present, keyCertSign must be set
+        if (this.extKeyUsage) {
+            return ca && this.extKeyUsage.keyCertSign;
+        }
+        // TODO: test coverage for this case
+        /* istanbul ignore next */
+        return ca;
+    }
+    extension(oid) {
+        const ext = this.findExtension(oid);
+        return ext ? new ext_1.X509Extension(ext) : undefined;
+    }
+    verify(issuerCertificate) {
+        // Use the issuer's public key if provided, otherwise use the subject's
+        const publicKey = issuerCertificate?.publicKey || this.publicKey;
+        const key = crypto.createPublicKey(publicKey);
+        return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm);
+    }
+    validForDate(date) {
+        return this.notBefore <= date && date <= this.notAfter;
+    }
+    equals(other) {
+        return this.root.toDER().equals(other.root.toDER());
+    }
+    // Creates a copy of the certificate with a new buffer
+    clone() {
+        const der = this.root.toDER();
+        const clone = Buffer.alloc(der.length);
+        der.copy(clone);
+        return X509Certificate.parse(clone);
+    }
+    findExtension(oid) {
+        // Find the extension with the given OID. The OID will always be the first
+        // element of the extension sequence
+        return this.extensions.find((ext) => ext.subs[0].toOID() === oid);
+    }
+    /////////////////////////////////////////////////////////////////////////////
+    // The following properties use the documented x509 structure to locate the
+    // desired ASN.1 object
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1
+    get tbsCertificateObj() {
+        // tbsCertificate is the first element of the certificate sequence
+        return this.root.subs[0];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2
+    get signatureAlgorithmObj() {
+        // signatureAlgorithm is the second element of the certificate sequence
+        return this.root.subs[1];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3
+    get signatureValueObj() {
+        // signatureValue is the third element of the certificate sequence
+        return this.root.subs[2];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1
+    get versionObj() {
+        // version is the first element of the tbsCertificate sequence
+        return this.tbsCertificateObj.subs[0];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2
+    get serialNumberObj() {
+        // serialNumber is the second element of the tbsCertificate sequence
+        return this.tbsCertificateObj.subs[1];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4
+    get issuerObj() {
+        // issuer is the fourth element of the tbsCertificate sequence
+        return this.tbsCertificateObj.subs[3];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5
+    get validityObj() {
+        // version is the fifth element of the tbsCertificate sequence
+        return this.tbsCertificateObj.subs[4];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6
+    get subjectObj() {
+        // subject is the sixth element of the tbsCertificate sequence
+        return this.tbsCertificateObj.subs[5];
+    }
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7
+    get subjectPublicKeyInfoObj() {
+        // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence
+        return this.tbsCertificateObj.subs[6];
+    }
+    // Extensions can't be located by index because their position varies. Instead,
+    // we need to find the extensions context specific tag
+    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9
+    get extensionsObj() {
+        return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03));
+    }
 }
+exports.X509Certificate = X509Certificate;
 
-// pkg/dist-src/wrap-request.js
-var import_light = __toESM(__nccwpck_require__(63251));
-var import_request_error = __nccwpck_require__(93708);
-async function wrapRequest(state, octokit, request, options) {
-  const limiter = new import_light.default();
-  limiter.on("failed", function(error, info) {
-    const maxRetries = ~~error.request.request.retries;
-    const after = ~~error.request.request.retryAfter;
-    options.request.retryCount = info.retryCount + 1;
-    if (maxRetries > info.retryCount) {
-      return after * state.retryAfterBaseValue;
+
+/***/ }),
+
+/***/ 96389:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0;
+const stream_1 = __nccwpck_require__(1673);
+const sct_1 = __nccwpck_require__(6144);
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.1
+class X509Extension {
+    constructor(asn1) {
+        this.root = asn1;
+    }
+    get oid() {
+        return this.root.subs[0].toOID();
+    }
+    get critical() {
+        // The critical field is optional and will be the second element of the
+        // extension sequence if present. Default to false if not present.
+        return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false;
+    }
+    get value() {
+        return this.extnValueObj.value;
+    }
+    get valueObj() {
+        return this.extnValueObj;
+    }
+    get extnValueObj() {
+        // The extnValue field will be the last element of the extension sequence
+        return this.root.subs[this.root.subs.length - 1];
     }
-  });
-  return limiter.schedule(
-    requestWithGraphqlErrorHandling.bind(null, state, octokit, request),
-    options
-  );
 }
-async function requestWithGraphqlErrorHandling(state, octokit, request, options) {
-  const response = await request(request, options);
-  if (response.data && response.data.errors && /Something went wrong while executing your query/.test(
-    response.data.errors[0].message
-  )) {
-    const error = new import_request_error.RequestError(response.data.errors[0].message, 500, {
-      request: options,
-      response
-    });
-    return errorRequest(state, octokit, error, options);
-  }
-  return response;
+exports.X509Extension = X509Extension;
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9
+class X509BasicConstraintsExtension extends X509Extension {
+    get isCA() {
+        return this.sequence.subs[0]?.toBoolean() ?? false;
+    }
+    get pathLenConstraint() {
+        return this.sequence.subs.length > 1
+            ? this.sequence.subs[1].toInteger()
+            : undefined;
+    }
+    // The extnValue field contains a single sequence wrapping the isCA and
+    // pathLenConstraint.
+    get sequence() {
+        return this.extnValueObj.subs[0];
+    }
 }
-
-// pkg/dist-src/index.js
-var VERSION = "6.0.1";
-function retry(octokit, octokitOptions) {
-  const state = Object.assign(
-    {
-      enabled: true,
-      retryAfterBaseValue: 1e3,
-      doNotRetry: [400, 401, 403, 404, 422, 451],
-      retries: 3
-    },
-    octokitOptions.retry
-  );
-  if (state.enabled) {
-    octokit.hook.error("request", errorRequest.bind(null, state, octokit));
-    octokit.hook.wrap("request", wrapRequest.bind(null, state, octokit));
-  }
-  return {
-    retry: {
-      retryRequest: (error, retries, retryAfter) => {
-        error.request.request = Object.assign({}, error.request.request, {
-          retries,
-          retryAfter
-        });
-        return error;
-      }
+exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension;
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3
+class X509KeyUsageExtension extends X509Extension {
+    get digitalSignature() {
+        return this.bitString[0] === 1;
+    }
+    get keyCertSign() {
+        return this.bitString[5] === 1;
+    }
+    get crlSign() {
+        return this.bitString[6] === 1;
+    }
+    // The extnValue field contains a single bit string which is a bit mask
+    // indicating which key usages are enabled.
+    get bitString() {
+        return this.extnValueObj.subs[0].toBitString();
+    }
+}
+exports.X509KeyUsageExtension = X509KeyUsageExtension;
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6
+class X509SubjectAlternativeNameExtension extends X509Extension {
+    get rfc822Name() {
+        return this.findGeneralName(0x01)?.value.toString('ascii');
+    }
+    get uri() {
+        return this.findGeneralName(0x06)?.value.toString('ascii');
+    }
+    // Retrieve the value of an otherName with the given OID.
+    otherName(oid) {
+        const otherName = this.findGeneralName(0x00);
+        if (otherName === undefined) {
+            return undefined;
+        }
+        // The otherName is a sequence containing an OID and a value.
+        // Need to check that the OID matches the one we're looking for.
+        const otherNameOID = otherName.subs[0].toOID();
+        if (otherNameOID !== oid) {
+            return undefined;
+        }
+        // The otherNameValue is a sequence containing the actual value.
+        const otherNameValue = otherName.subs[1];
+        return otherNameValue.subs[0].value.toString('ascii');
+    }
+    findGeneralName(tag) {
+        return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag));
+    }
+    // The extnValue field contains a sequence of GeneralNames.
+    get generalNames() {
+        return this.extnValueObj.subs[0].subs;
+    }
+}
+exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension;
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1
+class X509AuthorityKeyIDExtension extends X509Extension {
+    get keyIdentifier() {
+        return this.findSequenceMember(0x00)?.value;
+    }
+    findSequenceMember(tag) {
+        return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag));
+    }
+    // The extnValue field contains a single sequence wrapping the keyIdentifier
+    get sequence() {
+        return this.extnValueObj.subs[0];
     }
-  };
 }
-retry.VERSION = VERSION;
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension;
+// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2
+class X509SubjectKeyIDExtension extends X509Extension {
+    get keyIdentifier() {
+        return this.extnValueObj.subs[0].value;
+    }
+}
+exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension;
+// https://www.rfc-editor.org/rfc/rfc6962#section-3.3
+class X509SCTExtension extends X509Extension {
+    constructor(asn1) {
+        super(asn1);
+    }
+    get signedCertificateTimestamps() {
+        const buf = this.extnValueObj.subs[0].value;
+        const stream = new stream_1.ByteStream(buf);
+        // The overall list length is encoded in the first two bytes -- note this
+        // is the length of the list in bytes, NOT the number of SCTs in the list
+        const end = stream.getUint16() + 2;
+        const sctList = [];
+        while (stream.position < end) {
+            // Read the length of the next SCT
+            const sctLength = stream.getUint16();
+            // Slice out the bytes for the next SCT and parse it
+            const sct = stream.getBlock(sctLength);
+            sctList.push(sct_1.SignedCertificateTimestamp.parse(sct));
+        }
+        if (stream.position !== end) {
+            throw new Error('SCT list length does not match actual length');
+        }
+        return sctList;
+    }
+}
+exports.X509SCTExtension = X509SCTExtension;
 
 
 /***/ }),
 
-/***/ 93708:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 49358:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __create = Object.create;
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __getProtoOf = Object.getPrototypeOf;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__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: true }) : target,
-  mod
-));
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+/*
+Copyright 2023 The Sigstore Authors.
 
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  RequestError: () => RequestError
-});
-module.exports = __toCommonJS(dist_src_exports);
-var import_deprecation = __nccwpck_require__(14150);
-var import_once = __toESM(__nccwpck_require__(55560));
-var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation));
-var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation));
-var RequestError = class extends Error {
-  constructor(message, statusCode, options) {
-    super(message);
-    if (Error.captureStackTrace) {
-      Error.captureStackTrace(this, this.constructor);
-    }
-    this.name = "HttpError";
-    this.status = statusCode;
-    let headers;
-    if ("headers" in options && typeof options.headers !== "undefined") {
-      headers = options.headers;
-    }
-    if ("response" in options) {
-      this.response = options.response;
-      headers = options.response.headers;
-    }
-    const requestCopy = Object.assign({}, options.request);
-    if (options.request.headers.authorization) {
-      requestCopy.headers = Object.assign({}, options.request.headers, {
-        authorization: options.request.headers.authorization.replace(
-          /(? {
+/***/ 6144:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
-var __defProp = Object.defineProperty;
-var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
-var __getOwnPropNames = Object.getOwnPropertyNames;
-var __hasOwnProp = Object.prototype.hasOwnProperty;
-var __export = (target, all) => {
-  for (var name in all)
-    __defProp(target, name, { get: all[name], enumerable: true });
-};
-var __copyProps = (to, from, except, desc) => {
-  if (from && typeof from === "object" || typeof from === "function") {
-    for (let key of __getOwnPropNames(from))
-      if (!__hasOwnProp.call(to, key) && key !== except)
-        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
-  }
-  return to;
-};
-var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
-
-// pkg/dist-src/index.js
-var dist_src_exports = {};
-__export(dist_src_exports, {
-  request: () => request
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
 });
-module.exports = __toCommonJS(dist_src_exports);
-var import_endpoint = __nccwpck_require__(54471);
-var import_universal_user_agent = __nccwpck_require__(33843);
-
-// pkg/dist-src/version.js
-var VERSION = "8.2.0";
-
-// pkg/dist-src/is-plain-object.js
-function isPlainObject(value) {
-  if (typeof value !== "object" || value === null)
-    return false;
-  if (Object.prototype.toString.call(value) !== "[object Object]")
-    return false;
-  const proto = Object.getPrototypeOf(value);
-  if (proto === null)
-    return true;
-  const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor;
-  return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);
-}
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SignedCertificateTimestamp = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
 
-// pkg/dist-src/fetch-wrapper.js
-var import_request_error = __nccwpck_require__(93708);
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
 
-// pkg/dist-src/get-buffer-response.js
-function getBufferResponse(response) {
-  return response.arrayBuffer();
-}
+    http://www.apache.org/licenses/LICENSE-2.0
 
-// pkg/dist-src/fetch-wrapper.js
-function fetchWrapper(requestOptions) {
-  var _a, _b, _c;
-  const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console;
-  const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false;
-  if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) {
-    requestOptions.body = JSON.stringify(requestOptions.body);
-  }
-  let headers = {};
-  let status;
-  let url;
-  let { fetch } = globalThis;
-  if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) {
-    fetch = requestOptions.request.fetch;
-  }
-  if (!fetch) {
-    throw new Error(
-      "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing"
-    );
-  }
-  return fetch(requestOptions.url, {
-    method: requestOptions.method,
-    body: requestOptions.body,
-    headers: requestOptions.headers,
-    signal: (_c = requestOptions.request) == null ? void 0 : _c.signal,
-    // duplex must be set if request.body is ReadableStream or Async Iterables.
-    // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.
-    ...requestOptions.body && { duplex: "half" }
-  }).then(async (response) => {
-    url = response.url;
-    status = response.status;
-    for (const keyAndValue of response.headers) {
-      headers[keyAndValue[0]] = keyAndValue[1];
-    }
-    if ("deprecation" in headers) {
-      const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/);
-      const deprecationLink = matches && matches.pop();
-      log.warn(
-        `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`
-      );
-    }
-    if (status === 204 || status === 205) {
-      return;
-    }
-    if (requestOptions.method === "HEAD") {
-      if (status < 400) {
-        return;
-      }
-      throw new import_request_error.RequestError(response.statusText, status, {
-        response: {
-          url,
-          status,
-          headers,
-          data: void 0
-        },
-        request: requestOptions
-      });
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const crypto = __importStar(__nccwpck_require__(69368));
+const stream_1 = __nccwpck_require__(1673);
+class SignedCertificateTimestamp {
+    constructor(options) {
+        this.version = options.version;
+        this.logID = options.logID;
+        this.timestamp = options.timestamp;
+        this.extensions = options.extensions;
+        this.hashAlgorithm = options.hashAlgorithm;
+        this.signatureAlgorithm = options.signatureAlgorithm;
+        this.signature = options.signature;
     }
-    if (status === 304) {
-      throw new import_request_error.RequestError("Not modified", status, {
-        response: {
-          url,
-          status,
-          headers,
-          data: await getResponseData(response)
-        },
-        request: requestOptions
-      });
+    get datetime() {
+        return new Date(Number(this.timestamp.readBigInt64BE()));
     }
-    if (status >= 400) {
-      const data = await getResponseData(response);
-      const error = new import_request_error.RequestError(toErrorMessage(data), status, {
-        response: {
-          url,
-          status,
-          headers,
-          data
-        },
-        request: requestOptions
-      });
-      throw error;
+    // Returns the hash algorithm used to generate the SCT's signature.
+    // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1
+    get algorithm() {
+        switch (this.hashAlgorithm) {
+            /* istanbul ignore next */
+            case 0:
+                return 'none';
+            /* istanbul ignore next */
+            case 1:
+                return 'md5';
+            /* istanbul ignore next */
+            case 2:
+                return 'sha1';
+            /* istanbul ignore next */
+            case 3:
+                return 'sha224';
+            case 4:
+                return 'sha256';
+            /* istanbul ignore next */
+            case 5:
+                return 'sha384';
+            /* istanbul ignore next */
+            case 6:
+                return 'sha512';
+            /* istanbul ignore next */
+            default:
+                return 'unknown';
+        }
     }
-    return parseSuccessResponseBody ? await getResponseData(response) : response.body;
-  }).then((data) => {
-    return {
-      status,
-      url,
-      headers,
-      data
-    };
-  }).catch((error) => {
-    if (error instanceof import_request_error.RequestError)
-      throw error;
-    else if (error.name === "AbortError")
-      throw error;
-    let message = error.message;
-    if (error.name === "TypeError" && "cause" in error) {
-      if (error.cause instanceof Error) {
-        message = error.cause.message;
-      } else if (typeof error.cause === "string") {
-        message = error.cause;
-      }
+    verify(preCert, key) {
+        // Assemble the digitally-signed struct (the data over which the signature
+        // was generated).
+        // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
+        const stream = new stream_1.ByteStream();
+        stream.appendChar(this.version);
+        stream.appendChar(0x00); // SignatureType = certificate_timestamp(0)
+        stream.appendView(this.timestamp);
+        stream.appendUint16(0x01); // LogEntryType = precert_entry(1)
+        stream.appendView(preCert);
+        stream.appendUint16(this.extensions.byteLength);
+        /* istanbul ignore next - extensions are very uncommon */
+        if (this.extensions.byteLength > 0) {
+            stream.appendView(this.extensions);
+        }
+        return crypto.verify(stream.buffer, key, this.signature, this.algorithm);
     }
-    throw new import_request_error.RequestError(message, 500, {
-      request: requestOptions
-    });
-  });
-}
-async function getResponseData(response) {
-  const contentType = response.headers.get("content-type");
-  if (/application\/json/.test(contentType)) {
-    return response.json().catch(() => response.text()).catch(() => "");
-  }
-  if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
-    return response.text();
-  }
-  return getBufferResponse(response);
-}
-function toErrorMessage(data) {
-  if (typeof data === "string")
-    return data;
-  let suffix;
-  if ("documentation_url" in data) {
-    suffix = ` - ${data.documentation_url}`;
-  } else {
-    suffix = "";
-  }
-  if ("message" in data) {
-    if (Array.isArray(data.errors)) {
-      return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`;
+    // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using
+    // TLS encoding which means the fields and lengths of most fields are
+    // specified as part of the SCT and TLS specs.
+    // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
+    // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1
+    static parse(buf) {
+        const stream = new stream_1.ByteStream(buf);
+        // Version - enum { v1(0), (255) }
+        const version = stream.getUint8();
+        // Log ID  - struct { opaque key_id[32]; }
+        const logID = stream.getBlock(32);
+        // Timestamp - uint64
+        const timestamp = stream.getBlock(8);
+        // Extensions - opaque extensions<0..2^16-1>;
+        const extenstionLength = stream.getUint16();
+        const extensions = stream.getBlock(extenstionLength);
+        // Hash algo - enum { sha256(4), . . . (255) }
+        const hashAlgorithm = stream.getUint8();
+        // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
+        const signatureAlgorithm = stream.getUint8();
+        // Signature  - opaque signature<0..2^16-1>;
+        const sigLength = stream.getUint16();
+        const signature = stream.getBlock(sigLength);
+        // Check that we read the entire buffer
+        if (stream.position !== buf.length) {
+            throw new Error('SCT buffer length mismatch');
+        }
+        return new SignedCertificateTimestamp({
+            version,
+            logID,
+            timestamp,
+            extensions,
+            hashAlgorithm,
+            signatureAlgorithm,
+            signature,
+        });
     }
-    return `${data.message}${suffix}`;
-  }
-  return `Unknown error: ${JSON.stringify(data)}`;
 }
+exports.SignedCertificateTimestamp = SignedCertificateTimestamp;
 
-// pkg/dist-src/with-defaults.js
-function withDefaults(oldEndpoint, newDefaults) {
-  const endpoint2 = oldEndpoint.defaults(newDefaults);
-  const newApi = function(route, parameters) {
-    const endpointOptions = endpoint2.merge(route, parameters);
-    if (!endpointOptions.request || !endpointOptions.request.hook) {
-      return fetchWrapper(endpoint2.parse(endpointOptions));
-    }
-    const request2 = (route2, parameters2) => {
-      return fetchWrapper(
-        endpoint2.parse(endpoint2.merge(route2, parameters2))
-      );
-    };
-    Object.assign(request2, {
-      endpoint: endpoint2,
-      defaults: withDefaults.bind(null, endpoint2)
-    });
-    return endpointOptions.request.hook(request2, endpointOptions);
-  };
-  return Object.assign(newApi, {
-    endpoint: endpoint2,
-    defaults: withDefaults.bind(null, endpoint2)
-  });
-}
 
-// pkg/dist-src/index.js
-var request = withDefaults(import_endpoint.endpoint, {
-  headers: {
-    "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`
-  }
-});
-// Annotate the CommonJS export names for ESM import in node:
-0 && (0);
+/***/ }),
+
+/***/ 23688:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HEADER_OCI_SUBJECT = exports.HEADER_LOCATION = exports.HEADER_IF_MATCH = exports.HEADER_ETAG = exports.HEADER_DIGEST = exports.HEADER_CONTENT_TYPE = exports.HEADER_CONTENT_LENGTH = exports.HEADER_AUTHORIZATION = exports.HEADER_AUTHENTICATE = exports.HEADER_API_VERSION = exports.HEADER_ACCEPT = exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = exports.CONTENT_TYPE_OCTET_STREAM = exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = exports.CONTENT_TYPE_DOCKER_MANIFEST = exports.CONTENT_TYPE_OCI_MANIFEST = exports.CONTENT_TYPE_OCI_INDEX = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+exports.CONTENT_TYPE_OCI_INDEX = 'application/vnd.oci.image.index.v1+json';
+exports.CONTENT_TYPE_OCI_MANIFEST = 'application/vnd.oci.image.manifest.v1+json';
+exports.CONTENT_TYPE_DOCKER_MANIFEST = 'application/vnd.docker.distribution.manifest.v2+json';
+exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = 'application/vnd.docker.distribution.manifest.list.v2+json';
+exports.CONTENT_TYPE_OCTET_STREAM = 'application/octet-stream';
+exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = 'application/vnd.oci.empty.v1+json';
+exports.HEADER_ACCEPT = 'Accept';
+exports.HEADER_API_VERSION = 'Docker-Distribution-API-Version';
+exports.HEADER_AUTHENTICATE = 'WWW-Authenticate';
+exports.HEADER_AUTHORIZATION = 'Authorization';
+exports.HEADER_CONTENT_LENGTH = 'Content-Length';
+exports.HEADER_CONTENT_TYPE = 'Content-Type';
+exports.HEADER_DIGEST = 'Docker-Content-Digest';
+exports.HEADER_ETAG = 'Etag';
+exports.HEADER_IF_MATCH = 'If-Match';
+exports.HEADER_LOCATION = 'Location';
+exports.HEADER_OCI_SUBJECT = 'OCI-Subject';
 
 
 /***/ }),
 
-/***/ 18456:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 62691:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toMessageSignatureBundle = toMessageSignatureBundle;
-exports.toDSSEBundle = toDSSEBundle;
+exports.fromBasicAuth = exports.toBasicAuth = exports.getRegistryCredentials = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -13043,132 +12907,101 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const protobuf_specs_1 = __nccwpck_require__(74799);
-const bundle_1 = __nccwpck_require__(37742);
-// Message signature bundle - $case: 'messageSignature'
-function toMessageSignatureBundle(options) {
-    return {
-        mediaType: options.certificateChain
-            ? bundle_1.BUNDLE_V02_MEDIA_TYPE
-            : bundle_1.BUNDLE_V03_MEDIA_TYPE,
-        content: {
-            $case: 'messageSignature',
-            messageSignature: {
-                messageDigest: {
-                    algorithm: protobuf_specs_1.HashAlgorithm.SHA2_256,
-                    digest: options.digest,
-                },
-                signature: options.signature,
-            },
-        },
-        verificationMaterial: toVerificationMaterial(options),
-    };
-}
-// DSSE envelope bundle - $case: 'dsseEnvelope'
-function toDSSEBundle(options) {
-    return {
-        mediaType: options.certificateChain
-            ? bundle_1.BUNDLE_V02_MEDIA_TYPE
-            : bundle_1.BUNDLE_V03_MEDIA_TYPE,
-        content: {
-            $case: 'dsseEnvelope',
-            dsseEnvelope: toEnvelope(options),
-        },
-        verificationMaterial: toVerificationMaterial(options),
-    };
-}
-function toEnvelope(options) {
-    return {
-        payloadType: options.artifactType,
-        payload: options.artifact,
-        signatures: [toSignature(options)],
-    };
-}
-function toSignature(options) {
-    return {
-        keyid: options.keyHint || '',
-        sig: options.signature,
-    };
-}
-// Verification material
-function toVerificationMaterial(options) {
-    return {
-        content: toKeyContent(options),
-        tlogEntries: [],
-        timestampVerificationData: { rfc3161Timestamps: [] },
-    };
-}
-function toKeyContent(options) {
-    if (options.certificate) {
-        if (options.certificateChain) {
-            return {
-                $case: 'x509CertificateChain',
-                x509CertificateChain: {
-                    certificates: [{ rawBytes: options.certificate }],
-                },
-            };
-        }
-        else {
-            return {
-                $case: 'certificate',
-                certificate: { rawBytes: options.certificate },
-            };
-        }
+const node_fs_1 = __importDefault(__nccwpck_require__(73024));
+const node_os_1 = __importDefault(__nccwpck_require__(48161));
+const node_path_1 = __importDefault(__nccwpck_require__(76760));
+const name_1 = __nccwpck_require__(96666);
+// Returns the credentials for a given registry by reading the Docker config
+// file.
+const getRegistryCredentials = (imageName) => {
+    const { registry } = (0, name_1.parseImageName)(imageName);
+    const dockerConfigFile = node_path_1.default.join(node_os_1.default.homedir(), '.docker', 'config.json');
+    let content;
+    try {
+        content = node_fs_1.default.readFileSync(dockerConfigFile, 'utf8');
     }
-    else {
-        return {
-            $case: 'publicKey',
-            publicKey: {
-                hint: options.keyHint || '',
-            },
-        };
+    catch (err) {
+        throw new Error(`No credential file found at ${dockerConfigFile}`);
     }
-}
+    const dockerConfig = JSON.parse(content);
+    const credKey = Object.keys(dockerConfig.auths || {}).find((key) => key.includes(registry)) || registry;
+    const creds = dockerConfig.auths?.[credKey];
+    if (!creds) {
+        throw new Error(`No credentials found for registry ${registry}`);
+    }
+    // Extract username/password from auth string
+    const { username, password } = (0, exports.fromBasicAuth)(creds.auth);
+    // If the identitytoken is present, use it as the password (primarily for ACR)
+    const pass = creds.identitytoken ? creds.identitytoken : password;
+    return { username, password: pass };
+};
+exports.getRegistryCredentials = getRegistryCredentials;
+// Encode the username and password as base64-encoded basicauth value
+const toBasicAuth = (creds) => Buffer.from(`${creds.username}:${creds.password}`).toString('base64');
+exports.toBasicAuth = toBasicAuth;
+// Decode the base64-encoded basicauth value
+const fromBasicAuth = (auth) => {
+    // Need to account for the possibility of ':' in the password
+    const [username, ...rest] = Buffer.from(auth, 'base64').toString().split(':');
+    const password = rest.join(':');
+    return { username, password };
+};
+exports.fromBasicAuth = fromBasicAuth;
 
 
 /***/ }),
 
-/***/ 37742:
+/***/ 46803:
 /***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = void 0;
-exports.isBundleWithCertificateChain = isBundleWithCertificateChain;
-exports.isBundleWithPublicKey = isBundleWithPublicKey;
-exports.isBundleWithMessageSignature = isBundleWithMessageSignature;
-exports.isBundleWithDsseEnvelope = isBundleWithDsseEnvelope;
-exports.BUNDLE_V01_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1';
-exports.BUNDLE_V02_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.2';
-exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.3';
-exports.BUNDLE_V03_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle.v0.3+json';
-// Type guards for bundle variants.
-function isBundleWithCertificateChain(b) {
-    return b.verificationMaterial.content.$case === 'x509CertificateChain';
-}
-function isBundleWithPublicKey(b) {
-    return b.verificationMaterial.content.$case === 'publicKey';
-}
-function isBundleWithMessageSignature(b) {
-    return b.content.$case === 'messageSignature';
+exports.OCIError = exports.ensureStatus = exports.HTTPError = void 0;
+class HTTPError extends Error {
+    constructor({ status, message }) {
+        super(message);
+        this.statusCode = status;
+    }
 }
-function isBundleWithDsseEnvelope(b) {
-    return b.content.$case === 'dsseEnvelope';
+exports.HTTPError = HTTPError;
+// Inspects the response status and throws an HTTPError if it does not match the
+// expected status code
+const ensureStatus = (expectedStatus) => {
+    return (response) => {
+        if (response.status !== expectedStatus) {
+            throw new HTTPError({
+                message: `Error fetching ${response.url} - expected ${expectedStatus}, received ${response.status}`,
+                status: response.status,
+            });
+        }
+        return response;
+    };
+};
+exports.ensureStatus = ensureStatus;
+class OCIError extends Error {
+    constructor({ message, cause, }) {
+        super(message);
+        this.cause = cause;
+        this.name = this.constructor.name;
+    }
 }
+exports.OCIError = OCIError;
 
 
 /***/ }),
 
-/***/ 47714:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 32721:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ValidationError = void 0;
 /*
-Copyright 2023 The Sigstore Authors.
+Copyright 2024 The Sigstore Authors.
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
@@ -13182,24 +13015,91 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-class ValidationError extends Error {
-    constructor(message, fields) {
-        super(message);
-        this.fields = fields;
+const http2_1 = __nccwpck_require__(85675);
+const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310));
+const proc_log_1 = __nccwpck_require__(26687);
+const promise_retry_1 = __importDefault(__nccwpck_require__(90390));
+const { HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants;
+const fetchWithRetry = async (url, options = {}) => {
+    return (0, promise_retry_1.default)(async (retry, attemptNum) => {
+        /* eslint-disable @typescript-eslint/no-explicit-any */
+        const logRetry = (reason) => {
+            proc_log_1.log.http('fetch', `${options.method} ${url} attempt ${attemptNum} failed with ${reason}`);
+        };
+        const response = await (0, make_fetch_happen_1.default)(url, {
+            ...options,
+            retry: false, // We're handling retries ourselves
+        }).catch((reason) => {
+            logRetry(reason);
+            return retry(reason);
+        });
+        if (retryable(response.status)) {
+            logRetry(response.status);
+            return retry(response);
+        }
+        return response;
+    }, retryOpts(options.retry)).catch((err) => {
+        // If we got an actual error, throw it
+        if (err instanceof Error) {
+            throw err;
+        }
+        // Otherwise, return the response (this is simply a retry-able response for
+        // which we exceeded the retry limit)
+        return err;
+    });
+};
+// Returns a wrapped fetch function with default options
+fetchWithRetry.defaults = (defaultOptions = {}, wrappedFetch = fetchWithRetry) => {
+    const defaultedFetch = (url, options = {}) => {
+        const finalOptions = {
+            ...defaultOptions,
+            ...options,
+            headers: { ...defaultOptions.headers, ...options.headers },
+        };
+        return wrappedFetch(url, finalOptions);
+    };
+    defaultedFetch.defaults = (newDefaults = {}) => fetchWithRetry.defaults(newDefaults, defaultedFetch);
+    return defaultedFetch;
+};
+// Determine if a status code is retryable. This includes 5xx errors, 408, and
+// 429.
+const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR;
+// Normalize the retry options to the format expected by promise-retry
+const retryOpts = (retry) => {
+    if (typeof retry === 'boolean') {
+        return { retries: retry ? 1 : 0 };
     }
-}
-exports.ValidationError = ValidationError;
+    else if (typeof retry === 'number') {
+        return { retries: retry };
+    }
+    else {
+        return { retries: 0, ...retry };
+    }
+};
+exports["default"] = fetchWithRetry;
 
 
 /***/ }),
 
-/***/ 61040:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 19812:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
+    if (kind === "m") throw new TypeError("Private method is not writable");
+    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+};
+var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
+    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var _OCIImage_instances, _OCIImage_client, _OCIImage_credentials, _OCIImage_createReferrersIndexByTag;
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isBundleV01 = exports.assertBundleV02 = exports.assertBundleV01 = exports.assertBundleLatest = exports.assertBundle = exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = exports.ValidationError = exports.isBundleWithPublicKey = exports.isBundleWithMessageSignature = exports.isBundleWithDsseEnvelope = exports.isBundleWithCertificateChain = exports.BUNDLE_V03_MEDIA_TYPE = exports.BUNDLE_V03_LEGACY_MEDIA_TYPE = exports.BUNDLE_V02_MEDIA_TYPE = exports.BUNDLE_V01_MEDIA_TYPE = exports.toMessageSignatureBundle = exports.toDSSEBundle = void 0;
+exports.OCIImage = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -13215,103 +13115,264 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-var build_1 = __nccwpck_require__(18456);
-Object.defineProperty(exports, "toDSSEBundle", ({ enumerable: true, get: function () { return build_1.toDSSEBundle; } }));
-Object.defineProperty(exports, "toMessageSignatureBundle", ({ enumerable: true, get: function () { return build_1.toMessageSignatureBundle; } }));
-var bundle_1 = __nccwpck_require__(37742);
-Object.defineProperty(exports, "BUNDLE_V01_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V01_MEDIA_TYPE; } }));
-Object.defineProperty(exports, "BUNDLE_V02_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V02_MEDIA_TYPE; } }));
-Object.defineProperty(exports, "BUNDLE_V03_LEGACY_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_LEGACY_MEDIA_TYPE; } }));
-Object.defineProperty(exports, "BUNDLE_V03_MEDIA_TYPE", ({ enumerable: true, get: function () { return bundle_1.BUNDLE_V03_MEDIA_TYPE; } }));
-Object.defineProperty(exports, "isBundleWithCertificateChain", ({ enumerable: true, get: function () { return bundle_1.isBundleWithCertificateChain; } }));
-Object.defineProperty(exports, "isBundleWithDsseEnvelope", ({ enumerable: true, get: function () { return bundle_1.isBundleWithDsseEnvelope; } }));
-Object.defineProperty(exports, "isBundleWithMessageSignature", ({ enumerable: true, get: function () { return bundle_1.isBundleWithMessageSignature; } }));
-Object.defineProperty(exports, "isBundleWithPublicKey", ({ enumerable: true, get: function () { return bundle_1.isBundleWithPublicKey; } }));
-var error_1 = __nccwpck_require__(47714);
-Object.defineProperty(exports, "ValidationError", ({ enumerable: true, get: function () { return error_1.ValidationError; } }));
-var serialized_1 = __nccwpck_require__(23404);
-Object.defineProperty(exports, "bundleFromJSON", ({ enumerable: true, get: function () { return serialized_1.bundleFromJSON; } }));
-Object.defineProperty(exports, "bundleToJSON", ({ enumerable: true, get: function () { return serialized_1.bundleToJSON; } }));
-Object.defineProperty(exports, "envelopeFromJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeFromJSON; } }));
-Object.defineProperty(exports, "envelopeToJSON", ({ enumerable: true, get: function () { return serialized_1.envelopeToJSON; } }));
-var validate_1 = __nccwpck_require__(9352);
-Object.defineProperty(exports, "assertBundle", ({ enumerable: true, get: function () { return validate_1.assertBundle; } }));
-Object.defineProperty(exports, "assertBundleLatest", ({ enumerable: true, get: function () { return validate_1.assertBundleLatest; } }));
-Object.defineProperty(exports, "assertBundleV01", ({ enumerable: true, get: function () { return validate_1.assertBundleV01; } }));
-Object.defineProperty(exports, "assertBundleV02", ({ enumerable: true, get: function () { return validate_1.assertBundleV02; } }));
-Object.defineProperty(exports, "isBundleV01", ({ enumerable: true, get: function () { return validate_1.isBundleV01; } }));
+const constants_1 = __nccwpck_require__(23688);
+const error_1 = __nccwpck_require__(46803);
+const registry_1 = __nccwpck_require__(22138);
+const DOCKER_DEFAULT_REGISTRY = 'registry-1.docker.io';
+const EMPTY_BLOB = Buffer.from('{}');
+class OCIImage {
+    constructor(image, creds, opts) {
+        _OCIImage_instances.add(this);
+        _OCIImage_client.set(this, void 0);
+        _OCIImage_credentials.set(this, void 0);
+        __classPrivateFieldSet(this, _OCIImage_client, new registry_1.RegistryClient(canonicalizeRegistryName(image.registry), image.path, opts), "f");
+        __classPrivateFieldSet(this, _OCIImage_credentials, creds, "f");
+    }
+    async addArtifact(opts) {
+        let artifactDescriptor;
+        const annotations = {
+            'org.opencontainers.image.created': new Date().toISOString(),
+            ...opts.annotations,
+        };
+        try {
+            if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) {
+                await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f"));
+            }
+            // Check that the image exists
+            const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(opts.imageDigest);
+            // Upload the artifact blob
+            const artifactBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(opts.artifact);
+            // Upload the empty blob (needed for the manifest config)
+            const emptyBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(EMPTY_BLOB);
+            // Construct artifact manifest
+            const manifest = buildManifest({
+                artifactDescriptor: { ...artifactBlob, mediaType: opts.mediaType },
+                subjectDescriptor: imageDescriptor,
+                configDescriptor: {
+                    ...emptyBlob,
+                    mediaType: constants_1.CONTENT_TYPE_EMPTY_DESCRIPTOR,
+                },
+                annotations,
+            });
+            // Upload artifact manifest
+            artifactDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(manifest));
+            // Check to see if registry supports the referrers API. For most
+            // registries the presence of a subjectDigest response header when
+            // uploading the artifact manifest indicates that the referrers API IS
+            // supported -- however, this is not a guarantee (AWS ECR does NOT support
+            // the referrers API but still reports a subjectDigest).
+            const referrersSupported = await __classPrivateFieldGet(this, _OCIImage_client, "f").pingReferrers();
+            // Manually update the referrers list if the referrers API is not supported.
+            if (!artifactDescriptor.subjectDigest || !referrersSupported) {
+                // Strip subjectDigest from the artifact descriptor (in case it was returned)
+                /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
+                const { subjectDigest, ...descriptor } = artifactDescriptor;
+                await __classPrivateFieldGet(this, _OCIImage_instances, "m", _OCIImage_createReferrersIndexByTag).call(this, {
+                    artifact: {
+                        ...descriptor,
+                        artifactType: opts.mediaType,
+                        annotations,
+                    },
+                    imageDigest: opts.imageDigest,
+                });
+            }
+        }
+        catch (err) {
+            throw new error_1.OCIError({
+                message: `Error uploading artifact to container registry`,
+                cause: err,
+            });
+        }
+        return artifactDescriptor;
+    }
+    async getDigest(tag) {
+        try {
+            if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) {
+                await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f"));
+            }
+            const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(tag);
+            return imageDescriptor.digest;
+        }
+        catch (err) {
+            throw new error_1.OCIError({
+                message: `Error retrieving image digest from container registry`,
+                cause: err,
+            });
+        }
+    }
+}
+exports.OCIImage = OCIImage;
+_OCIImage_client = new WeakMap(), _OCIImage_credentials = new WeakMap(), _OCIImage_instances = new WeakSet(), _OCIImage_createReferrersIndexByTag = 
+// Create a referrers index by tag. This is a fallback for registries that do
+// not support the referrers API.
+// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests-with-subject
+async function _OCIImage_createReferrersIndexByTag(opts) {
+    const referrerTag = digestToTag(opts.imageDigest);
+    let referrerManifest;
+    let etag;
+    try {
+        // Retrieve any existing referrer index
+        const referrerIndex = await __classPrivateFieldGet(this, _OCIImage_client, "f").getManifest(referrerTag);
+        if (referrerIndex.mediaType !== constants_1.CONTENT_TYPE_OCI_INDEX) {
+            throw new Error(`Expected referrer manifest type ${constants_1.CONTENT_TYPE_OCI_INDEX}, got ${referrerIndex.mediaType}`);
+        }
+        referrerManifest = referrerIndex.body;
+        etag = referrerIndex.etag;
+    }
+    catch (err) {
+        // If the referrer index does not exist, create a new one
+        if (err instanceof error_1.HTTPError && err.statusCode === 404) {
+            referrerManifest = newIndex();
+        }
+        else {
+            throw err;
+        }
+    }
+    // If the artifact is not already in the index, add it to the list and
+    // re-upload the index
+    if (!referrerManifest.manifests.some((manifest) => manifest.digest === opts.artifact.digest)) {
+        // Add the artifact to the index
+        referrerManifest.manifests.push(opts.artifact);
+        await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(referrerManifest), {
+            mediaType: constants_1.CONTENT_TYPE_OCI_INDEX,
+            reference: referrerTag,
+            etag,
+        });
+    }
+};
+// Build an OCI manifest document with references to the given artifact,
+// subject, and config
+const buildManifest = (opts) => ({
+    schemaVersion: 2,
+    mediaType: constants_1.CONTENT_TYPE_OCI_MANIFEST,
+    artifactType: opts.artifactDescriptor.mediaType,
+    config: opts.configDescriptor,
+    layers: [opts.artifactDescriptor],
+    subject: opts.subjectDescriptor,
+    annotations: opts.annotations,
+});
+// Return an empty OCI index document
+const newIndex = () => ({
+    mediaType: constants_1.CONTENT_TYPE_OCI_INDEX,
+    schemaVersion: 2,
+    manifests: [],
+});
+// Convert an image digest to a tag per the Referrers Tag Schema
+// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#referrers-tag-schema
+const digestToTag = (digest) => {
+    return digest.replace(':', '-');
+};
+// Canonicalize the registry name to match the format used by the registry
+// client. This is used primarily to handle the special case of the Docker Hub
+// registry.
+// https://github.com/moby/moby/blob/v24.0.2/registry/config.go#L25-L48
+const canonicalizeRegistryName = (registry) => {
+    return registry.endsWith('docker.io') ? DOCKER_DEFAULT_REGISTRY : registry;
+};
 
 
 /***/ }),
 
-/***/ 23404:
+/***/ 81057:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.envelopeToJSON = exports.envelopeFromJSON = exports.bundleToJSON = exports.bundleFromJSON = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const protobuf_specs_1 = __nccwpck_require__(74799);
-const bundle_1 = __nccwpck_require__(37742);
-const validate_1 = __nccwpck_require__(9352);
-const bundleFromJSON = (obj) => {
-    const bundle = protobuf_specs_1.Bundle.fromJSON(obj);
-    switch (bundle.mediaType) {
-        case bundle_1.BUNDLE_V01_MEDIA_TYPE:
-            (0, validate_1.assertBundleV01)(bundle);
-            break;
-        case bundle_1.BUNDLE_V02_MEDIA_TYPE:
-            (0, validate_1.assertBundleV02)(bundle);
-            break;
-        default:
-            (0, validate_1.assertBundleLatest)(bundle);
-            break;
+exports.getImageDigest = exports.attachArtifactToImage = exports.OCIError = exports.getRegistryCredentials = void 0;
+const image_1 = __nccwpck_require__(19812);
+const name_1 = __nccwpck_require__(96666);
+var credentials_1 = __nccwpck_require__(62691);
+Object.defineProperty(exports, "getRegistryCredentials", ({ enumerable: true, get: function () { return credentials_1.getRegistryCredentials; } }));
+var error_1 = __nccwpck_require__(46803);
+Object.defineProperty(exports, "OCIError", ({ enumerable: true, get: function () { return error_1.OCIError; } }));
+// Associates the given artifact with an OCI image. The artifact is identified
+// by its media type and a buffer containing the artifact. The image is
+// identified by its FQDN and digest.
+const attachArtifactToImage = async (opts) => {
+    const image = (0, name_1.parseImageName)(opts.imageName);
+    return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).addArtifact(opts);
+};
+exports.attachArtifactToImage = attachArtifactToImage;
+// Returns the digest of the given image tag in the remote registry.
+const getImageDigest = async (opts) => {
+    const image = (0, name_1.parseImageName)(opts.imageName);
+    return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).getDigest(opts.imageTag);
+};
+exports.getImageDigest = getImageDigest;
+
+
+/***/ }),
+
+/***/ 96666:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseImageName = void 0;
+const expression = (...res) => res.join('');
+const group = (...res) => `(?:${expression(...res)})`;
+const repeated = (...res) => `${group(expression(...res))}+`;
+const optional = (...res) => `${group(expression(...res))}?`;
+const capture = (...res) => `(${expression(...res)})`;
+const anchored = (...res) => `^${expression(...res)}$`;
+// Lower case letters, numbers
+const ALPHA_NUMERIC_RE = '[a-z0-9]+';
+// Separators allowed to be embedded in name components. This allows one period,
+// one or two underscore or multiple dashes.
+const SEPARATOR_RE = group('\\.|_|__|-+');
+// Registry path component names to start with at least one letter or number,
+// with following parts able to be separated by one period, one or two
+// underscores or multiple dashes.
+const NAME_COMPONENT_RE = expression(ALPHA_NUMERIC_RE, optional(repeated(SEPARATOR_RE, ALPHA_NUMERIC_RE)));
+const NAME_RE = expression(NAME_COMPONENT_RE, repeated(optional('\\/', NAME_COMPONENT_RE)));
+// Component of the registry domain must be at least one letter or number, with
+// following parts able to be separated by a dash.
+const DOMAIN_COMPONENT_RE = group('[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]');
+// Restricts the registry domain to be one or more period separated components
+// followed by an optional port.
+const DOMAIN_RE = expression(DOMAIN_COMPONENT_RE, optional(repeated('\\.', DOMAIN_COMPONENT_RE)), optional(':[0-9]+'));
+// Capture the registry domain and path components of a repository name.
+const ANCHORED_NAME_RE = anchored(capture(DOMAIN_RE), '\\/', capture(NAME_RE));
+// Parses a fully qualified image name into its registry and path components.
+const parseImageName = (image) => {
+    const matches = image.match(ANCHORED_NAME_RE);
+    if (!matches) {
+        throw new Error(`Invalid image name: ${image}`);
     }
-    return bundle;
-};
-exports.bundleFromJSON = bundleFromJSON;
-const bundleToJSON = (bundle) => {
-    return protobuf_specs_1.Bundle.toJSON(bundle);
-};
-exports.bundleToJSON = bundleToJSON;
-const envelopeFromJSON = (obj) => {
-    return protobuf_specs_1.Envelope.fromJSON(obj);
-};
-exports.envelopeFromJSON = envelopeFromJSON;
-const envelopeToJSON = (envelope) => {
-    return protobuf_specs_1.Envelope.toJSON(envelope);
+    return {
+        registry: matches[1],
+        path: matches[2],
+    };
 };
-exports.envelopeToJSON = envelopeToJSON;
+exports.parseImageName = parseImageName;
 
 
 /***/ }),
 
-/***/ 9352:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 22138:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
+    if (kind === "m") throw new TypeError("Private method is not writable");
+    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+};
+var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
+    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+var _RegistryClient_instances, _RegistryClient_baseURL, _RegistryClient_repository, _RegistryClient_fetch, _RegistryClient_fetchDistributionToken, _RegistryClient_fetchOAuth2Token;
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.assertBundle = assertBundle;
-exports.assertBundleV01 = assertBundleV01;
-exports.isBundleV01 = isBundleV01;
-exports.assertBundleV02 = assertBundleV02;
-exports.assertBundleLatest = assertBundleLatest;
+exports.RegistryClient = exports.ZERO_DIGEST = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -13327,188 +13388,213 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const error_1 = __nccwpck_require__(47714);
-// Performs basic validation of a Sigstore bundle to ensure that all required
-// fields are populated. This is not a complete validation of the bundle, but
-// rather a check that the bundle is in a valid state to be processed by the
-// rest of the code.
-function assertBundle(b) {
-    const invalidValues = validateBundleBase(b);
-    if (invalidValues.length > 0) {
-        throw new error_1.ValidationError('invalid bundle', invalidValues);
-    }
-}
-// Asserts that the given bundle conforms to the v0.1 bundle format.
-function assertBundleV01(b) {
-    const invalidValues = [];
-    invalidValues.push(...validateBundleBase(b));
-    invalidValues.push(...validateInclusionPromise(b));
-    if (invalidValues.length > 0) {
-        throw new error_1.ValidationError('invalid v0.1 bundle', invalidValues);
-    }
-}
-// Type guard to determine if Bundle is a v0.1 bundle.
-function isBundleV01(b) {
-    try {
-        assertBundleV01(b);
-        return true;
-    }
-    catch (e) {
-        return false;
-    }
-}
-// Asserts that the given bundle conforms to the v0.2 bundle format.
-function assertBundleV02(b) {
-    const invalidValues = [];
-    invalidValues.push(...validateBundleBase(b));
-    invalidValues.push(...validateInclusionProof(b));
-    if (invalidValues.length > 0) {
-        throw new error_1.ValidationError('invalid v0.2 bundle', invalidValues);
-    }
-}
-// Asserts that the given bundle conforms to the newest (0.3) bundle format.
-function assertBundleLatest(b) {
-    const invalidValues = [];
-    invalidValues.push(...validateBundleBase(b));
-    invalidValues.push(...validateInclusionProof(b));
-    invalidValues.push(...validateNoCertificateChain(b));
-    if (invalidValues.length > 0) {
-        throw new error_1.ValidationError('invalid bundle', invalidValues);
-    }
-}
-function validateBundleBase(b) {
-    const invalidValues = [];
-    // Media type validation
-    if (b.mediaType === undefined ||
-        (!b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\+json;version=\d\.\d/) &&
-            !b.mediaType.match(/^application\/vnd\.dev\.sigstore\.bundle\.v\d\.\d\+json/))) {
-        invalidValues.push('mediaType');
-    }
-    // Content-related validation
-    if (b.content === undefined) {
-        invalidValues.push('content');
+const node_crypto_1 = __importDefault(__nccwpck_require__(77598));
+const constants_1 = __nccwpck_require__(23688);
+const credentials_1 = __nccwpck_require__(62691);
+const error_1 = __nccwpck_require__(46803);
+const fetch_1 = __importDefault(__nccwpck_require__(32721));
+const ALL_MANIFEST_MEDIA_TYPES = [
+    constants_1.CONTENT_TYPE_OCI_INDEX,
+    constants_1.CONTENT_TYPE_OCI_MANIFEST,
+    constants_1.CONTENT_TYPE_DOCKER_MANIFEST,
+    constants_1.CONTENT_TYPE_DOCKER_MANIFEST_LIST,
+].join(',');
+exports.ZERO_DIGEST = 'sha256:0000000000000000000000000000000000000000000000000000000000000000';
+class RegistryClient {
+    constructor(registry, repository, opts) {
+        _RegistryClient_instances.add(this);
+        _RegistryClient_baseURL.set(this, void 0);
+        _RegistryClient_repository.set(this, void 0);
+        _RegistryClient_fetch.set(this, void 0);
+        __classPrivateFieldSet(this, _RegistryClient_repository, repository, "f");
+        __classPrivateFieldSet(this, _RegistryClient_fetch, fetch_1.default.defaults(opts), "f");
+        // Use http for localhost registries, https otherwise
+        const hostname = new URL(`http://${registry}`).hostname;
+        /* istanbul ignore next */
+        const protocol = hostname === 'localhost' || hostname === '127.0.0.1' ? 'http' : 'https';
+        __classPrivateFieldSet(this, _RegistryClient_baseURL, `${protocol}://${registry}`, "f");
     }
-    else {
-        switch (b.content.$case) {
-            case 'messageSignature':
-                if (b.content.messageSignature.messageDigest === undefined) {
-                    invalidValues.push('content.messageSignature.messageDigest');
-                }
-                else {
-                    if (b.content.messageSignature.messageDigest.digest.length === 0) {
-                        invalidValues.push('content.messageSignature.messageDigest.digest');
-                    }
-                }
-                if (b.content.messageSignature.signature.length === 0) {
-                    invalidValues.push('content.messageSignature.signature');
-                }
-                break;
-            case 'dsseEnvelope':
-                if (b.content.dsseEnvelope.payload.length === 0) {
-                    invalidValues.push('content.dsseEnvelope.payload');
-                }
-                if (b.content.dsseEnvelope.signatures.length !== 1) {
-                    invalidValues.push('content.dsseEnvelope.signatures');
-                }
-                else {
-                    if (b.content.dsseEnvelope.signatures[0].sig.length === 0) {
-                        invalidValues.push('content.dsseEnvelope.signatures[0].sig');
-                    }
-                }
-                break;
+    // Authenticate with the registry. Sends an unauthenticated request to the
+    // registry in order to get an auth challenge. If the challenge scheme is
+    // "basic" we don't need a token and can authenticate requests using basic
+    // auth. Otherwise, we fetch a token from the auth server and use that to
+    // authenticate requests.
+    // https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md#the-registry
+    async signIn(creds) {
+        // Initiate a blob upload to get the auth challenge
+        const probeResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' });
+        // If we get a 200 response, we're already authenticated
+        if (probeResponse.status === 200) {
+            return;
+        }
+        const authHeader = probeResponse.headers.get(constants_1.HEADER_AUTHENTICATE) ||
+            /* istanbul ignore next */ '';
+        const challenge = parseChallenge(authHeader);
+        // If the challenge scheme is "basic" we don't need a token and can
+        // authenticate requests using basic auth
+        if (challenge.scheme === 'basic') {
+            const basicAuth = (0, credentials_1.toBasicAuth)(creds);
+            __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({
+                headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` },
+            }), "f");
+            return;
+        }
+        let token;
+        if (creds.username === '') {
+            // If the OAUth2 token request fails, try to fetch a distribution token
+            token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchOAuth2Token).call(this, creds, challenge).catch(() => undefined);
+        }
+        if (!token) {
+            token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchDistributionToken).call(this, creds, challenge);
         }
+        // Ensure the token is sent with all future requests
+        __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({
+            headers: { [constants_1.HEADER_AUTHORIZATION]: `Bearer ${token}` },
+        }), "f");
     }
-    // Verification material-related validation
-    if (b.verificationMaterial === undefined) {
-        invalidValues.push('verificationMaterial');
+    // Check the registry API version
+    async checkVersion() {
+        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/`);
+        return response.headers.get(constants_1.HEADER_API_VERSION) || '';
     }
-    else {
-        if (b.verificationMaterial.content === undefined) {
-            invalidValues.push('verificationMaterial.content');
-        }
-        else {
-            switch (b.verificationMaterial.content.$case) {
-                case 'x509CertificateChain':
-                    if (b.verificationMaterial.content.x509CertificateChain.certificates
-                        .length === 0) {
-                        invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates');
-                    }
-                    b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => {
-                        if (cert.rawBytes.length === 0) {
-                            invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`);
-                        }
-                    });
-                    break;
-                case 'certificate':
-                    if (b.verificationMaterial.content.certificate.rawBytes.length === 0) {
-                        invalidValues.push('verificationMaterial.content.certificate.rawBytes');
-                    }
-                    break;
-            }
+    // Upload a blob to the registry using the post/put method. Calculates the
+    // digest of the blob and checks to make sure the blob doesn't already exist
+    // in the registry before uploading.
+    async uploadBlob(blob) {
+        const digest = RegistryClient.digest(blob);
+        const size = blob.length;
+        // Check if blob already exists
+        const headResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/${digest}`, { method: 'HEAD', redirect: 'follow' });
+        if (headResponse.status === 200) {
+            return {
+                mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM,
+                digest,
+                size,
+            };
         }
-        if (b.verificationMaterial.tlogEntries === undefined) {
-            invalidValues.push('verificationMaterial.tlogEntries');
+        // Retrieve upload location (session ID)
+        const postResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' }).then((0, error_1.ensureStatus)(202));
+        const location = postResponse.headers.get(constants_1.HEADER_LOCATION);
+        if (!location) {
+            throw new Error('Missing location for blob upload');
         }
-        else {
-            if (b.verificationMaterial.tlogEntries.length > 0) {
-                b.verificationMaterial.tlogEntries.forEach((entry, i) => {
-                    if (entry.logId === undefined) {
-                        invalidValues.push(`verificationMaterial.tlogEntries[${i}].logId`);
-                    }
-                    if (entry.kindVersion === undefined) {
-                        invalidValues.push(`verificationMaterial.tlogEntries[${i}].kindVersion`);
-                    }
-                });
-            }
+        // Translate location to a full URL
+        const uploadLocation = new URL(location.startsWith('/') ? `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}${location}` : location);
+        // Add digest to query string
+        uploadLocation.searchParams.set('digest', digest);
+        // Upload blob
+        await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, uploadLocation.href, {
+            method: 'PUT',
+            body: blob,
+            headers: { [constants_1.HEADER_CONTENT_TYPE]: constants_1.CONTENT_TYPE_OCTET_STREAM },
+        }).then((0, error_1.ensureStatus)(201));
+        return { mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM, digest, size };
+    }
+    // Checks for the existence of a manifest by reference
+    async checkManifest(reference) {
+        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, {
+            method: 'HEAD',
+            headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES },
+        }).then((0, error_1.ensureStatus)(200));
+        const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) ||
+            /* istanbul ignore next */ '';
+        const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ '';
+        const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) ||
+            /* istanbul ignore next */ 0;
+        return { mediaType, digest, size };
+    }
+    // Retrieves a manifest by reference
+    async getManifest(reference) {
+        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, {
+            headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES },
+        }).then((0, error_1.ensureStatus)(200));
+        const body = await response.json();
+        const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) ||
+            /* istanbul ignore next */ '';
+        const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ '';
+        const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) || 0;
+        const etag = response.headers.get(constants_1.HEADER_ETAG) || undefined;
+        return { body, mediaType, digest, size, etag };
+    }
+    // Uploads a manifest by digest. If specified, the reference will be used as
+    // the manifest tag.
+    async uploadManifest(manifest, options = {}) {
+        const digest = RegistryClient.digest(manifest);
+        const reference = options.reference || digest;
+        const contentType = options.mediaType || constants_1.CONTENT_TYPE_OCI_MANIFEST;
+        const headers = { [constants_1.HEADER_CONTENT_TYPE]: contentType };
+        if (options.etag) {
+            headers[constants_1.HEADER_IF_MATCH] = options.etag;
         }
+        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { method: 'PUT', body: manifest, headers }).then((0, error_1.ensureStatus)(201));
+        const subjectDigest = response.headers.get(constants_1.HEADER_OCI_SUBJECT) || undefined;
+        return {
+            mediaType: contentType,
+            digest,
+            size: manifest.length,
+            subjectDigest,
+        };
     }
-    return invalidValues;
-}
-// Necessary for V01 bundles
-function validateInclusionPromise(b) {
-    const invalidValues = [];
-    if (b.verificationMaterial &&
-        b.verificationMaterial.tlogEntries?.length > 0) {
-        b.verificationMaterial.tlogEntries.forEach((entry, i) => {
-            if (entry.inclusionPromise === undefined) {
-                invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionPromise`);
-            }
-        });
+    // Returns true if the registry supports the referrers API
+    async pingReferrers() {
+        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/referrers/${exports.ZERO_DIGEST}`);
+        return response.status === 200;
     }
-    return invalidValues;
-}
-// Necessary for V02 and later bundles
-function validateInclusionProof(b) {
-    const invalidValues = [];
-    if (b.verificationMaterial &&
-        b.verificationMaterial.tlogEntries?.length > 0) {
-        b.verificationMaterial.tlogEntries.forEach((entry, i) => {
-            if (entry.inclusionProof === undefined) {
-                invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof`);
-            }
-            else {
-                if (entry.inclusionProof.checkpoint === undefined) {
-                    invalidValues.push(`verificationMaterial.tlogEntries[${i}].inclusionProof.checkpoint`);
-                }
-            }
-        });
+    static digest(blob) {
+        const hash = node_crypto_1.default.createHash('sha256');
+        hash.update(blob);
+        return `sha256:${hash.digest('hex')}`;
     }
-    return invalidValues;
 }
-// Necessary for V03 and later bundles
-function validateNoCertificateChain(b) {
-    const invalidValues = [];
-    /* istanbul ignore next */
-    if (b.verificationMaterial?.content?.$case === 'x509CertificateChain') {
-        invalidValues.push('verificationMaterial.content.$case');
+exports.RegistryClient = RegistryClient;
+_RegistryClient_baseURL = new WeakMap(), _RegistryClient_repository = new WeakMap(), _RegistryClient_fetch = new WeakMap(), _RegistryClient_instances = new WeakSet(), _RegistryClient_fetchDistributionToken = async function _RegistryClient_fetchDistributionToken(creds, challenge) {
+    const basicAuth = (0, credentials_1.toBasicAuth)(creds);
+    const authURL = new URL(challenge.realm);
+    authURL.searchParams.set('service', challenge.service);
+    authURL.searchParams.set('scope', challenge.scope);
+    // Make token request with basic auth
+    const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, authURL.toString(), {
+        headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` },
+    }).then((0, error_1.ensureStatus)(200));
+    return tokenResponse.json().then((json) => json.access_token || json.token);
+}, _RegistryClient_fetchOAuth2Token = async function _RegistryClient_fetchOAuth2Token(creds, challenge) {
+    const body = new URLSearchParams({
+        service: challenge.service,
+        scope: challenge.scope,
+        username: creds.username,
+        password: creds.password,
+        grant_type: 'password',
+    });
+    // Make OAuth token request
+    const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, challenge.realm, {
+        method: 'POST',
+        body,
+    }).then((0, error_1.ensureStatus)(200));
+    return tokenResponse.json().then((json) => json.access_token);
+};
+// Parses an auth challenge header into its components
+// https://datatracker.ietf.org/doc/html/rfc7235#section-4.1
+function parseChallenge(challenge) {
+    // Account for the possibility of spaces in the auth params
+    const [scheme, ...rest] = challenge.split(' ');
+    const authParams = rest.join(' ');
+    if (!['Basic', 'Bearer'].includes(scheme)) {
+        throw new Error(`Invalid challenge: ${challenge}`);
     }
-    return invalidValues;
+    return {
+        scheme: scheme.toLocaleLowerCase(),
+        realm: singleMatch(authParams, /realm="(.+?)"/),
+        service: singleMatch(authParams, /service="(.+?)"/),
+        scope: singleMatch(authParams, /scope="(.+?)"/),
+    };
 }
+// Returns the first capture group of a regex match, or an empty string
+const singleMatch = (str, regex) => str.match(regex)?.[1] || '';
 
 
 /***/ }),
 
-/***/ 99101:
+/***/ 47030:
 /***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
@@ -13605,7 +13691,7 @@ function isSet(value) {
 
 /***/ }),
 
-/***/ 53433:
+/***/ 45000:
 /***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
@@ -13637,7 +13723,7 @@ function isSet(value) {
 
 /***/ }),
 
-/***/ 38970:
+/***/ 70715:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
@@ -13645,9 +13731,9 @@ function isSet(value) {
 Object.defineProperty(exports, "__esModule", ({ value: true }));
 exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0;
 /* eslint-disable */
-const envelope_1 = __nccwpck_require__(99101);
-const sigstore_common_1 = __nccwpck_require__(48575);
-const sigstore_rekor_1 = __nccwpck_require__(13243);
+const envelope_1 = __nccwpck_require__(47030);
+const sigstore_common_1 = __nccwpck_require__(5334);
+const sigstore_rekor_1 = __nccwpck_require__(85204);
 function createBaseTimestampVerificationData() {
     return { rfc3161Timestamps: [] };
 }
@@ -13757,7 +13843,7 @@ function isSet(value) {
 
 /***/ }),
 
-/***/ 48575:
+/***/ 5334:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
@@ -13765,7 +13851,7 @@ function isSet(value) {
 Object.defineProperty(exports, "__esModule", ({ value: true }));
 exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0;
 /* eslint-disable */
-const timestamp_1 = __nccwpck_require__(53433);
+const timestamp_1 = __nccwpck_require__(45000);
 /**
  * Only a subset of the secure hash standard algorithms are supported.
  * See  for more
@@ -14353,7 +14439,7 @@ function isSet(value) {
 
 /***/ }),
 
-/***/ 13243:
+/***/ 85204:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
@@ -14361,7 +14447,7 @@ function isSet(value) {
 Object.defineProperty(exports, "__esModule", ({ value: true }));
 exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0;
 /* eslint-disable */
-const sigstore_common_1 = __nccwpck_require__(48575);
+const sigstore_common_1 = __nccwpck_require__(5334);
 function createBaseKindVersion() {
     return { kind: "", version: "" };
 }
@@ -14528,7 +14614,7 @@ function isSet(value) {
 
 /***/ }),
 
-/***/ 94810:
+/***/ 61997:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
@@ -14536,7 +14622,7 @@ function isSet(value) {
 Object.defineProperty(exports, "__esModule", ({ value: true }));
 exports.ClientTrustConfig = exports.SigningConfig = exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0;
 /* eslint-disable */
-const sigstore_common_1 = __nccwpck_require__(48575);
+const sigstore_common_1 = __nccwpck_require__(5334);
 function createBaseTransparencyLogInstance() {
     return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined, checkpointKeyId: undefined };
 }
@@ -14694,7 +14780,7 @@ function isSet(value) {
 
 /***/ }),
 
-/***/ 30445:
+/***/ 99732:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
@@ -14702,9 +14788,9 @@ function isSet(value) {
 Object.defineProperty(exports, "__esModule", ({ value: true }));
 exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_ObserverTimestampOptions = exports.ArtifactVerificationOptions_TlogIntegratedTimestampOptions = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0;
 /* eslint-disable */
-const sigstore_bundle_1 = __nccwpck_require__(38970);
-const sigstore_common_1 = __nccwpck_require__(48575);
-const sigstore_trustroot_1 = __nccwpck_require__(94810);
+const sigstore_bundle_1 = __nccwpck_require__(70715);
+const sigstore_common_1 = __nccwpck_require__(5334);
+const sigstore_trustroot_1 = __nccwpck_require__(61997);
 function createBaseCertificateIdentity() {
     return { issuer: "", san: undefined, oids: [] };
 }
@@ -15011,22 +15097,125 @@ function base64FromBytes(arr) {
     if (tsProtoGlobalThis.Buffer) {
         return tsProtoGlobalThis.Buffer.from(arr).toString("base64");
     }
-    else {
-        const bin = [];
-        arr.forEach((byte) => {
-            bin.push(String.fromCharCode(byte));
+    else {
+        const bin = [];
+        arr.forEach((byte) => {
+            bin.push(String.fromCharCode(byte));
+        });
+        return tsProtoGlobalThis.btoa(bin.join(""));
+    }
+}
+function isSet(value) {
+    return value !== null && value !== undefined;
+}
+
+
+/***/ }),
+
+/***/ 19654:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+__exportStar(__nccwpck_require__(47030), exports);
+__exportStar(__nccwpck_require__(70715), exports);
+__exportStar(__nccwpck_require__(5334), exports);
+__exportStar(__nccwpck_require__(85204), exports);
+__exportStar(__nccwpck_require__(61997), exports);
+__exportStar(__nccwpck_require__(99732), exports);
+
+
+/***/ }),
+
+/***/ 43049:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.BaseBundleBuilder = void 0;
+// BaseBundleBuilder is a base class for BundleBuilder implementations. It
+// provides a the basic wokflow for signing and witnessing an artifact.
+// Subclasses must implement the `package` method to assemble a valid bundle
+// with the generated signature and verification material.
+class BaseBundleBuilder {
+    constructor(options) {
+        this.signer = options.signer;
+        this.witnesses = options.witnesses;
+    }
+    // Executes the signing/witnessing process for the given artifact.
+    async create(artifact) {
+        const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob));
+        const bundle = await this.package(artifact, signature);
+        // Invoke all of the witnesses in parallel
+        const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key))));
+        // Collect the verification material from all of the witnesses
+        const tlogEntryList = [];
+        const timestampList = [];
+        verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => {
+            tlogEntryList.push(...(tlogEntries ?? []));
+            timestampList.push(...(rfc3161Timestamps ?? []));
         });
-        return tsProtoGlobalThis.btoa(bin.join(""));
+        // Merge the collected verification material into the bundle
+        bundle.verificationMaterial.tlogEntries = tlogEntryList;
+        bundle.verificationMaterial.timestampVerificationData = {
+            rfc3161Timestamps: timestampList,
+        };
+        return bundle;
+    }
+    // Override this function to apply any pre-signing transformations to the
+    // artifact. The returned buffer will be signed by the signer. The default
+    // implementation simply returns the artifact data.
+    async prepare(artifact) {
+        return artifact.data;
     }
 }
-function isSet(value) {
-    return value !== null && value !== undefined;
+exports.BaseBundleBuilder = BaseBundleBuilder;
+// Extracts the public key from a KeyMaterial. Returns either the public key
+// or the certificate, depending on the type of key material.
+function publicKey(key) {
+    switch (key.$case) {
+        case 'publicKey':
+            return key.publicKey;
+        case 'x509Certificate':
+            return key.certificate;
+    }
 }
 
 
 /***/ }),
 
-/***/ 74799:
+/***/ 85192:
 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
@@ -15042,10 +15231,21 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
     if (k2 === undefined) k2 = k;
     o[k2] = m[k];
 }));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
-    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
 };
 Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toMessageSignatureBundle = toMessageSignatureBundle;
+exports.toDSSEBundle = toDSSEBundle;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15061,23 +15261,46 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-__exportStar(__nccwpck_require__(99101), exports);
-__exportStar(__nccwpck_require__(38970), exports);
-__exportStar(__nccwpck_require__(48575), exports);
-__exportStar(__nccwpck_require__(13243), exports);
-__exportStar(__nccwpck_require__(94810), exports);
-__exportStar(__nccwpck_require__(30445), exports);
+const sigstore = __importStar(__nccwpck_require__(61040));
+const util_1 = __nccwpck_require__(19100);
+// Helper functions for assembling the parts of a Sigstore bundle
+// Message signature bundle - $case: 'messageSignature'
+function toMessageSignatureBundle(artifact, signature) {
+    const digest = util_1.crypto.digest('sha256', artifact.data);
+    return sigstore.toMessageSignatureBundle({
+        digest,
+        signature: signature.signature,
+        certificate: signature.key.$case === 'x509Certificate'
+            ? util_1.pem.toDER(signature.key.certificate)
+            : undefined,
+        keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined,
+        certificateChain: true,
+    });
+}
+// DSSE envelope bundle - $case: 'dsseEnvelope'
+function toDSSEBundle(artifact, signature, certificateChain) {
+    return sigstore.toDSSEBundle({
+        artifact: artifact.data,
+        artifactType: artifact.type,
+        signature: signature.signature,
+        certificate: signature.key.$case === 'x509Certificate'
+            ? util_1.pem.toDER(signature.key.certificate)
+            : undefined,
+        keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined,
+        certificateChain,
+    });
+}
 
 
 /***/ }),
 
-/***/ 11121:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 83997:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ASN1TypeError = exports.ASN1ParseError = void 0;
+exports.DSSEBundleBuilder = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15093,23 +15316,60 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-class ASN1ParseError extends Error {
+const util_1 = __nccwpck_require__(19100);
+const base_1 = __nccwpck_require__(43049);
+const bundle_1 = __nccwpck_require__(85192);
+// BundleBuilder implementation for DSSE wrapped attestations
+class DSSEBundleBuilder extends base_1.BaseBundleBuilder {
+    constructor(options) {
+        super(options);
+        this.certificateChain = options.certificateChain ?? false;
+    }
+    // DSSE requires the artifact to be pre-encoded with the payload type
+    // before the signature is generated.
+    async prepare(artifact) {
+        const a = artifactDefaults(artifact);
+        return util_1.dsse.preAuthEncoding(a.type, a.data);
+    }
+    // Packages the artifact and signature into a DSSE bundle
+    async package(artifact, signature) {
+        return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.certificateChain);
+    }
 }
-exports.ASN1ParseError = ASN1ParseError;
-class ASN1TypeError extends Error {
+exports.DSSEBundleBuilder = DSSEBundleBuilder;
+// Defaults the artifact type to an empty string if not provided
+function artifactDefaults(artifact) {
+    return {
+        ...artifact,
+        type: artifact.type ?? '',
+    };
 }
-exports.ASN1TypeError = ASN1TypeError;
 
 
 /***/ }),
 
-/***/ 86027:
+/***/ 35530:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ASN1Obj = void 0;
+exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0;
+var dsse_1 = __nccwpck_require__(83997);
+Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } }));
+var message_1 = __nccwpck_require__(8269);
+Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } }));
+
+
+/***/ }),
+
+/***/ 8269:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MessageSignatureBundleBuilder = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15125,13 +15385,23 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-var obj_1 = __nccwpck_require__(50990);
-Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return obj_1.ASN1Obj; } }));
+const base_1 = __nccwpck_require__(43049);
+const bundle_1 = __nccwpck_require__(85192);
+// BundleBuilder implementation for raw message signatures
+class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder {
+    constructor(options) {
+        super(options);
+    }
+    async package(artifact, signature) {
+        return (0, bundle_1.toMessageSignatureBundle)(artifact, signature);
+    }
+}
+exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder;
 
 
 /***/ }),
 
-/***/ 84243:
+/***/ 97841:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
@@ -15152,62 +15422,37 @@ See the License for the specific language governing permissions and
 limitations under the License.
 */
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decodeLength = decodeLength;
-exports.encodeLength = encodeLength;
-const error_1 = __nccwpck_require__(11121);
-// Decodes the length of a DER-encoded ANS.1 element from the supplied stream.
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes
-function decodeLength(stream) {
-    const buf = stream.getUint8();
-    // If the most significant bit is UNSET the length is just the value of the
-    // byte.
-    if ((buf & 0x80) === 0x00) {
-        return buf;
-    }
-    // Otherwise, the lower 7 bits of the first byte indicate the number of bytes
-    // that follow to encode the length.
-    const byteCount = buf & 0x7f;
-    // Ensure the encoded length can safely fit in a JS number.
-    if (byteCount > 6) {
-        throw new error_1.ASN1ParseError('length exceeds 6 byte limit');
-    }
-    // Iterate over the bytes that encode the length.
-    let len = 0;
-    for (let i = 0; i < byteCount; i++) {
-        len = len * 256 + stream.getUint8();
-    }
-    // This is a valid ASN.1 length encoding, but we don't support it.
-    if (len === 0) {
-        throw new error_1.ASN1ParseError('indefinite length encoding not supported');
+exports.InternalError = void 0;
+exports.internalError = internalError;
+const error_1 = __nccwpck_require__(40369);
+class InternalError extends Error {
+    constructor({ code, message, cause, }) {
+        super(message);
+        this.name = this.constructor.name;
+        this.cause = cause;
+        this.code = code;
     }
-    return len;
 }
-// Translates the supplied value to a DER-encoded length.
-function encodeLength(len) {
-    if (len < 128) {
-        return Buffer.from([len]);
-    }
-    // Bitwise operations on large numbers are not supported in JS, so we need to
-    // use BigInts.
-    let val = BigInt(len);
-    const bytes = [];
-    while (val > 0n) {
-        bytes.unshift(Number(val & 255n));
-        val = val >> 8n;
+exports.InternalError = InternalError;
+function internalError(err, code, message) {
+    if (err instanceof error_1.HTTPError) {
+        message += ` - ${err.message}`;
     }
-    return Buffer.from([0x80 | bytes.length, ...bytes]);
+    throw new InternalError({
+        code: code,
+        message: message,
+        cause: err,
+    });
 }
 
 
 /***/ }),
 
-/***/ 50990:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 40369:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ASN1Obj = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15223,156 +15468,30 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const stream_1 = __nccwpck_require__(1673);
-const error_1 = __nccwpck_require__(11121);
-const length_1 = __nccwpck_require__(84243);
-const parse_1 = __nccwpck_require__(81044);
-const tag_1 = __nccwpck_require__(59343);
-class ASN1Obj {
-    constructor(tag, value, subs) {
-        this.tag = tag;
-        this.value = value;
-        this.subs = subs;
-    }
-    // Constructs an ASN.1 object from a Buffer of DER-encoded bytes.
-    static parseBuffer(buf) {
-        return parseStream(new stream_1.ByteStream(buf));
-    }
-    toDER() {
-        const valueStream = new stream_1.ByteStream();
-        if (this.subs.length > 0) {
-            for (const sub of this.subs) {
-                valueStream.appendView(sub.toDER());
-            }
-        }
-        else {
-            valueStream.appendView(this.value);
-        }
-        const value = valueStream.buffer;
-        // Concat tag/length/value
-        const obj = new stream_1.ByteStream();
-        obj.appendChar(this.tag.toDER());
-        obj.appendView((0, length_1.encodeLength)(value.length));
-        obj.appendView(value);
-        return obj.buffer;
-    }
-    /////////////////////////////////////////////////////////////////////////////
-    // Convenience methods for parsing ASN.1 primitives into JS types
-    // Returns the ASN.1 object's value as a boolean. Throws an error if the
-    // object is not a boolean.
-    toBoolean() {
-        if (!this.tag.isBoolean()) {
-            throw new error_1.ASN1TypeError('not a boolean');
-        }
-        return (0, parse_1.parseBoolean)(this.value);
-    }
-    // Returns the ASN.1 object's value as a BigInt. Throws an error if the
-    // object is not an integer.
-    toInteger() {
-        if (!this.tag.isInteger()) {
-            throw new error_1.ASN1TypeError('not an integer');
-        }
-        return (0, parse_1.parseInteger)(this.value);
-    }
-    // Returns the ASN.1 object's value as an OID string. Throws an error if the
-    // object is not an OID.
-    toOID() {
-        if (!this.tag.isOID()) {
-            throw new error_1.ASN1TypeError('not an OID');
-        }
-        return (0, parse_1.parseOID)(this.value);
-    }
-    // Returns the ASN.1 object's value as a Date. Throws an error if the object
-    // is not either a UTCTime or a GeneralizedTime.
-    toDate() {
-        switch (true) {
-            case this.tag.isUTCTime():
-                return (0, parse_1.parseTime)(this.value, true);
-            case this.tag.isGeneralizedTime():
-                return (0, parse_1.parseTime)(this.value, false);
-            default:
-                throw new error_1.ASN1TypeError('not a date');
-        }
-    }
-    // Returns the ASN.1 object's value as a number[] where each number is the
-    // value of a bit in the bit string. Throws an error if the object is not a
-    // bit string.
-    toBitString() {
-        if (!this.tag.isBitString()) {
-            throw new error_1.ASN1TypeError('not a bit string');
-        }
-        return (0, parse_1.parseBitString)(this.value);
-    }
-}
-exports.ASN1Obj = ASN1Obj;
-/////////////////////////////////////////////////////////////////////////////
-// Internal stream parsing functions
-function parseStream(stream) {
-    // Parse tag, length, and value from stream
-    const tag = new tag_1.ASN1Tag(stream.getUint8());
-    const len = (0, length_1.decodeLength)(stream);
-    const value = stream.slice(stream.position, len);
-    const start = stream.position;
-    let subs = [];
-    // If the object is constructed, parse its children. Sometimes, children
-    // are embedded in OCTESTRING objects, so we need to check those
-    // for children as well.
-    if (tag.constructed) {
-        subs = collectSubs(stream, len);
-    }
-    else if (tag.isOctetString()) {
-        // Attempt to parse children of OCTETSTRING objects. If anything fails,
-        // assume the object is not constructed and treat as primitive.
-        try {
-            subs = collectSubs(stream, len);
-        }
-        catch (e) {
-            // Fail silently and treat as primitive
-        }
-    }
-    // If there are no children, move stream cursor to the end of the object
-    if (subs.length === 0) {
-        stream.seek(start + len);
-    }
-    return new ASN1Obj(tag, value, subs);
-}
-function collectSubs(stream, len) {
-    // Calculate end of object content
-    const end = stream.position + len;
-    // Make sure there are enough bytes left in the stream. This should never
-    // happen, cause it'll get caught when the stream is sliced in parseStream.
-    // Leaving as an extra check just in case.
-    /* istanbul ignore if */
-    if (end > stream.length) {
-        throw new error_1.ASN1ParseError('invalid length');
-    }
-    // Parse all children
-    const subs = [];
-    while (stream.position < end) {
-        subs.push(parseStream(stream));
-    }
-    // When we're done parsing children, we should be at the end of the object
-    if (stream.position !== end) {
-        throw new error_1.ASN1ParseError('invalid length');
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HTTPError = void 0;
+class HTTPError extends Error {
+    constructor({ status, message, location, }) {
+        super(`(${status}) ${message}`);
+        this.statusCode = status;
+        this.location = location;
     }
-    return subs;
 }
+exports.HTTPError = HTTPError;
 
 
 /***/ }),
 
-/***/ 81044:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 9823:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseInteger = parseInteger;
-exports.parseStringASCII = parseStringASCII;
-exports.parseTime = parseTime;
-exports.parseOID = parseOID;
-exports.parseBoolean = parseBoolean;
-exports.parseBitString = parseBitString;
+exports.fetchWithRetry = fetchWithRetry;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15388,118 +15507,94 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/;
-const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\.\d{3})?Z$/;
-// Parse a BigInt from the DER-encoded buffer
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer
-function parseInteger(buf) {
-    let pos = 0;
-    const end = buf.length;
-    let val = buf[pos];
-    const neg = val > 0x7f;
-    // Consume any padding bytes
-    const pad = neg ? 0xff : 0x00;
-    while (val == pad && ++pos < end) {
-        val = buf[pos];
-    }
-    // Calculate remaining bytes to read
-    const len = end - pos;
-    if (len === 0)
-        return BigInt(neg ? -1 : 0);
-    // Handle two's complement for negative numbers
-    val = neg ? val - 256 : val;
-    // Parse remaining bytes
-    let n = BigInt(val);
-    for (let i = pos + 1; i < end; ++i) {
-        n = n * BigInt(256) + BigInt(buf[i]);
-    }
-    return n;
-}
-// Parse an ASCII string from the DER-encoded buffer
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean
-function parseStringASCII(buf) {
-    return buf.toString('ascii');
-}
-// Parse a Date from the DER-encoded buffer
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1
-function parseTime(buf, shortYear) {
-    const timeStr = parseStringASCII(buf);
-    // Parse the time string into matches - captured groups start at index 1
-    const m = shortYear
-        ? RE_TIME_SHORT_YEAR.exec(timeStr)
-        : RE_TIME_LONG_YEAR.exec(timeStr);
-    if (!m) {
-        throw new Error('invalid time');
-    }
-    // Translate dates with a 2-digit year to 4 digits per the spec
-    if (shortYear) {
-        let year = Number(m[1]);
-        year += year >= 50 ? 1900 : 2000;
-        m[1] = year.toString();
-    }
-    // Translate to ISO8601 format and parse
-    return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`);
+const http2_1 = __nccwpck_require__(85675);
+const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310));
+const proc_log_1 = __nccwpck_require__(26687);
+const promise_retry_1 = __importDefault(__nccwpck_require__(90390));
+const util_1 = __nccwpck_require__(19100);
+const error_1 = __nccwpck_require__(40369);
+const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants;
+async function fetchWithRetry(url, options) {
+    return (0, promise_retry_1.default)(async (retry, attemptNum) => {
+        const method = options.method || 'POST';
+        const headers = {
+            [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(),
+            ...options.headers,
+        };
+        const response = await (0, make_fetch_happen_1.default)(url, {
+            method,
+            headers,
+            body: options.body,
+            timeout: options.timeout,
+            retry: false, // We're handling retries ourselves
+        }).catch((reason) => {
+            proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`);
+            return retry(reason);
+        });
+        if (response.ok) {
+            return response;
+        }
+        else {
+            const error = await errorFromResponse(response);
+            proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`);
+            if (retryable(response.status)) {
+                return retry(error);
+            }
+            else {
+                throw error;
+            }
+        }
+    }, retryOpts(options.retry));
 }
-// Parse an OID from the DER-encoded buffer
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier
-function parseOID(buf) {
-    let pos = 0;
-    const end = buf.length;
-    // Consume first byte which encodes the first two OID components
-    let n = buf[pos++];
-    const first = Math.floor(n / 40);
-    const second = n % 40;
-    let oid = `${first}.${second}`;
-    // Consume remaining bytes
-    let val = 0;
-    for (; pos < end; ++pos) {
-        n = buf[pos];
-        val = (val << 7) + (n & 0x7f);
-        // If the left-most bit is NOT set, then this is the last byte in the
-        // sequence and we can add the value to the OID and reset the accumulator
-        if ((n & 0x80) === 0) {
-            oid += `.${val}`;
-            val = 0;
+// Translate a Response into an HTTPError instance. This will attempt to parse
+// the response body for a message, but will default to the statusText if none
+// is found.
+const errorFromResponse = async (response) => {
+    let message = response.statusText;
+    const location = response.headers.get(HTTP2_HEADER_LOCATION) || undefined;
+    const contentType = response.headers.get(HTTP2_HEADER_CONTENT_TYPE);
+    // If response type is JSON, try to parse the body for a message
+    if (contentType?.includes('application/json')) {
+        try {
+            const body = await response.json();
+            message = body.message || message;
+        }
+        catch (e) {
+            // ignore
         }
     }
-    return oid;
-}
-// Parse a boolean from the DER-encoded buffer
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean
-function parseBoolean(buf) {
-    return buf[0] !== 0;
-}
-// Parse a bit string from the DER-encoded buffer
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string
-function parseBitString(buf) {
-    // First byte tell us how many unused bits are in the last byte
-    const unused = buf[0];
-    const start = 1;
-    const end = buf.length;
-    const bits = [];
-    for (let i = start; i < end; ++i) {
-        const byte = buf[i];
-        // The skip value is only used for the last byte
-        const skip = i === end - 1 ? unused : 0;
-        // Iterate over each bit in the byte (most significant first)
-        for (let j = 7; j >= skip; --j) {
-            // Read the bit and add it to the bit string
-            bits.push((byte >> j) & 0x01);
-        }
+    return new error_1.HTTPError({
+        status: response.status,
+        message: message,
+        location: location,
+    });
+};
+// Determine if a status code is retryable. This includes 5xx errors, 408, and
+// 429.
+const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR;
+// Normalize the retry options to the format expected by promise-retry
+const retryOpts = (retry) => {
+    if (typeof retry === 'boolean') {
+        return { retries: retry ? 1 : 0 };
     }
-    return bits;
-}
+    else if (typeof retry === 'number') {
+        return { retries: retry };
+    }
+    else {
+        return { retries: 0, ...retry };
+    }
+};
 
 
 /***/ }),
 
-/***/ 59343:
+/***/ 26819:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ASN1Tag = void 0;
+exports.Fulcio = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15515,91 +15610,40 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const error_1 = __nccwpck_require__(11121);
-const UNIVERSAL_TAG = {
-    BOOLEAN: 0x01,
-    INTEGER: 0x02,
-    BIT_STRING: 0x03,
-    OCTET_STRING: 0x04,
-    OBJECT_IDENTIFIER: 0x06,
-    SEQUENCE: 0x10,
-    SET: 0x11,
-    PRINTABLE_STRING: 0x13,
-    UTC_TIME: 0x17,
-    GENERALIZED_TIME: 0x18,
-};
-const TAG_CLASS = {
-    UNIVERSAL: 0x00,
-    APPLICATION: 0x01,
-    CONTEXT_SPECIFIC: 0x02,
-    PRIVATE: 0x03,
-};
-// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes
-class ASN1Tag {
-    constructor(enc) {
-        // Bits 0 through 4 are the tag number
-        this.number = enc & 0x1f;
-        // Bit 5 is the constructed bit
-        this.constructed = (enc & 0x20) === 0x20;
-        // Bit 6 & 7 are the class
-        this.class = enc >> 6;
-        if (this.number === 0x1f) {
-            throw new error_1.ASN1ParseError('long form tags not supported');
-        }
-        if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) {
-            throw new error_1.ASN1ParseError('unsupported tag 0x00');
-        }
-    }
-    isUniversal() {
-        return this.class === TAG_CLASS.UNIVERSAL;
-    }
-    isContextSpecific(num) {
-        const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC;
-        return num !== undefined ? res && this.number === num : res;
-    }
-    isBoolean() {
-        return this.isUniversal() && this.number === UNIVERSAL_TAG.BOOLEAN;
-    }
-    isInteger() {
-        return this.isUniversal() && this.number === UNIVERSAL_TAG.INTEGER;
-    }
-    isBitString() {
-        return this.isUniversal() && this.number === UNIVERSAL_TAG.BIT_STRING;
-    }
-    isOctetString() {
-        return this.isUniversal() && this.number === UNIVERSAL_TAG.OCTET_STRING;
-    }
-    isOID() {
-        return (this.isUniversal() && this.number === UNIVERSAL_TAG.OBJECT_IDENTIFIER);
-    }
-    isUTCTime() {
-        return this.isUniversal() && this.number === UNIVERSAL_TAG.UTC_TIME;
-    }
-    isGeneralizedTime() {
-        return this.isUniversal() && this.number === UNIVERSAL_TAG.GENERALIZED_TIME;
+const fetch_1 = __nccwpck_require__(9823);
+/**
+ * Fulcio API client.
+ */
+class Fulcio {
+    constructor(options) {
+        this.options = options;
     }
-    toDER() {
-        return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6);
+    async createSigningCertificate(request) {
+        const { baseURL, retry, timeout } = this.options;
+        const url = `${baseURL}/api/v2/signingCert`;
+        const response = await (0, fetch_1.fetchWithRetry)(url, {
+            headers: {
+                'Content-Type': 'application/json',
+            },
+            body: JSON.stringify(request),
+            timeout,
+            retry,
+        });
+        return response.json();
     }
 }
-exports.ASN1Tag = ASN1Tag;
+exports.Fulcio = Fulcio;
 
 
 /***/ }),
 
-/***/ 69368:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 32688:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createPublicKey = createPublicKey;
-exports.digest = digest;
-exports.verify = verify;
-exports.bufferEqual = bufferEqual;
+exports.Rekor = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15615,53 +15659,79 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const crypto_1 = __importDefault(__nccwpck_require__(76982));
-function createPublicKey(key, type = 'spki') {
-    if (typeof key === 'string') {
-        return crypto_1.default.createPublicKey(key);
-    }
-    else {
-        return crypto_1.default.createPublicKey({ key, format: 'der', type: type });
-    }
-}
-function digest(algorithm, ...data) {
-    const hash = crypto_1.default.createHash(algorithm);
-    for (const d of data) {
-        hash.update(d);
+const fetch_1 = __nccwpck_require__(9823);
+/**
+ * Rekor API client.
+ */
+class Rekor {
+    constructor(options) {
+        this.options = options;
     }
-    return hash.digest();
-}
-function verify(data, key, signature, algorithm) {
-    // The try/catch is to work around an issue in Node 14.x where verify throws
-    // an error in some scenarios if the signature is invalid.
-    try {
-        return crypto_1.default.verify(algorithm, data, key, signature);
+    /**
+     * Create a new entry in the Rekor log.
+     * @param propsedEntry {ProposedEntry} Data to create a new entry
+     * @returns {Promise} The created entry
+     */
+    async createEntry(propsedEntry) {
+        const { baseURL, timeout, retry } = this.options;
+        const url = `${baseURL}/api/v1/log/entries`;
+        const response = await (0, fetch_1.fetchWithRetry)(url, {
+            headers: {
+                'Content-Type': 'application/json',
+                Accept: 'application/json',
+            },
+            body: JSON.stringify(propsedEntry),
+            timeout,
+            retry,
+        });
+        const data = await response.json();
+        return entryFromResponse(data);
     }
-    catch (e) {
-        /* istanbul ignore next */
-        return false;
+    /**
+     * Get an entry from the Rekor log.
+     * @param uuid {string} The UUID of the entry to retrieve
+     * @returns {Promise} The retrieved entry
+     */
+    async getEntry(uuid) {
+        const { baseURL, timeout, retry } = this.options;
+        const url = `${baseURL}/api/v1/log/entries/${uuid}`;
+        const response = await (0, fetch_1.fetchWithRetry)(url, {
+            method: 'GET',
+            headers: {
+                Accept: 'application/json',
+            },
+            timeout,
+            retry,
+        });
+        const data = await response.json();
+        return entryFromResponse(data);
     }
 }
-function bufferEqual(a, b) {
-    try {
-        return crypto_1.default.timingSafeEqual(a, b);
-    }
-    catch {
-        /* istanbul ignore next */
-        return false;
+exports.Rekor = Rekor;
+// Unpack the response from the Rekor API into a more convenient format.
+function entryFromResponse(data) {
+    const entries = Object.entries(data);
+    if (entries.length != 1) {
+        throw new Error('Received multiple entries in Rekor response');
     }
+    // Grab UUID and entry data from the response
+    const [uuid, entry] = entries[0];
+    return {
+        ...entry,
+        uuid,
+    };
 }
 
 
 /***/ }),
 
-/***/ 49032:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 78963:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.preAuthEncoding = preAuthEncoding;
+exports.TimestampAuthority = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15677,30 +15747,40 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const PAE_PREFIX = 'DSSEv1';
-// DSSE Pre-Authentication Encoding
-function preAuthEncoding(payloadType, payload) {
-    const prefix = [
-        PAE_PREFIX,
-        payloadType.length,
-        payloadType,
-        payload.length,
-        '',
-    ].join(' ');
-    return Buffer.concat([Buffer.from(prefix, 'ascii'), payload]);
+const fetch_1 = __nccwpck_require__(9823);
+class TimestampAuthority {
+    constructor(options) {
+        this.options = options;
+    }
+    async createTimestamp(request) {
+        const { baseURL, timeout, retry } = this.options;
+        const url = `${baseURL}/api/v1/timestamp`;
+        const response = await (0, fetch_1.fetchWithRetry)(url, {
+            headers: {
+                'Content-Type': 'application/json',
+            },
+            body: JSON.stringify(request),
+            timeout,
+            retry,
+        });
+        return response.buffer();
+    }
 }
+exports.TimestampAuthority = TimestampAuthority;
 
 
 /***/ }),
 
-/***/ 52788:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 92092:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.base64Encode = base64Encode;
-exports.base64Decode = base64Decode;
+exports.CIContextProvider = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15716,48 +15796,69 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const BASE64_ENCODING = 'base64';
-const UTF8_ENCODING = 'utf-8';
-function base64Encode(str) {
-    return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING);
+const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310));
+// Collection of all the CI-specific providers we have implemented
+const providers = [getGHAToken, getEnv];
+/**
+ * CIContextProvider is a composite identity provider which will iterate
+ * over all of the CI-specific providers and return the token from the first
+ * one that resolves.
+ */
+class CIContextProvider {
+    /* istanbul ignore next */
+    constructor(audience = 'sigstore') {
+        this.audience = audience;
+    }
+    // Invoke all registered ProviderFuncs and return the value of whichever one
+    // resolves first.
+    async getToken() {
+        return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available'));
+    }
 }
-function base64Decode(str) {
-    return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING);
+exports.CIContextProvider = CIContextProvider;
+/**
+ * getGHAToken can retrieve an OIDC token when running in a GitHub Actions
+ * workflow
+ */
+async function getGHAToken(audience) {
+    // Check to see if we're running in GitHub Actions
+    if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||
+        !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) {
+        return Promise.reject('no token available');
+    }
+    // Construct URL to request token w/ appropriate audience
+    const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);
+    url.searchParams.append('audience', audience);
+    const response = await (0, make_fetch_happen_1.default)(url.href, {
+        retry: 2,
+        headers: {
+            Accept: 'application/json',
+            Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`,
+        },
+    });
+    return response.json().then((data) => data.value);
+}
+/**
+ * getEnv can retrieve an OIDC token from an environment variable.
+ * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar
+ */
+async function getEnv() {
+    if (!process.env.SIGSTORE_ID_TOKEN) {
+        return Promise.reject('no token available');
+    }
+    return process.env.SIGSTORE_ID_TOKEN;
 }
 
 
 /***/ }),
 
-/***/ 83917:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 55022:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = exports.ByteStream = exports.RFC3161Timestamp = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = exports.ASN1Obj = void 0;
+exports.CIContextProvider = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15773,30 +15874,44 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-var asn1_1 = __nccwpck_require__(86027);
-Object.defineProperty(exports, "ASN1Obj", ({ enumerable: true, get: function () { return asn1_1.ASN1Obj; } }));
-exports.crypto = __importStar(__nccwpck_require__(69368));
-exports.dsse = __importStar(__nccwpck_require__(49032));
-exports.encoding = __importStar(__nccwpck_require__(52788));
-exports.json = __importStar(__nccwpck_require__(13327));
-exports.pem = __importStar(__nccwpck_require__(1055));
-var rfc3161_1 = __nccwpck_require__(20994);
-Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return rfc3161_1.RFC3161Timestamp; } }));
-var stream_1 = __nccwpck_require__(1673);
-Object.defineProperty(exports, "ByteStream", ({ enumerable: true, get: function () { return stream_1.ByteStream; } }));
-var x509_1 = __nccwpck_require__(49358);
-Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return x509_1.EXTENSION_OID_SCT; } }));
-Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return x509_1.X509Certificate; } }));
-Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return x509_1.X509SCTExtension; } }));
+var ci_1 = __nccwpck_require__(92092);
+Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return ci_1.CIContextProvider; } }));
 
 
 /***/ }),
 
-/***/ 13327:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 15179:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0;
+var bundler_1 = __nccwpck_require__(35530);
+Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } }));
+Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } }));
+var error_1 = __nccwpck_require__(97841);
+Object.defineProperty(exports, "InternalError", ({ enumerable: true, get: function () { return error_1.InternalError; } }));
+var identity_1 = __nccwpck_require__(55022);
+Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return identity_1.CIContextProvider; } }));
+var signer_1 = __nccwpck_require__(34342);
+Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } }));
+Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return signer_1.FulcioSigner; } }));
+var witness_1 = __nccwpck_require__(55383);
+Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } }));
+Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return witness_1.RekorWitness; } }));
+Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return witness_1.TSAWitness; } }));
+
+
+/***/ }),
+
+/***/ 5875:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.CAClient = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15812,84 +15927,61 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.canonicalize = canonicalize;
-// JSON canonicalization per https://github.com/cyberphone/json-canonicalization
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function canonicalize(object) {
-    let buffer = '';
-    if (object === null || typeof object !== 'object' || object.toJSON != null) {
-        // Primitives or toJSONable objects
-        buffer += JSON.stringify(object);
-    }
-    else if (Array.isArray(object)) {
-        // Array - maintain element order
-        buffer += '[';
-        let first = true;
-        object.forEach((element) => {
-            if (!first) {
-                buffer += ',';
-            }
-            first = false;
-            // recursive call
-            buffer += canonicalize(element);
+const error_1 = __nccwpck_require__(97841);
+const fulcio_1 = __nccwpck_require__(26819);
+class CAClient {
+    constructor(options) {
+        this.fulcio = new fulcio_1.Fulcio({
+            baseURL: options.fulcioBaseURL,
+            retry: options.retry,
+            timeout: options.timeout,
         });
-        buffer += ']';
     }
-    else {
-        // Object - Sort properties before serializing
-        buffer += '{';
-        let first = true;
-        Object.keys(object)
-            .sort()
-            .forEach((property) => {
-            if (!first) {
-                buffer += ',';
-            }
-            first = false;
-            buffer += JSON.stringify(property);
-            buffer += ':';
-            // recursive call
-            buffer += canonicalize(object[property]);
-        });
-        buffer += '}';
+    async createSigningCertificate(identityToken, publicKey, challenge) {
+        const request = toCertificateRequest(identityToken, publicKey, challenge);
+        try {
+            const resp = await this.fulcio.createSigningCertificate(request);
+            // Account for the fact that the response may contain either a
+            // signedCertificateEmbeddedSct or a signedCertificateDetachedSct.
+            const cert = resp.signedCertificateEmbeddedSct
+                ? resp.signedCertificateEmbeddedSct
+                : resp.signedCertificateDetachedSct;
+            return cert.chain.certificates;
+        }
+        catch (err) {
+            (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate');
+        }
     }
-    return buffer;
+}
+exports.CAClient = CAClient;
+function toCertificateRequest(identityToken, publicKey, challenge) {
+    return {
+        credentials: {
+            oidcIdentityToken: identityToken,
+        },
+        publicKeyRequest: {
+            publicKey: {
+                algorithm: 'ECDSA',
+                content: publicKey,
+            },
+            proofOfPossession: challenge.toString('base64'),
+        },
+    };
 }
 
 
 /***/ }),
 
-/***/ 91817:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SHA2_HASH_ALGOS = exports.ECDSA_SIGNATURE_ALGOS = void 0;
-exports.ECDSA_SIGNATURE_ALGOS = {
-    '1.2.840.10045.4.3.1': 'sha224',
-    '1.2.840.10045.4.3.2': 'sha256',
-    '1.2.840.10045.4.3.3': 'sha384',
-    '1.2.840.10045.4.3.4': 'sha512',
-};
-exports.SHA2_HASH_ALGOS = {
-    '2.16.840.1.101.3.4.2.1': 'sha256',
-    '2.16.840.1.101.3.4.2.2': 'sha384',
-    '2.16.840.1.101.3.4.2.3': 'sha512',
-};
-
-
-/***/ }),
-
-/***/ 1055:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 97064:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toDER = toDER;
-exports.fromDER = fromDER;
+exports.EphemeralSigner = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15905,41 +15997,41 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const PEM_HEADER = /-----BEGIN (.*)-----/;
-const PEM_FOOTER = /-----END (.*)-----/;
-function toDER(certificate) {
-    let der = '';
-    certificate.split('\n').forEach((line) => {
-        if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) {
-            return;
-        }
-        der += line;
-    });
-    return Buffer.from(der, 'base64');
-}
-// Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM
-// encoding dictates that each certificate should have a trailing newline after
-// the footer.
-function fromDER(certificate, type = 'CERTIFICATE') {
-    // Base64-encode the certificate.
-    const der = certificate.toString('base64');
-    // Split the certificate into lines of 64 characters.
-    const lines = der.match(/.{1,64}/g) || '';
-    return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`]
-        .join('\n')
-        .concat('\n');
+const crypto_1 = __importDefault(__nccwpck_require__(76982));
+const EC_KEYPAIR_TYPE = 'ec';
+const P256_CURVE = 'P-256';
+// Signer implementation which uses an ephemeral keypair to sign artifacts.
+// The private key lives only in memory and is tied to the lifetime of the
+// EphemeralSigner instance.
+class EphemeralSigner {
+    constructor() {
+        this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, {
+            namedCurve: P256_CURVE,
+        });
+    }
+    async sign(data) {
+        const signature = crypto_1.default.sign(null, data, this.keypair.privateKey);
+        const publicKey = this.keypair.publicKey
+            .export({ format: 'pem', type: 'spki' })
+            .toString('ascii');
+        return {
+            signature: signature,
+            key: { $case: 'publicKey', publicKey },
+        };
+    }
 }
+exports.EphemeralSigner = EphemeralSigner;
 
 
 /***/ }),
 
-/***/ 97512:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 26303:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RFC3161TimestampVerificationError = void 0;
+exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15955,18 +16047,87 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-class RFC3161TimestampVerificationError extends Error {
+const error_1 = __nccwpck_require__(97841);
+const util_1 = __nccwpck_require__(19100);
+const ca_1 = __nccwpck_require__(5875);
+const ephemeral_1 = __nccwpck_require__(97064);
+exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev';
+// Signer implementation which can be used to decorate another signer
+// with a Fulcio-issued signing certificate for the signer's public key.
+// Must be instantiated with an identity provider which can provide a JWT
+// which represents the identity to be bound to the signing certificate.
+class FulcioSigner {
+    constructor(options) {
+        this.ca = new ca_1.CAClient({
+            ...options,
+            fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL,
+        });
+        this.identityProvider = options.identityProvider;
+        this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner();
+    }
+    async sign(data) {
+        // Retrieve identity token from the supplied identity provider
+        const identityToken = await this.getIdentityToken();
+        // Extract challenge claim from OIDC token
+        let subject;
+        try {
+            subject = util_1.oidc.extractJWTSubject(identityToken);
+        }
+        catch (err) {
+            throw new error_1.InternalError({
+                code: 'IDENTITY_TOKEN_PARSE_ERROR',
+                message: `invalid identity token: ${identityToken}`,
+                cause: err,
+            });
+        }
+        // Construct challenge value by signing the subject claim
+        const challenge = await this.keyHolder.sign(Buffer.from(subject));
+        if (challenge.key.$case !== 'publicKey') {
+            throw new error_1.InternalError({
+                code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR',
+                message: 'unexpected format for signing key',
+            });
+        }
+        // Create signing certificate
+        const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature);
+        // Generate artifact signature
+        const signature = await this.keyHolder.sign(data);
+        // Specifically returning only the first certificate in the chain
+        // as the key.
+        return {
+            signature: signature.signature,
+            key: {
+                $case: 'x509Certificate',
+                certificate: certificates[0],
+            },
+        };
+    }
+    async getIdentityToken() {
+        try {
+            return await this.identityProvider.getToken();
+        }
+        catch (err) {
+            throw new error_1.InternalError({
+                code: 'IDENTITY_TOKEN_READ_ERROR',
+                message: 'error retrieving identity token',
+                cause: err,
+            });
+        }
+    }
 }
-exports.RFC3161TimestampVerificationError = RFC3161TimestampVerificationError;
+exports.FulcioSigner = FulcioSigner;
 
 
 /***/ }),
 
-/***/ 20994:
+/***/ 34342:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
+/* istanbul ignore file */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -15982,15 +16143,14 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RFC3161Timestamp = void 0;
-var timestamp_1 = __nccwpck_require__(92714);
-Object.defineProperty(exports, "RFC3161Timestamp", ({ enumerable: true, get: function () { return timestamp_1.RFC3161Timestamp; } }));
+var fulcio_1 = __nccwpck_require__(26303);
+Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } }));
+Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return fulcio_1.FulcioSigner; } }));
 
 
 /***/ }),
 
-/***/ 92714:
+/***/ 19100:
 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
@@ -16019,7 +16179,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
     return result;
 };
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RFC3161Timestamp = void 0;
+exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -16035,246 +16195,66 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const asn1_1 = __nccwpck_require__(86027);
-const crypto = __importStar(__nccwpck_require__(69368));
-const oid_1 = __nccwpck_require__(91817);
-const error_1 = __nccwpck_require__(97512);
-const tstinfo_1 = __nccwpck_require__(62925);
-const OID_PKCS9_CONTENT_TYPE_SIGNED_DATA = '1.2.840.113549.1.7.2';
-const OID_PKCS9_CONTENT_TYPE_TSTINFO = '1.2.840.113549.1.9.16.1.4';
-const OID_PKCS9_MESSAGE_DIGEST_KEY = '1.2.840.113549.1.9.4';
-class RFC3161Timestamp {
-    constructor(asn1) {
-        this.root = asn1;
-    }
-    static parse(der) {
-        const asn1 = asn1_1.ASN1Obj.parseBuffer(der);
-        return new RFC3161Timestamp(asn1);
-    }
-    get status() {
-        return this.pkiStatusInfoObj.subs[0].toInteger();
-    }
-    get contentType() {
-        return this.contentTypeObj.toOID();
-    }
-    get eContentType() {
-        return this.eContentTypeObj.toOID();
-    }
-    get signingTime() {
-        return this.tstInfo.genTime;
-    }
-    get signerIssuer() {
-        return this.signerSidObj.subs[0].value;
-    }
-    get signerSerialNumber() {
-        return this.signerSidObj.subs[1].value;
-    }
-    get signerDigestAlgorithm() {
-        const oid = this.signerDigestAlgorithmObj.subs[0].toOID();
-        return oid_1.SHA2_HASH_ALGOS[oid];
-    }
-    get signatureAlgorithm() {
-        const oid = this.signatureAlgorithmObj.subs[0].toOID();
-        return oid_1.ECDSA_SIGNATURE_ALGOS[oid];
-    }
-    get signatureValue() {
-        return this.signatureValueObj.value;
-    }
-    get tstInfo() {
-        // Need to unpack tstInfo from an OCTET STRING
-        return new tstinfo_1.TSTInfo(this.eContentObj.subs[0].subs[0]);
-    }
-    verify(data, publicKey) {
-        if (!this.timeStampTokenObj) {
-            throw new error_1.RFC3161TimestampVerificationError('timeStampToken is missing');
-        }
-        // Check for expected ContentInfo content type
-        if (this.contentType !== OID_PKCS9_CONTENT_TYPE_SIGNED_DATA) {
-            throw new error_1.RFC3161TimestampVerificationError(`incorrect content type: ${this.contentType}`);
-        }
-        // Check for expected encapsulated content type
-        if (this.eContentType !== OID_PKCS9_CONTENT_TYPE_TSTINFO) {
-            throw new error_1.RFC3161TimestampVerificationError(`incorrect encapsulated content type: ${this.eContentType}`);
-        }
-        // Check that the tstInfo references the correct artifact
-        this.tstInfo.verify(data);
-        // Check that the signed message digest matches the tstInfo
-        this.verifyMessageDigest();
-        // Check that the signature is valid for the signed attributes
-        this.verifySignature(publicKey);
-    }
-    verifyMessageDigest() {
-        // Check that the tstInfo matches the signed data
-        const tstInfoDigest = crypto.digest(this.signerDigestAlgorithm, this.tstInfo.raw);
-        const expectedDigest = this.messageDigestAttributeObj.subs[1].subs[0].value;
-        if (!crypto.bufferEqual(tstInfoDigest, expectedDigest)) {
-            throw new error_1.RFC3161TimestampVerificationError('signed data does not match tstInfo');
-        }
-    }
-    verifySignature(key) {
-        // Encode the signed attributes for verification
-        const signedAttrs = this.signedAttrsObj.toDER();
-        signedAttrs[0] = 0x31; // Change context-specific tag to SET
-        // Check that the signature is valid for the signed attributes
-        const verified = crypto.verify(signedAttrs, key, this.signatureValue, this.signatureAlgorithm);
-        if (!verified) {
-            throw new error_1.RFC3161TimestampVerificationError('signature verification failed');
-        }
-    }
-    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
-    get pkiStatusInfoObj() {
-        // pkiStatusInfo is the first element of the timestamp response sequence
-        return this.root.subs[0];
-    }
-    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
-    get timeStampTokenObj() {
-        // timeStampToken is the first element of the timestamp response sequence
-        return this.root.subs[1];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-3
-    get contentTypeObj() {
-        return this.timeStampTokenObj.subs[0];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5652#section-3
-    get signedDataObj() {
-        const obj = this.timeStampTokenObj.subs.find((sub) => sub.tag.isContextSpecific(0x00));
-        return obj.subs[0];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1
-    get encapContentInfoObj() {
-        return this.signedDataObj.subs[2];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.1
-    get signerInfosObj() {
-        // SignerInfos is the last element of the signed data sequence
-        const sd = this.signedDataObj;
-        return sd.subs[sd.subs.length - 1];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5652#section-5.1
-    get signerInfoObj() {
-        // Only supporting one signer
-        return this.signerInfosObj.subs[0];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2
-    get eContentTypeObj() {
-        return this.encapContentInfoObj.subs[0];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.2
-    get eContentObj() {
-        return this.encapContentInfoObj.subs[1];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
-    get signedAttrsObj() {
-        const signedAttrs = this.signerInfoObj.subs.find((sub) => sub.tag.isContextSpecific(0x00));
-        return signedAttrs;
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
-    get messageDigestAttributeObj() {
-        const messageDigest = this.signedAttrsObj.subs.find((sub) => sub.subs[0].tag.isOID() &&
-            sub.subs[0].toOID() === OID_PKCS9_MESSAGE_DIGEST_KEY);
-        return messageDigest;
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
-    get signerSidObj() {
-        return this.signerInfoObj.subs[1];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
-    get signerDigestAlgorithmObj() {
-        // Signature is the 2nd element of the signerInfoObj object
-        return this.signerInfoObj.subs[2];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
-    get signatureAlgorithmObj() {
-        // Signature is the 4th element of the signerInfoObj object
-        return this.signerInfoObj.subs[4];
-    }
-    // https://datatracker.ietf.org/doc/html/rfc5652#section-5.3
-    get signatureValueObj() {
-        // Signature is the 6th element of the signerInfoObj object
-        return this.signerInfoObj.subs[5];
-    }
-}
-exports.RFC3161Timestamp = RFC3161Timestamp;
+var core_1 = __nccwpck_require__(83917);
+Object.defineProperty(exports, "crypto", ({ enumerable: true, get: function () { return core_1.crypto; } }));
+Object.defineProperty(exports, "dsse", ({ enumerable: true, get: function () { return core_1.dsse; } }));
+Object.defineProperty(exports, "encoding", ({ enumerable: true, get: function () { return core_1.encoding; } }));
+Object.defineProperty(exports, "json", ({ enumerable: true, get: function () { return core_1.json; } }));
+Object.defineProperty(exports, "pem", ({ enumerable: true, get: function () { return core_1.pem; } }));
+exports.oidc = __importStar(__nccwpck_require__(81963));
+exports.ua = __importStar(__nccwpck_require__(81268));
 
 
 /***/ }),
 
-/***/ 62925:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 81963:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TSTInfo = void 0;
-const crypto = __importStar(__nccwpck_require__(69368));
-const oid_1 = __nccwpck_require__(91817);
-const error_1 = __nccwpck_require__(97512);
-class TSTInfo {
-    constructor(asn1) {
-        this.root = asn1;
-    }
-    get version() {
-        return this.root.subs[0].toInteger();
-    }
-    get genTime() {
-        return this.root.subs[4].toDate();
-    }
-    get messageImprintHashAlgorithm() {
-        const oid = this.messageImprintObj.subs[0].subs[0].toOID();
-        return oid_1.SHA2_HASH_ALGOS[oid];
-    }
-    get messageImprintHashedMessage() {
-        return this.messageImprintObj.subs[1].value;
-    }
-    get raw() {
-        return this.root.toDER();
-    }
-    verify(data) {
-        const digest = crypto.digest(this.messageImprintHashAlgorithm, data);
-        if (!crypto.bufferEqual(digest, this.messageImprintHashedMessage)) {
-            throw new error_1.RFC3161TimestampVerificationError('message imprint does not match artifact');
-        }
-    }
-    // https://www.rfc-editor.org/rfc/rfc3161#section-2.4.2
-    get messageImprintObj() {
-        return this.root.subs[2];
+exports.extractJWTSubject = extractJWTSubject;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const core_1 = __nccwpck_require__(83917);
+function extractJWTSubject(jwt) {
+    const parts = jwt.split('.', 3);
+    const payload = JSON.parse(core_1.encoding.base64Decode(parts[1]));
+    switch (payload.iss) {
+        case 'https://accounts.google.com':
+        case 'https://oauth2.sigstore.dev/auth':
+            return payload.email;
+        default:
+            return payload.sub;
     }
 }
-exports.TSTInfo = TSTInfo;
 
 
 /***/ }),
 
-/***/ 1673:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 81268:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ByteStream = void 0;
+exports.getUserAgent = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -16290,137 +16270,29 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-class StreamError extends Error {
-}
-class ByteStream {
-    constructor(buffer) {
-        this.start = 0;
-        if (buffer) {
-            this.buf = buffer;
-            this.view = Buffer.from(buffer);
-        }
-        else {
-            this.buf = new ArrayBuffer(0);
-            this.view = Buffer.from(this.buf);
-        }
-    }
-    get buffer() {
-        return this.view.subarray(0, this.start);
-    }
-    get length() {
-        return this.view.byteLength;
-    }
-    get position() {
-        return this.start;
-    }
-    seek(position) {
-        this.start = position;
-    }
-    // Returns a Buffer containing the specified number of bytes starting at the
-    // given start position.
-    slice(start, len) {
-        const end = start + len;
-        if (end > this.length) {
-            throw new StreamError('request past end of buffer');
-        }
-        return this.view.subarray(start, end);
-    }
-    appendChar(char) {
-        this.ensureCapacity(1);
-        this.view[this.start] = char;
-        this.start += 1;
-    }
-    appendUint16(num) {
-        this.ensureCapacity(2);
-        const value = new Uint16Array([num]);
-        const view = new Uint8Array(value.buffer);
-        this.view[this.start] = view[1];
-        this.view[this.start + 1] = view[0];
-        this.start += 2;
-    }
-    appendUint24(num) {
-        this.ensureCapacity(3);
-        const value = new Uint32Array([num]);
-        const view = new Uint8Array(value.buffer);
-        this.view[this.start] = view[2];
-        this.view[this.start + 1] = view[1];
-        this.view[this.start + 2] = view[0];
-        this.start += 3;
-    }
-    appendView(view) {
-        this.ensureCapacity(view.length);
-        this.view.set(view, this.start);
-        this.start += view.length;
-    }
-    getBlock(size) {
-        if (size <= 0) {
-            return Buffer.alloc(0);
-        }
-        if (this.start + size > this.view.length) {
-            throw new Error('request past end of buffer');
-        }
-        const result = this.view.subarray(this.start, this.start + size);
-        this.start += size;
-        return result;
-    }
-    getUint8() {
-        return this.getBlock(1)[0];
-    }
-    getUint16() {
-        const block = this.getBlock(2);
-        return (block[0] << 8) | block[1];
-    }
-    ensureCapacity(size) {
-        if (this.start + size > this.view.byteLength) {
-            const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0);
-            this.realloc(this.view.byteLength + blockSize);
-        }
-    }
-    realloc(size) {
-        const newArray = new ArrayBuffer(size);
-        const newView = Buffer.from(newArray);
-        // Copy the old buffer into the new one
-        newView.set(this.view);
-        this.buf = newArray;
-        this.view = newView;
-    }
-}
-exports.ByteStream = ByteStream;
-ByteStream.BLOCK_SIZE = 1024;
+const os_1 = __importDefault(__nccwpck_require__(70857));
+// Format User-Agent:  /  ()
+// source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
+const getUserAgent = () => {
+    const packageVersion = (__nccwpck_require__(85896)/* .version */ .rE);
+    const nodeVersion = process.version;
+    const platformName = os_1.default.platform();
+    const archName = os_1.default.arch();
+    return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`;
+};
+exports.getUserAgent = getUserAgent;
 
 
 /***/ }),
 
-/***/ 83566:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 55383:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
+/* istanbul ignore file */
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0;
+exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -16436,357 +16308,383 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-const asn1_1 = __nccwpck_require__(86027);
-const crypto = __importStar(__nccwpck_require__(69368));
-const oid_1 = __nccwpck_require__(91817);
-const pem = __importStar(__nccwpck_require__(1055));
-const ext_1 = __nccwpck_require__(96389);
-const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14';
-const EXTENSION_OID_KEY_USAGE = '2.5.29.15';
-const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17';
-const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19';
-const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35';
-exports.EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2';
-class X509Certificate {
-    constructor(asn1) {
-        this.root = asn1;
-    }
-    static parse(cert) {
-        const der = typeof cert === 'string' ? pem.toDER(cert) : cert;
-        const asn1 = asn1_1.ASN1Obj.parseBuffer(der);
-        return new X509Certificate(asn1);
-    }
-    get tbsCertificate() {
-        return this.tbsCertificateObj;
-    }
-    get version() {
-        // version number is the first element of the version context specific tag
-        const ver = this.versionObj.subs[0].toInteger();
-        return `v${(ver + BigInt(1)).toString()}`;
-    }
-    get serialNumber() {
-        return this.serialNumberObj.value;
-    }
-    get notBefore() {
-        // notBefore is the first element of the validity sequence
-        return this.validityObj.subs[0].toDate();
-    }
-    get notAfter() {
-        // notAfter is the second element of the validity sequence
-        return this.validityObj.subs[1].toDate();
-    }
-    get issuer() {
-        return this.issuerObj.value;
-    }
-    get subject() {
-        return this.subjectObj.value;
-    }
-    get publicKey() {
-        return this.subjectPublicKeyInfoObj.toDER();
-    }
-    get signatureAlgorithm() {
-        const oid = this.signatureAlgorithmObj.subs[0].toOID();
-        return oid_1.ECDSA_SIGNATURE_ALGOS[oid];
-    }
-    get signatureValue() {
-        // Signature value is a bit string, so we need to skip the first byte
-        return this.signatureValueObj.value.subarray(1);
-    }
-    get subjectAltName() {
-        const ext = this.extSubjectAltName;
-        return ext?.uri || /* istanbul ignore next */ ext?.rfc822Name;
-    }
-    get extensions() {
-        // The extension list is the first (and only) element of the extensions
-        // context specific tag
-        /* istanbul ignore next */
-        const extSeq = this.extensionsObj?.subs[0];
-        /* istanbul ignore next */
-        return extSeq?.subs || [];
-    }
-    get extKeyUsage() {
-        const ext = this.findExtension(EXTENSION_OID_KEY_USAGE);
-        return ext ? new ext_1.X509KeyUsageExtension(ext) : undefined;
-    }
-    get extBasicConstraints() {
-        const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS);
-        return ext ? new ext_1.X509BasicConstraintsExtension(ext) : undefined;
-    }
-    get extSubjectAltName() {
-        const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME);
-        return ext ? new ext_1.X509SubjectAlternativeNameExtension(ext) : undefined;
-    }
-    get extAuthorityKeyID() {
-        const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID);
-        return ext ? new ext_1.X509AuthorityKeyIDExtension(ext) : undefined;
-    }
-    get extSubjectKeyID() {
-        const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID);
-        return ext
-            ? new ext_1.X509SubjectKeyIDExtension(ext)
-            : /* istanbul ignore next */ undefined;
-    }
-    get extSCT() {
-        const ext = this.findExtension(exports.EXTENSION_OID_SCT);
-        return ext ? new ext_1.X509SCTExtension(ext) : undefined;
+var tlog_1 = __nccwpck_require__(2566);
+Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } }));
+Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return tlog_1.RekorWitness; } }));
+var tsa_1 = __nccwpck_require__(66936);
+Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return tsa_1.TSAWitness; } }));
+
+
+/***/ }),
+
+/***/ 42815:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TLogClient = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const error_1 = __nccwpck_require__(97841);
+const error_2 = __nccwpck_require__(40369);
+const rekor_1 = __nccwpck_require__(32688);
+class TLogClient {
+    constructor(options) {
+        this.fetchOnConflict = options.fetchOnConflict ?? false;
+        this.rekor = new rekor_1.Rekor({
+            baseURL: options.rekorBaseURL,
+            retry: options.retry,
+            timeout: options.timeout,
+        });
     }
-    get isCA() {
-        const ca = this.extBasicConstraints?.isCA || false;
-        // If the KeyUsage extension is present, keyCertSign must be set
-        if (this.extKeyUsage) {
-            return ca && this.extKeyUsage.keyCertSign;
+    async createEntry(proposedEntry) {
+        let entry;
+        try {
+            entry = await this.rekor.createEntry(proposedEntry);
         }
-        // TODO: test coverage for this case
-        /* istanbul ignore next */
-        return ca;
-    }
-    extension(oid) {
-        const ext = this.findExtension(oid);
-        return ext ? new ext_1.X509Extension(ext) : undefined;
-    }
-    verify(issuerCertificate) {
-        // Use the issuer's public key if provided, otherwise use the subject's
-        const publicKey = issuerCertificate?.publicKey || this.publicKey;
-        const key = crypto.createPublicKey(publicKey);
-        return crypto.verify(this.tbsCertificate.toDER(), key, this.signatureValue, this.signatureAlgorithm);
-    }
-    validForDate(date) {
-        return this.notBefore <= date && date <= this.notAfter;
-    }
-    equals(other) {
-        return this.root.toDER().equals(other.root.toDER());
-    }
-    // Creates a copy of the certificate with a new buffer
-    clone() {
-        const der = this.root.toDER();
-        const clone = Buffer.alloc(der.length);
-        der.copy(clone);
-        return X509Certificate.parse(clone);
-    }
-    findExtension(oid) {
-        // Find the extension with the given OID. The OID will always be the first
-        // element of the extension sequence
-        return this.extensions.find((ext) => ext.subs[0].toOID() === oid);
-    }
-    /////////////////////////////////////////////////////////////////////////////
-    // The following properties use the documented x509 structure to locate the
-    // desired ASN.1 object
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1
-    get tbsCertificateObj() {
-        // tbsCertificate is the first element of the certificate sequence
-        return this.root.subs[0];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2
-    get signatureAlgorithmObj() {
-        // signatureAlgorithm is the second element of the certificate sequence
-        return this.root.subs[1];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3
-    get signatureValueObj() {
-        // signatureValue is the third element of the certificate sequence
-        return this.root.subs[2];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1
-    get versionObj() {
-        // version is the first element of the tbsCertificate sequence
-        return this.tbsCertificateObj.subs[0];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2
-    get serialNumberObj() {
-        // serialNumber is the second element of the tbsCertificate sequence
-        return this.tbsCertificateObj.subs[1];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4
-    get issuerObj() {
-        // issuer is the fourth element of the tbsCertificate sequence
-        return this.tbsCertificateObj.subs[3];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5
-    get validityObj() {
-        // version is the fifth element of the tbsCertificate sequence
-        return this.tbsCertificateObj.subs[4];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6
-    get subjectObj() {
-        // subject is the sixth element of the tbsCertificate sequence
-        return this.tbsCertificateObj.subs[5];
-    }
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7
-    get subjectPublicKeyInfoObj() {
-        // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence
-        return this.tbsCertificateObj.subs[6];
-    }
-    // Extensions can't be located by index because their position varies. Instead,
-    // we need to find the extensions context specific tag
-    // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9
-    get extensionsObj() {
-        return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03));
+        catch (err) {
+            // If the entry already exists, fetch it (if enabled)
+            if (entryExistsError(err) && this.fetchOnConflict) {
+                // Grab the UUID of the existing entry from the location header
+                /* istanbul ignore next */
+                const uuid = err.location.split('/').pop() || '';
+                try {
+                    entry = await this.rekor.getEntry(uuid);
+                }
+                catch (err) {
+                    (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry');
+                }
+            }
+            else {
+                (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry');
+            }
+        }
+        return entry;
     }
 }
-exports.X509Certificate = X509Certificate;
+exports.TLogClient = TLogClient;
+function entryExistsError(value) {
+    return (value instanceof error_2.HTTPError &&
+        value.statusCode === 409 &&
+        value.location !== undefined);
+}
 
 
 /***/ }),
 
-/***/ 96389:
+/***/ 97890:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.X509SCTExtension = exports.X509SubjectKeyIDExtension = exports.X509AuthorityKeyIDExtension = exports.X509SubjectAlternativeNameExtension = exports.X509KeyUsageExtension = exports.X509BasicConstraintsExtension = exports.X509Extension = void 0;
-const stream_1 = __nccwpck_require__(1673);
-const sct_1 = __nccwpck_require__(6144);
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.1
-class X509Extension {
-    constructor(asn1) {
-        this.root = asn1;
-    }
-    get oid() {
-        return this.root.subs[0].toOID();
-    }
-    get critical() {
-        // The critical field is optional and will be the second element of the
-        // extension sequence if present. Default to false if not present.
-        return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false;
-    }
-    get value() {
-        return this.extnValueObj.value;
-    }
-    get valueObj() {
-        return this.extnValueObj;
-    }
-    get extnValueObj() {
-        // The extnValue field will be the last element of the extension sequence
-        return this.root.subs[this.root.subs.length - 1];
+exports.toProposedEntry = toProposedEntry;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const bundle_1 = __nccwpck_require__(61040);
+const util_1 = __nccwpck_require__(19100);
+const SHA256_ALGORITHM = 'sha256';
+function toProposedEntry(content, publicKey, 
+// TODO: Remove this parameter once have completely switched to 'dsse' entries
+entryType = 'dsse') {
+    switch (content.$case) {
+        case 'dsseEnvelope':
+            // TODO: Remove this conditional once have completely ditched "intoto" entries
+            if (entryType === 'intoto') {
+                return toProposedIntotoEntry(content.dsseEnvelope, publicKey);
+            }
+            return toProposedDSSEEntry(content.dsseEnvelope, publicKey);
+        case 'messageSignature':
+            return toProposedHashedRekordEntry(content.messageSignature, publicKey);
     }
 }
-exports.X509Extension = X509Extension;
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9
-class X509BasicConstraintsExtension extends X509Extension {
-    get isCA() {
-        return this.sequence.subs[0]?.toBoolean() ?? false;
-    }
-    get pathLenConstraint() {
-        return this.sequence.subs.length > 1
-            ? this.sequence.subs[1].toInteger()
-            : undefined;
-    }
-    // The extnValue field contains a single sequence wrapping the isCA and
-    // pathLenConstraint.
-    get sequence() {
-        return this.extnValueObj.subs[0];
-    }
+// Returns a properly formatted Rekor "hashedrekord" entry for the given digest
+// and signature
+function toProposedHashedRekordEntry(messageSignature, publicKey) {
+    const hexDigest = messageSignature.messageDigest.digest.toString('hex');
+    const b64Signature = messageSignature.signature.toString('base64');
+    const b64Key = util_1.encoding.base64Encode(publicKey);
+    return {
+        apiVersion: '0.0.1',
+        kind: 'hashedrekord',
+        spec: {
+            data: {
+                hash: {
+                    algorithm: SHA256_ALGORITHM,
+                    value: hexDigest,
+                },
+            },
+            signature: {
+                content: b64Signature,
+                publicKey: {
+                    content: b64Key,
+                },
+            },
+        },
+    };
 }
-exports.X509BasicConstraintsExtension = X509BasicConstraintsExtension;
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3
-class X509KeyUsageExtension extends X509Extension {
-    get digitalSignature() {
-        return this.bitString[0] === 1;
-    }
-    get keyCertSign() {
-        return this.bitString[5] === 1;
-    }
-    get crlSign() {
-        return this.bitString[6] === 1;
-    }
-    // The extnValue field contains a single bit string which is a bit mask
-    // indicating which key usages are enabled.
-    get bitString() {
-        return this.extnValueObj.subs[0].toBitString();
-    }
+// Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope
+// and signature
+function toProposedDSSEEntry(envelope, publicKey) {
+    const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope));
+    const encodedKey = util_1.encoding.base64Encode(publicKey);
+    return {
+        apiVersion: '0.0.1',
+        kind: 'dsse',
+        spec: {
+            proposedContent: {
+                envelope: envelopeJSON,
+                verifiers: [encodedKey],
+            },
+        },
+    };
 }
-exports.X509KeyUsageExtension = X509KeyUsageExtension;
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6
-class X509SubjectAlternativeNameExtension extends X509Extension {
-    get rfc822Name() {
-        return this.findGeneralName(0x01)?.value.toString('ascii');
-    }
-    get uri() {
-        return this.findGeneralName(0x06)?.value.toString('ascii');
-    }
-    // Retrieve the value of an otherName with the given OID.
-    otherName(oid) {
-        const otherName = this.findGeneralName(0x00);
-        if (otherName === undefined) {
-            return undefined;
-        }
-        // The otherName is a sequence containing an OID and a value.
-        // Need to check that the OID matches the one we're looking for.
-        const otherNameOID = otherName.subs[0].toOID();
-        if (otherNameOID !== oid) {
-            return undefined;
-        }
-        // The otherNameValue is a sequence containing the actual value.
-        const otherNameValue = otherName.subs[1];
-        return otherNameValue.subs[0].value.toString('ascii');
-    }
-    findGeneralName(tag) {
-        return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag));
+// Returns a properly formatted Rekor "intoto" entry for the given DSSE
+// envelope and signature
+function toProposedIntotoEntry(envelope, publicKey) {
+    // Calculate the value for the payloadHash field in the Rekor entry
+    const payloadHash = util_1.crypto
+        .digest(SHA256_ALGORITHM, envelope.payload)
+        .toString('hex');
+    // Calculate the value for the hash field in the Rekor entry
+    const envelopeHash = calculateDSSEHash(envelope, publicKey);
+    // Collect values for re-creating the DSSE envelope.
+    // Double-encode payload and signature cause that's what Rekor expects
+    const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64'));
+    const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64'));
+    const keyid = envelope.signatures[0].keyid;
+    const encodedKey = util_1.encoding.base64Encode(publicKey);
+    // Create the envelope portion of the entry. Note the inclusion of the
+    // publicKey in the signature struct is not a standard part of a DSSE
+    // envelope, but is required by Rekor.
+    const dsse = {
+        payloadType: envelope.payloadType,
+        payload: payload,
+        signatures: [{ sig, publicKey: encodedKey }],
+    };
+    // If the keyid is an empty string, Rekor seems to remove it altogether. We
+    // need to do the same here so that we can properly recreate the entry for
+    // verification.
+    if (keyid.length > 0) {
+        dsse.signatures[0].keyid = keyid;
     }
-    // The extnValue field contains a sequence of GeneralNames.
-    get generalNames() {
-        return this.extnValueObj.subs[0].subs;
+    return {
+        apiVersion: '0.0.2',
+        kind: 'intoto',
+        spec: {
+            content: {
+                envelope: dsse,
+                hash: { algorithm: SHA256_ALGORITHM, value: envelopeHash },
+                payloadHash: { algorithm: SHA256_ALGORITHM, value: payloadHash },
+            },
+        },
+    };
+}
+// Calculates the hash of a DSSE envelope for inclusion in a Rekor entry.
+// There is no standard way to do this, so the scheme we're using as as
+// follows:
+//  * payload is base64 encoded
+//  * signature is base64 encoded (only the first signature is used)
+//  * keyid is included ONLY if it is NOT an empty string
+//  * The resulting JSON is canonicalized and hashed to a hex string
+function calculateDSSEHash(envelope, publicKey) {
+    const dsse = {
+        payloadType: envelope.payloadType,
+        payload: envelope.payload.toString('base64'),
+        signatures: [
+            { sig: envelope.signatures[0].sig.toString('base64'), publicKey },
+        ],
+    };
+    // If the keyid is an empty string, Rekor seems to remove it altogether.
+    if (envelope.signatures[0].keyid.length > 0) {
+        dsse.signatures[0].keyid = envelope.signatures[0].keyid;
     }
+    return util_1.crypto
+        .digest(SHA256_ALGORITHM, util_1.json.canonicalize(dsse))
+        .toString('hex');
 }
-exports.X509SubjectAlternativeNameExtension = X509SubjectAlternativeNameExtension;
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1
-class X509AuthorityKeyIDExtension extends X509Extension {
-    get keyIdentifier() {
-        return this.findSequenceMember(0x00)?.value;
-    }
-    findSequenceMember(tag) {
-        return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag));
+
+
+/***/ }),
+
+/***/ 2566:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const util_1 = __nccwpck_require__(19100);
+const client_1 = __nccwpck_require__(42815);
+const entry_1 = __nccwpck_require__(97890);
+exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev';
+class RekorWitness {
+    constructor(options) {
+        this.entryType = options.entryType;
+        this.tlog = new client_1.TLogClient({
+            ...options,
+            rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL,
+        });
     }
-    // The extnValue field contains a single sequence wrapping the keyIdentifier
-    get sequence() {
-        return this.extnValueObj.subs[0];
+    async testify(content, publicKey) {
+        const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType);
+        const entry = await this.tlog.createEntry(proposedEntry);
+        return toTransparencyLogEntry(entry);
     }
 }
-exports.X509AuthorityKeyIDExtension = X509AuthorityKeyIDExtension;
-// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2
-class X509SubjectKeyIDExtension extends X509Extension {
-    get keyIdentifier() {
-        return this.extnValueObj.subs[0].value;
-    }
+exports.RekorWitness = RekorWitness;
+function toTransparencyLogEntry(entry) {
+    const logID = Buffer.from(entry.logID, 'hex');
+    // Parse entry body so we can extract the kind and version.
+    const bodyJSON = util_1.encoding.base64Decode(entry.body);
+    const entryBody = JSON.parse(bodyJSON);
+    const promise = entry?.verification?.signedEntryTimestamp
+        ? inclusionPromise(entry.verification.signedEntryTimestamp)
+        : undefined;
+    const proof = entry?.verification?.inclusionProof
+        ? inclusionProof(entry.verification.inclusionProof)
+        : undefined;
+    const tlogEntry = {
+        logIndex: entry.logIndex.toString(),
+        logId: {
+            keyId: logID,
+        },
+        integratedTime: entry.integratedTime.toString(),
+        kindVersion: {
+            kind: entryBody.kind,
+            version: entryBody.apiVersion,
+        },
+        inclusionPromise: promise,
+        inclusionProof: proof,
+        canonicalizedBody: Buffer.from(entry.body, 'base64'),
+    };
+    return {
+        tlogEntries: [tlogEntry],
+    };
 }
-exports.X509SubjectKeyIDExtension = X509SubjectKeyIDExtension;
-// https://www.rfc-editor.org/rfc/rfc6962#section-3.3
-class X509SCTExtension extends X509Extension {
-    constructor(asn1) {
-        super(asn1);
+function inclusionPromise(promise) {
+    return {
+        signedEntryTimestamp: Buffer.from(promise, 'base64'),
+    };
+}
+function inclusionProof(proof) {
+    return {
+        logIndex: proof.logIndex.toString(),
+        treeSize: proof.treeSize.toString(),
+        rootHash: Buffer.from(proof.rootHash, 'hex'),
+        hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')),
+        checkpoint: {
+            envelope: proof.checkpoint,
+        },
+    };
+}
+
+
+/***/ }),
+
+/***/ 97409:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TSAClient = void 0;
+/*
+Copyright 2023 The Sigstore Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+const error_1 = __nccwpck_require__(97841);
+const tsa_1 = __nccwpck_require__(78963);
+const util_1 = __nccwpck_require__(19100);
+const SHA256_ALGORITHM = 'sha256';
+class TSAClient {
+    constructor(options) {
+        this.tsa = new tsa_1.TimestampAuthority({
+            baseURL: options.tsaBaseURL,
+            retry: options.retry,
+            timeout: options.timeout,
+        });
     }
-    get signedCertificateTimestamps() {
-        const buf = this.extnValueObj.subs[0].value;
-        const stream = new stream_1.ByteStream(buf);
-        // The overall list length is encoded in the first two bytes -- note this
-        // is the length of the list in bytes, NOT the number of SCTs in the list
-        const end = stream.getUint16() + 2;
-        const sctList = [];
-        while (stream.position < end) {
-            // Read the length of the next SCT
-            const sctLength = stream.getUint16();
-            // Slice out the bytes for the next SCT and parse it
-            const sct = stream.getBlock(sctLength);
-            sctList.push(sct_1.SignedCertificateTimestamp.parse(sct));
+    async createTimestamp(signature) {
+        const request = {
+            artifactHash: util_1.crypto
+                .digest(SHA256_ALGORITHM, signature)
+                .toString('base64'),
+            hashAlgorithm: SHA256_ALGORITHM,
+        };
+        try {
+            return await this.tsa.createTimestamp(request);
         }
-        if (stream.position !== end) {
-            throw new Error('SCT list length does not match actual length');
+        catch (err) {
+            (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp');
         }
-        return sctList;
     }
 }
-exports.X509SCTExtension = X509SCTExtension;
+exports.TSAClient = TSAClient;
 
 
 /***/ }),
 
-/***/ 49358:
+/***/ 66936:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TSAWitness = void 0;
 /*
 Copyright 2023 The Sigstore Authors.
 
@@ -16802,18 +16700,37 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.X509SCTExtension = exports.X509Certificate = exports.EXTENSION_OID_SCT = void 0;
-var cert_1 = __nccwpck_require__(83566);
-Object.defineProperty(exports, "EXTENSION_OID_SCT", ({ enumerable: true, get: function () { return cert_1.EXTENSION_OID_SCT; } }));
-Object.defineProperty(exports, "X509Certificate", ({ enumerable: true, get: function () { return cert_1.X509Certificate; } }));
-var ext_1 = __nccwpck_require__(96389);
-Object.defineProperty(exports, "X509SCTExtension", ({ enumerable: true, get: function () { return ext_1.X509SCTExtension; } }));
+const client_1 = __nccwpck_require__(97409);
+class TSAWitness {
+    constructor(options) {
+        this.tsa = new client_1.TSAClient({
+            tsaBaseURL: options.tsaBaseURL,
+            retry: options.retry,
+            timeout: options.timeout,
+        });
+    }
+    async testify(content) {
+        const signature = extractSignature(content);
+        const timestamp = await this.tsa.createTimestamp(signature);
+        return {
+            rfc3161Timestamps: [{ signedTimestamp: timestamp }],
+        };
+    }
+}
+exports.TSAWitness = TSAWitness;
+function extractSignature(content) {
+    switch (content.$case) {
+        case 'dsseEnvelope':
+            return content.dsseEnvelope.signatures[0].sig;
+        case 'messageSignature':
+            return content.messageSignature.signature;
+    }
+}
 
 
 /***/ }),
 
-/***/ 6144:
+/***/ 15183:
 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
@@ -16842,4494 +16759,3783 @@ var __importStar = (this && this.__importStar) || function (mod) {
     return result;
 };
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SignedCertificateTimestamp = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+exports.req = exports.json = exports.toBuffer = void 0;
+const http = __importStar(__nccwpck_require__(58611));
+const https = __importStar(__nccwpck_require__(65692));
+async function toBuffer(stream) {
+    let length = 0;
+    const chunks = [];
+    for await (const chunk of stream) {
+        length += chunk.length;
+        chunks.push(chunk);
+    }
+    return Buffer.concat(chunks, length);
+}
+exports.toBuffer = toBuffer;
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+async function json(stream) {
+    const buf = await toBuffer(stream);
+    const str = buf.toString('utf8');
+    try {
+        return JSON.parse(str);
+    }
+    catch (_err) {
+        const err = _err;
+        err.message += ` (input: ${str})`;
+        throw err;
+    }
+}
+exports.json = json;
+function req(url, opts = {}) {
+    const href = typeof url === 'string' ? url : url.href;
+    const req = (href.startsWith('https:') ? https : http).request(url, opts);
+    const promise = new Promise((resolve, reject) => {
+        req
+            .once('response', resolve)
+            .once('error', reject)
+            .end();
+    });
+    req.then = promise.then.bind(promise);
+    return req;
+}
+exports.req = req;
+//# sourceMappingURL=helpers.js.map
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+/***/ }),
 
-    http://www.apache.org/licenses/LICENSE-2.0
+/***/ 98894:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const crypto = __importStar(__nccwpck_require__(69368));
-const stream_1 = __nccwpck_require__(1673);
-class SignedCertificateTimestamp {
-    constructor(options) {
-        this.version = options.version;
-        this.logID = options.logID;
-        this.timestamp = options.timestamp;
-        this.extensions = options.extensions;
-        this.hashAlgorithm = options.hashAlgorithm;
-        this.signatureAlgorithm = options.signatureAlgorithm;
-        this.signature = options.signature;
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
     }
-    get datetime() {
-        return new Date(Number(this.timestamp.readBigInt64BE()));
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Agent = void 0;
+const net = __importStar(__nccwpck_require__(69278));
+const http = __importStar(__nccwpck_require__(58611));
+const https_1 = __nccwpck_require__(65692);
+__exportStar(__nccwpck_require__(15183), exports);
+const INTERNAL = Symbol('AgentBaseInternalState');
+class Agent extends http.Agent {
+    constructor(opts) {
+        super(opts);
+        this[INTERNAL] = {};
     }
-    // Returns the hash algorithm used to generate the SCT's signature.
-    // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1
-    get algorithm() {
-        switch (this.hashAlgorithm) {
-            /* istanbul ignore next */
-            case 0:
-                return 'none';
-            /* istanbul ignore next */
-            case 1:
-                return 'md5';
-            /* istanbul ignore next */
-            case 2:
-                return 'sha1';
-            /* istanbul ignore next */
-            case 3:
-                return 'sha224';
-            case 4:
-                return 'sha256';
-            /* istanbul ignore next */
-            case 5:
-                return 'sha384';
-            /* istanbul ignore next */
-            case 6:
-                return 'sha512';
-            /* istanbul ignore next */
-            default:
-                return 'unknown';
+    /**
+     * Determine whether this is an `http` or `https` request.
+     */
+    isSecureEndpoint(options) {
+        if (options) {
+            // First check the `secureEndpoint` property explicitly, since this
+            // means that a parent `Agent` is "passing through" to this instance.
+            // eslint-disable-next-line @typescript-eslint/no-explicit-any
+            if (typeof options.secureEndpoint === 'boolean') {
+                return options.secureEndpoint;
+            }
+            // If no explicit `secure` endpoint, check if `protocol` property is
+            // set. This will usually be the case since using a full string URL
+            // or `URL` instance should be the most common usage.
+            if (typeof options.protocol === 'string') {
+                return options.protocol === 'https:';
+            }
         }
+        // Finally, if no `protocol` property was set, then fall back to
+        // checking the stack trace of the current call stack, and try to
+        // detect the "https" module.
+        const { stack } = new Error();
+        if (typeof stack !== 'string')
+            return false;
+        return stack
+            .split('\n')
+            .some((l) => l.indexOf('(https.js:') !== -1 ||
+            l.indexOf('node:https:') !== -1);
     }
-    verify(preCert, key) {
-        // Assemble the digitally-signed struct (the data over which the signature
-        // was generated).
-        // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
-        const stream = new stream_1.ByteStream();
-        stream.appendChar(this.version);
-        stream.appendChar(0x00); // SignatureType = certificate_timestamp(0)
-        stream.appendView(this.timestamp);
-        stream.appendUint16(0x01); // LogEntryType = precert_entry(1)
-        stream.appendView(preCert);
-        stream.appendUint16(this.extensions.byteLength);
-        /* istanbul ignore next - extensions are very uncommon */
-        if (this.extensions.byteLength > 0) {
-            stream.appendView(this.extensions);
+    // In order to support async signatures in `connect()` and Node's native
+    // connection pooling in `http.Agent`, the array of sockets for each origin
+    // has to be updated synchronously. This is so the length of the array is
+    // accurate when `addRequest()` is next called. We achieve this by creating a
+    // fake socket and adding it to `sockets[origin]` and incrementing
+    // `totalSocketCount`.
+    incrementSockets(name) {
+        // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no
+        // need to create a fake socket because Node.js native connection pooling
+        // will never be invoked.
+        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
+            return null;
         }
-        return crypto.verify(stream.buffer, key, this.signature, this.algorithm);
+        // All instances of `sockets` are expected TypeScript errors. The
+        // alternative is to add it as a private property of this class but that
+        // will break TypeScript subclassing.
+        if (!this.sockets[name]) {
+            // @ts-expect-error `sockets` is readonly in `@types/node`
+            this.sockets[name] = [];
+        }
+        const fakeSocket = new net.Socket({ writable: false });
+        this.sockets[name].push(fakeSocket);
+        // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
+        this.totalSocketCount++;
+        return fakeSocket;
     }
-    // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using
-    // TLS encoding which means the fields and lengths of most fields are
-    // specified as part of the SCT and TLS specs.
-    // https://www.rfc-editor.org/rfc/rfc6962#section-3.2
-    // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1
-    static parse(buf) {
-        const stream = new stream_1.ByteStream(buf);
-        // Version - enum { v1(0), (255) }
-        const version = stream.getUint8();
-        // Log ID  - struct { opaque key_id[32]; }
-        const logID = stream.getBlock(32);
-        // Timestamp - uint64
-        const timestamp = stream.getBlock(8);
-        // Extensions - opaque extensions<0..2^16-1>;
-        const extenstionLength = stream.getUint16();
-        const extensions = stream.getBlock(extenstionLength);
-        // Hash algo - enum { sha256(4), . . . (255) }
-        const hashAlgorithm = stream.getUint8();
-        // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
-        const signatureAlgorithm = stream.getUint8();
-        // Signature  - opaque signature<0..2^16-1>;
-        const sigLength = stream.getUint16();
-        const signature = stream.getBlock(sigLength);
-        // Check that we read the entire buffer
-        if (stream.position !== buf.length) {
-            throw new Error('SCT buffer length mismatch');
+    decrementSockets(name, socket) {
+        if (!this.sockets[name] || socket === null) {
+            return;
+        }
+        const sockets = this.sockets[name];
+        const index = sockets.indexOf(socket);
+        if (index !== -1) {
+            sockets.splice(index, 1);
+            // @ts-expect-error  `totalSocketCount` isn't defined in `@types/node`
+            this.totalSocketCount--;
+            if (sockets.length === 0) {
+                // @ts-expect-error `sockets` is readonly in `@types/node`
+                delete this.sockets[name];
+            }
+        }
+    }
+    // In order to properly update the socket pool, we need to call `getName()` on
+    // the core `https.Agent` if it is a secureEndpoint.
+    getName(options) {
+        const secureEndpoint = typeof options.secureEndpoint === 'boolean'
+            ? options.secureEndpoint
+            : this.isSecureEndpoint(options);
+        if (secureEndpoint) {
+            // @ts-expect-error `getName()` isn't defined in `@types/node`
+            return https_1.Agent.prototype.getName.call(this, options);
+        }
+        // @ts-expect-error `getName()` isn't defined in `@types/node`
+        return super.getName(options);
+    }
+    createSocket(req, options, cb) {
+        const connectOpts = {
+            ...options,
+            secureEndpoint: this.isSecureEndpoint(options),
+        };
+        const name = this.getName(connectOpts);
+        const fakeSocket = this.incrementSockets(name);
+        Promise.resolve()
+            .then(() => this.connect(req, connectOpts))
+            .then((socket) => {
+            this.decrementSockets(name, fakeSocket);
+            if (socket instanceof http.Agent) {
+                // @ts-expect-error `addRequest()` isn't defined in `@types/node`
+                return socket.addRequest(req, connectOpts);
+            }
+            this[INTERNAL].currentSocket = socket;
+            // @ts-expect-error `createSocket()` isn't defined in `@types/node`
+            super.createSocket(req, options, cb);
+        }, (err) => {
+            this.decrementSockets(name, fakeSocket);
+            cb(err);
+        });
+    }
+    createConnection() {
+        const socket = this[INTERNAL].currentSocket;
+        this[INTERNAL].currentSocket = undefined;
+        if (!socket) {
+            throw new Error('No socket was returned in the `connect()` function');
+        }
+        return socket;
+    }
+    get defaultPort() {
+        return (this[INTERNAL].defaultPort ??
+            (this.protocol === 'https:' ? 443 : 80));
+    }
+    set defaultPort(v) {
+        if (this[INTERNAL]) {
+            this[INTERNAL].defaultPort = v;
+        }
+    }
+    get protocol() {
+        return (this[INTERNAL].protocol ??
+            (this.isSecureEndpoint() ? 'https:' : 'http:'));
+    }
+    set protocol(v) {
+        if (this[INTERNAL]) {
+            this[INTERNAL].protocol = v;
         }
-        return new SignedCertificateTimestamp({
-            version,
-            logID,
-            timestamp,
-            extensions,
-            hashAlgorithm,
-            signatureAlgorithm,
-            signature,
-        });
     }
 }
-exports.SignedCertificateTimestamp = SignedCertificateTimestamp;
-
+exports.Agent = Agent;
+//# sourceMappingURL=index.js.map
 
 /***/ }),
 
-/***/ 23688:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 59380:
+/***/ ((module) => {
 
 "use strict";
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HEADER_OCI_SUBJECT = exports.HEADER_LOCATION = exports.HEADER_IF_MATCH = exports.HEADER_ETAG = exports.HEADER_DIGEST = exports.HEADER_CONTENT_TYPE = exports.HEADER_CONTENT_LENGTH = exports.HEADER_AUTHORIZATION = exports.HEADER_AUTHENTICATE = exports.HEADER_API_VERSION = exports.HEADER_ACCEPT = exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = exports.CONTENT_TYPE_OCTET_STREAM = exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = exports.CONTENT_TYPE_DOCKER_MANIFEST = exports.CONTENT_TYPE_OCI_MANIFEST = exports.CONTENT_TYPE_OCI_INDEX = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-exports.CONTENT_TYPE_OCI_INDEX = 'application/vnd.oci.image.index.v1+json';
-exports.CONTENT_TYPE_OCI_MANIFEST = 'application/vnd.oci.image.manifest.v1+json';
-exports.CONTENT_TYPE_DOCKER_MANIFEST = 'application/vnd.docker.distribution.manifest.v2+json';
-exports.CONTENT_TYPE_DOCKER_MANIFEST_LIST = 'application/vnd.docker.distribution.manifest.list.v2+json';
-exports.CONTENT_TYPE_OCTET_STREAM = 'application/octet-stream';
-exports.CONTENT_TYPE_EMPTY_DESCRIPTOR = 'application/vnd.oci.empty.v1+json';
-exports.HEADER_ACCEPT = 'Accept';
-exports.HEADER_API_VERSION = 'Docker-Distribution-API-Version';
-exports.HEADER_AUTHENTICATE = 'WWW-Authenticate';
-exports.HEADER_AUTHORIZATION = 'Authorization';
-exports.HEADER_CONTENT_LENGTH = 'Content-Length';
-exports.HEADER_CONTENT_TYPE = 'Content-Type';
-exports.HEADER_DIGEST = 'Docker-Content-Digest';
-exports.HEADER_ETAG = 'Etag';
-exports.HEADER_IF_MATCH = 'If-Match';
-exports.HEADER_LOCATION = 'Location';
-exports.HEADER_OCI_SUBJECT = 'OCI-Subject';
-
-
-/***/ }),
-
-/***/ 62691:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+module.exports = balanced;
+function balanced(a, b, str) {
+  if (a instanceof RegExp) a = maybeMatch(a, str);
+  if (b instanceof RegExp) b = maybeMatch(b, str);
 
-"use strict";
+  var r = range(a, b, str);
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.fromBasicAuth = exports.toBasicAuth = exports.getRegistryCredentials = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+  return r && {
+    start: r[0],
+    end: r[1],
+    pre: str.slice(0, r[0]),
+    body: str.slice(r[0] + a.length, r[1]),
+    post: str.slice(r[1] + b.length)
+  };
+}
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+function maybeMatch(reg, str) {
+  var m = str.match(reg);
+  return m ? m[0] : null;
+}
 
-    http://www.apache.org/licenses/LICENSE-2.0
+balanced.range = range;
+function range(a, b, str) {
+  var begs, beg, left, right, result;
+  var ai = str.indexOf(a);
+  var bi = str.indexOf(b, ai + 1);
+  var i = ai;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const node_fs_1 = __importDefault(__nccwpck_require__(73024));
-const node_os_1 = __importDefault(__nccwpck_require__(48161));
-const node_path_1 = __importDefault(__nccwpck_require__(76760));
-const name_1 = __nccwpck_require__(96666);
-// Returns the credentials for a given registry by reading the Docker config
-// file.
-const getRegistryCredentials = (imageName) => {
-    const { registry } = (0, name_1.parseImageName)(imageName);
-    const dockerConfigFile = node_path_1.default.join(node_os_1.default.homedir(), '.docker', 'config.json');
-    let content;
-    try {
-        content = node_fs_1.default.readFileSync(dockerConfigFile, 'utf8');
-    }
-    catch (err) {
-        throw new Error(`No credential file found at ${dockerConfigFile}`);
-    }
-    const dockerConfig = JSON.parse(content);
-    const credKey = Object.keys(dockerConfig.auths || {}).find((key) => key.includes(registry)) || registry;
-    const creds = dockerConfig.auths?.[credKey];
-    if (!creds) {
-        throw new Error(`No credentials found for registry ${registry}`);
+  if (ai >= 0 && bi > 0) {
+    if(a===b) {
+      return [ai, bi];
     }
-    // Extract username/password from auth string
-    const { username, password } = (0, exports.fromBasicAuth)(creds.auth);
-    // If the identitytoken is present, use it as the password (primarily for ACR)
-    const pass = creds.identitytoken ? creds.identitytoken : password;
-    return { username, password: pass };
-};
-exports.getRegistryCredentials = getRegistryCredentials;
-// Encode the username and password as base64-encoded basicauth value
-const toBasicAuth = (creds) => Buffer.from(`${creds.username}:${creds.password}`).toString('base64');
-exports.toBasicAuth = toBasicAuth;
-// Decode the base64-encoded basicauth value
-const fromBasicAuth = (auth) => {
-    // Need to account for the possibility of ':' in the password
-    const [username, ...rest] = Buffer.from(auth, 'base64').toString().split(':');
-    const password = rest.join(':');
-    return { username, password };
-};
-exports.fromBasicAuth = fromBasicAuth;
-
-
-/***/ }),
+    begs = [];
+    left = str.length;
 
-/***/ 46803:
-/***/ ((__unused_webpack_module, exports) => {
+    while (i >= 0 && !result) {
+      if (i == ai) {
+        begs.push(i);
+        ai = str.indexOf(a, i + 1);
+      } else if (begs.length == 1) {
+        result = [ begs.pop(), bi ];
+      } else {
+        beg = begs.pop();
+        if (beg < left) {
+          left = beg;
+          right = bi;
+        }
 
-"use strict";
+        bi = str.indexOf(b, i + 1);
+      }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.OCIError = exports.ensureStatus = exports.HTTPError = void 0;
-class HTTPError extends Error {
-    constructor({ status, message }) {
-        super(message);
-        this.statusCode = status;
+      i = ai < bi && ai >= 0 ? ai : bi;
     }
-}
-exports.HTTPError = HTTPError;
-// Inspects the response status and throws an HTTPError if it does not match the
-// expected status code
-const ensureStatus = (expectedStatus) => {
-    return (response) => {
-        if (response.status !== expectedStatus) {
-            throw new HTTPError({
-                message: `Error fetching ${response.url} - expected ${expectedStatus}, received ${response.status}`,
-                status: response.status,
-            });
-        }
-        return response;
-    };
-};
-exports.ensureStatus = ensureStatus;
-class OCIError extends Error {
-    constructor({ message, cause, }) {
-        super(message);
-        this.cause = cause;
-        this.name = this.constructor.name;
+
+    if (begs.length) {
+      result = [ left, right ];
     }
+  }
+
+  return result;
 }
-exports.OCIError = OCIError;
 
 
 /***/ }),
 
-/***/ 32721:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
-
-"use strict";
-
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-/*
-Copyright 2024 The Sigstore Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const http2_1 = __nccwpck_require__(85675);
-const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310));
-const proc_log_1 = __nccwpck_require__(26687);
-const promise_retry_1 = __importDefault(__nccwpck_require__(90390));
-const { HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants;
-const fetchWithRetry = async (url, options = {}) => {
-    return (0, promise_retry_1.default)(async (retry, attemptNum) => {
-        /* eslint-disable @typescript-eslint/no-explicit-any */
-        const logRetry = (reason) => {
-            proc_log_1.log.http('fetch', `${options.method} ${url} attempt ${attemptNum} failed with ${reason}`);
-        };
-        const response = await (0, make_fetch_happen_1.default)(url, {
-            ...options,
-            retry: false, // We're handling retries ourselves
-        }).catch((reason) => {
-            logRetry(reason);
-            return retry(reason);
-        });
-        if (retryable(response.status)) {
-            logRetry(response.status);
-            return retry(response);
-        }
-        return response;
-    }, retryOpts(options.retry)).catch((err) => {
-        // If we got an actual error, throw it
-        if (err instanceof Error) {
-            throw err;
-        }
-        // Otherwise, return the response (this is simply a retry-able response for
-        // which we exceeded the retry limit)
-        return err;
-    });
-};
-// Returns a wrapped fetch function with default options
-fetchWithRetry.defaults = (defaultOptions = {}, wrappedFetch = fetchWithRetry) => {
-    const defaultedFetch = (url, options = {}) => {
-        const finalOptions = {
-            ...defaultOptions,
-            ...options,
-            headers: { ...defaultOptions.headers, ...options.headers },
-        };
-        return wrappedFetch(url, finalOptions);
-    };
-    defaultedFetch.defaults = (newDefaults = {}) => fetchWithRetry.defaults(newDefaults, defaultedFetch);
-    return defaultedFetch;
-};
-// Determine if a status code is retryable. This includes 5xx errors, 408, and
-// 429.
-const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR;
-// Normalize the retry options to the format expected by promise-retry
-const retryOpts = (retry) => {
-    if (typeof retry === 'boolean') {
-        return { retries: retry ? 1 : 0 };
-    }
-    else if (typeof retry === 'number') {
-        return { retries: retry };
-    }
-    else {
-        return { retries: 0, ...retry };
-    }
-};
-exports["default"] = fetchWithRetry;
-
+/***/ 52732:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-/***/ }),
+var register = __nccwpck_require__(11063);
+var addHook = __nccwpck_require__(22027);
+var removeHook = __nccwpck_require__(59934);
 
-/***/ 19812:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+// bind with array of arguments: https://stackoverflow.com/a/21792913
+var bind = Function.bind;
+var bindable = bind.bind(bind);
 
-"use strict";
+function bindApi(hook, state, name) {
+  var removeHookRef = bindable(removeHook, null).apply(
+    null,
+    name ? [state, name] : [state]
+  );
+  hook.api = { remove: removeHookRef };
+  hook.remove = removeHookRef;
+  ["before", "error", "after", "wrap"].forEach(function (kind) {
+    var args = name ? [state, kind, name] : [state, kind];
+    hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);
+  });
+}
 
-var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
-    if (kind === "m") throw new TypeError("Private method is not writable");
-    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
-    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
-    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
-};
-var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
-    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
-    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
-    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-};
-var _OCIImage_instances, _OCIImage_client, _OCIImage_credentials, _OCIImage_createReferrersIndexByTag;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.OCIImage = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+function HookSingular() {
+  var singularHookName = "h";
+  var singularHookState = {
+    registry: {},
+  };
+  var singularHook = register.bind(null, singularHookState, singularHookName);
+  bindApi(singularHook, singularHookState, singularHookName);
+  return singularHook;
+}
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+function HookCollection() {
+  var state = {
+    registry: {},
+  };
 
-    http://www.apache.org/licenses/LICENSE-2.0
+  var hook = register.bind(null, state);
+  bindApi(hook, state);
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const constants_1 = __nccwpck_require__(23688);
-const error_1 = __nccwpck_require__(46803);
-const registry_1 = __nccwpck_require__(22138);
-const DOCKER_DEFAULT_REGISTRY = 'registry-1.docker.io';
-const EMPTY_BLOB = Buffer.from('{}');
-class OCIImage {
-    constructor(image, creds, opts) {
-        _OCIImage_instances.add(this);
-        _OCIImage_client.set(this, void 0);
-        _OCIImage_credentials.set(this, void 0);
-        __classPrivateFieldSet(this, _OCIImage_client, new registry_1.RegistryClient(canonicalizeRegistryName(image.registry), image.path, opts), "f");
-        __classPrivateFieldSet(this, _OCIImage_credentials, creds, "f");
-    }
-    async addArtifact(opts) {
-        let artifactDescriptor;
-        const annotations = {
-            'org.opencontainers.image.created': new Date().toISOString(),
-            ...opts.annotations,
-        };
-        try {
-            if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) {
-                await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f"));
-            }
-            // Check that the image exists
-            const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(opts.imageDigest);
-            // Upload the artifact blob
-            const artifactBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(opts.artifact);
-            // Upload the empty blob (needed for the manifest config)
-            const emptyBlob = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadBlob(EMPTY_BLOB);
-            // Construct artifact manifest
-            const manifest = buildManifest({
-                artifactDescriptor: { ...artifactBlob, mediaType: opts.mediaType },
-                subjectDescriptor: imageDescriptor,
-                configDescriptor: {
-                    ...emptyBlob,
-                    mediaType: constants_1.CONTENT_TYPE_EMPTY_DESCRIPTOR,
-                },
-                annotations,
-            });
-            // Upload artifact manifest
-            artifactDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(manifest));
-            // Check to see if registry supports the referrers API. For most
-            // registries the presence of a subjectDigest response header when
-            // uploading the artifact manifest indicates that the referrers API IS
-            // supported -- however, this is not a guarantee (AWS ECR does NOT support
-            // the referrers API but still reports a subjectDigest).
-            const referrersSupported = await __classPrivateFieldGet(this, _OCIImage_client, "f").pingReferrers();
-            // Manually update the referrers list if the referrers API is not supported.
-            if (!artifactDescriptor.subjectDigest || !referrersSupported) {
-                // Strip subjectDigest from the artifact descriptor (in case it was returned)
-                /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
-                const { subjectDigest, ...descriptor } = artifactDescriptor;
-                await __classPrivateFieldGet(this, _OCIImage_instances, "m", _OCIImage_createReferrersIndexByTag).call(this, {
-                    artifact: {
-                        ...descriptor,
-                        artifactType: opts.mediaType,
-                        annotations,
-                    },
-                    imageDigest: opts.imageDigest,
-                });
-            }
-        }
-        catch (err) {
-            throw new error_1.OCIError({
-                message: `Error uploading artifact to container registry`,
-                cause: err,
-            });
-        }
-        return artifactDescriptor;
-    }
-    async getDigest(tag) {
-        try {
-            if (__classPrivateFieldGet(this, _OCIImage_credentials, "f")) {
-                await __classPrivateFieldGet(this, _OCIImage_client, "f").signIn(__classPrivateFieldGet(this, _OCIImage_credentials, "f"));
-            }
-            const imageDescriptor = await __classPrivateFieldGet(this, _OCIImage_client, "f").checkManifest(tag);
-            return imageDescriptor.digest;
-        }
-        catch (err) {
-            throw new error_1.OCIError({
-                message: `Error retrieving image digest from container registry`,
-                cause: err,
-            });
-        }
-    }
+  return hook;
+}
+
+var collectionHookDeprecationMessageDisplayed = false;
+function Hook() {
+  if (!collectionHookDeprecationMessageDisplayed) {
+    console.warn(
+      '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4'
+    );
+    collectionHookDeprecationMessageDisplayed = true;
+  }
+  return HookCollection();
 }
-exports.OCIImage = OCIImage;
-_OCIImage_client = new WeakMap(), _OCIImage_credentials = new WeakMap(), _OCIImage_instances = new WeakSet(), _OCIImage_createReferrersIndexByTag = 
-// Create a referrers index by tag. This is a fallback for registries that do
-// not support the referrers API.
-// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests-with-subject
-async function _OCIImage_createReferrersIndexByTag(opts) {
-    const referrerTag = digestToTag(opts.imageDigest);
-    let referrerManifest;
-    let etag;
-    try {
-        // Retrieve any existing referrer index
-        const referrerIndex = await __classPrivateFieldGet(this, _OCIImage_client, "f").getManifest(referrerTag);
-        if (referrerIndex.mediaType !== constants_1.CONTENT_TYPE_OCI_INDEX) {
-            throw new Error(`Expected referrer manifest type ${constants_1.CONTENT_TYPE_OCI_INDEX}, got ${referrerIndex.mediaType}`);
-        }
-        referrerManifest = referrerIndex.body;
-        etag = referrerIndex.etag;
-    }
-    catch (err) {
-        // If the referrer index does not exist, create a new one
-        if (err instanceof error_1.HTTPError && err.statusCode === 404) {
-            referrerManifest = newIndex();
-        }
-        else {
-            throw err;
-        }
-    }
-    // If the artifact is not already in the index, add it to the list and
-    // re-upload the index
-    if (!referrerManifest.manifests.some((manifest) => manifest.digest === opts.artifact.digest)) {
-        // Add the artifact to the index
-        referrerManifest.manifests.push(opts.artifact);
-        await __classPrivateFieldGet(this, _OCIImage_client, "f").uploadManifest(JSON.stringify(referrerManifest), {
-            mediaType: constants_1.CONTENT_TYPE_OCI_INDEX,
-            reference: referrerTag,
-            etag,
-        });
-    }
-};
-// Build an OCI manifest document with references to the given artifact,
-// subject, and config
-const buildManifest = (opts) => ({
-    schemaVersion: 2,
-    mediaType: constants_1.CONTENT_TYPE_OCI_MANIFEST,
-    artifactType: opts.artifactDescriptor.mediaType,
-    config: opts.configDescriptor,
-    layers: [opts.artifactDescriptor],
-    subject: opts.subjectDescriptor,
-    annotations: opts.annotations,
-});
-// Return an empty OCI index document
-const newIndex = () => ({
-    mediaType: constants_1.CONTENT_TYPE_OCI_INDEX,
-    schemaVersion: 2,
-    manifests: [],
-});
-// Convert an image digest to a tag per the Referrers Tag Schema
-// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#referrers-tag-schema
-const digestToTag = (digest) => {
-    return digest.replace(':', '-');
-};
-// Canonicalize the registry name to match the format used by the registry
-// client. This is used primarily to handle the special case of the Docker Hub
-// registry.
-// https://github.com/moby/moby/blob/v24.0.2/registry/config.go#L25-L48
-const canonicalizeRegistryName = (registry) => {
-    return registry.endsWith('docker.io') ? DOCKER_DEFAULT_REGISTRY : registry;
-};
 
+Hook.Singular = HookSingular.bind();
+Hook.Collection = HookCollection.bind();
 
-/***/ }),
+module.exports = Hook;
+// expose constructors as a named property for TypeScript
+module.exports.Hook = Hook;
+module.exports.Singular = Hook.Singular;
+module.exports.Collection = Hook.Collection;
 
-/***/ 81057:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-"use strict";
+/***/ }),
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getImageDigest = exports.attachArtifactToImage = exports.OCIError = exports.getRegistryCredentials = void 0;
-const image_1 = __nccwpck_require__(19812);
-const name_1 = __nccwpck_require__(96666);
-var credentials_1 = __nccwpck_require__(62691);
-Object.defineProperty(exports, "getRegistryCredentials", ({ enumerable: true, get: function () { return credentials_1.getRegistryCredentials; } }));
-var error_1 = __nccwpck_require__(46803);
-Object.defineProperty(exports, "OCIError", ({ enumerable: true, get: function () { return error_1.OCIError; } }));
-// Associates the given artifact with an OCI image. The artifact is identified
-// by its media type and a buffer containing the artifact. The image is
-// identified by its FQDN and digest.
-const attachArtifactToImage = async (opts) => {
-    const image = (0, name_1.parseImageName)(opts.imageName);
-    return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).addArtifact(opts);
-};
-exports.attachArtifactToImage = attachArtifactToImage;
-// Returns the digest of the given image tag in the remote registry.
-const getImageDigest = async (opts) => {
-    const image = (0, name_1.parseImageName)(opts.imageName);
-    return new image_1.OCIImage(image, opts.credentials, opts.fetchOpts).getDigest(opts.imageTag);
-};
-exports.getImageDigest = getImageDigest;
+/***/ 22027:
+/***/ ((module) => {
 
+module.exports = addHook;
 
-/***/ }),
+function addHook(state, kind, name, hook) {
+  var orig = hook;
+  if (!state.registry[name]) {
+    state.registry[name] = [];
+  }
 
-/***/ 96666:
-/***/ ((__unused_webpack_module, exports) => {
+  if (kind === "before") {
+    hook = function (method, options) {
+      return Promise.resolve()
+        .then(orig.bind(null, options))
+        .then(method.bind(null, options));
+    };
+  }
 
-"use strict";
+  if (kind === "after") {
+    hook = function (method, options) {
+      var result;
+      return Promise.resolve()
+        .then(method.bind(null, options))
+        .then(function (result_) {
+          result = result_;
+          return orig(result, options);
+        })
+        .then(function () {
+          return result;
+        });
+    };
+  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseImageName = void 0;
-const expression = (...res) => res.join('');
-const group = (...res) => `(?:${expression(...res)})`;
-const repeated = (...res) => `${group(expression(...res))}+`;
-const optional = (...res) => `${group(expression(...res))}?`;
-const capture = (...res) => `(${expression(...res)})`;
-const anchored = (...res) => `^${expression(...res)}$`;
-// Lower case letters, numbers
-const ALPHA_NUMERIC_RE = '[a-z0-9]+';
-// Separators allowed to be embedded in name components. This allows one period,
-// one or two underscore or multiple dashes.
-const SEPARATOR_RE = group('\\.|_|__|-+');
-// Registry path component names to start with at least one letter or number,
-// with following parts able to be separated by one period, one or two
-// underscores or multiple dashes.
-const NAME_COMPONENT_RE = expression(ALPHA_NUMERIC_RE, optional(repeated(SEPARATOR_RE, ALPHA_NUMERIC_RE)));
-const NAME_RE = expression(NAME_COMPONENT_RE, repeated(optional('\\/', NAME_COMPONENT_RE)));
-// Component of the registry domain must be at least one letter or number, with
-// following parts able to be separated by a dash.
-const DOMAIN_COMPONENT_RE = group('[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]');
-// Restricts the registry domain to be one or more period separated components
-// followed by an optional port.
-const DOMAIN_RE = expression(DOMAIN_COMPONENT_RE, optional(repeated('\\.', DOMAIN_COMPONENT_RE)), optional(':[0-9]+'));
-// Capture the registry domain and path components of a repository name.
-const ANCHORED_NAME_RE = anchored(capture(DOMAIN_RE), '\\/', capture(NAME_RE));
-// Parses a fully qualified image name into its registry and path components.
-const parseImageName = (image) => {
-    const matches = image.match(ANCHORED_NAME_RE);
-    if (!matches) {
-        throw new Error(`Invalid image name: ${image}`);
-    }
-    return {
-        registry: matches[1],
-        path: matches[2],
+  if (kind === "error") {
+    hook = function (method, options) {
+      return Promise.resolve()
+        .then(method.bind(null, options))
+        .catch(function (error) {
+          return orig(error, options);
+        });
     };
-};
-exports.parseImageName = parseImageName;
+  }
+
+  state.registry[name].push({
+    hook: hook,
+    orig: orig,
+  });
+}
 
 
 /***/ }),
 
-/***/ 22138:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 11063:
+/***/ ((module) => {
 
-"use strict";
+module.exports = register;
 
-var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
-    if (kind === "m") throw new TypeError("Private method is not writable");
-    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
-    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
-    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
-};
-var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
-    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
-    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
-    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-var _RegistryClient_instances, _RegistryClient_baseURL, _RegistryClient_repository, _RegistryClient_fetch, _RegistryClient_fetchDistributionToken, _RegistryClient_fetchOAuth2Token;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RegistryClient = exports.ZERO_DIGEST = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+function register(state, name, method, options) {
+  if (typeof method !== "function") {
+    throw new Error("method for before hook must be a function");
+  }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+  if (!options) {
+    options = {};
+  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+  if (Array.isArray(name)) {
+    return name.reverse().reduce(function (callback, name) {
+      return register.bind(null, state, name, callback, options);
+    }, method)();
+  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const node_crypto_1 = __importDefault(__nccwpck_require__(77598));
-const constants_1 = __nccwpck_require__(23688);
-const credentials_1 = __nccwpck_require__(62691);
-const error_1 = __nccwpck_require__(46803);
-const fetch_1 = __importDefault(__nccwpck_require__(32721));
-const ALL_MANIFEST_MEDIA_TYPES = [
-    constants_1.CONTENT_TYPE_OCI_INDEX,
-    constants_1.CONTENT_TYPE_OCI_MANIFEST,
-    constants_1.CONTENT_TYPE_DOCKER_MANIFEST,
-    constants_1.CONTENT_TYPE_DOCKER_MANIFEST_LIST,
-].join(',');
-exports.ZERO_DIGEST = 'sha256:0000000000000000000000000000000000000000000000000000000000000000';
-class RegistryClient {
-    constructor(registry, repository, opts) {
-        _RegistryClient_instances.add(this);
-        _RegistryClient_baseURL.set(this, void 0);
-        _RegistryClient_repository.set(this, void 0);
-        _RegistryClient_fetch.set(this, void 0);
-        __classPrivateFieldSet(this, _RegistryClient_repository, repository, "f");
-        __classPrivateFieldSet(this, _RegistryClient_fetch, fetch_1.default.defaults(opts), "f");
-        // Use http for localhost registries, https otherwise
-        const hostname = new URL(`http://${registry}`).hostname;
-        /* istanbul ignore next */
-        const protocol = hostname === 'localhost' || hostname === '127.0.0.1' ? 'http' : 'https';
-        __classPrivateFieldSet(this, _RegistryClient_baseURL, `${protocol}://${registry}`, "f");
-    }
-    // Authenticate with the registry. Sends an unauthenticated request to the
-    // registry in order to get an auth challenge. If the challenge scheme is
-    // "basic" we don't need a token and can authenticate requests using basic
-    // auth. Otherwise, we fetch a token from the auth server and use that to
-    // authenticate requests.
-    // https://github.com/google/go-containerregistry/blob/main/pkg/authn/README.md#the-registry
-    async signIn(creds) {
-        // Initiate a blob upload to get the auth challenge
-        const probeResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' });
-        // If we get a 200 response, we're already authenticated
-        if (probeResponse.status === 200) {
-            return;
-        }
-        const authHeader = probeResponse.headers.get(constants_1.HEADER_AUTHENTICATE) ||
-            /* istanbul ignore next */ '';
-        const challenge = parseChallenge(authHeader);
-        // If the challenge scheme is "basic" we don't need a token and can
-        // authenticate requests using basic auth
-        if (challenge.scheme === 'basic') {
-            const basicAuth = (0, credentials_1.toBasicAuth)(creds);
-            __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({
-                headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` },
-            }), "f");
-            return;
-        }
-        let token;
-        if (creds.username === '') {
-            // If the OAUth2 token request fails, try to fetch a distribution token
-            token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchOAuth2Token).call(this, creds, challenge).catch(() => undefined);
-        }
-        if (!token) {
-            token = await __classPrivateFieldGet(this, _RegistryClient_instances, "m", _RegistryClient_fetchDistributionToken).call(this, creds, challenge);
-        }
-        // Ensure the token is sent with all future requests
-        __classPrivateFieldSet(this, _RegistryClient_fetch, __classPrivateFieldGet(this, _RegistryClient_fetch, "f").defaults({
-            headers: { [constants_1.HEADER_AUTHORIZATION]: `Bearer ${token}` },
-        }), "f");
-    }
-    // Check the registry API version
-    async checkVersion() {
-        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/`);
-        return response.headers.get(constants_1.HEADER_API_VERSION) || '';
-    }
-    // Upload a blob to the registry using the post/put method. Calculates the
-    // digest of the blob and checks to make sure the blob doesn't already exist
-    // in the registry before uploading.
-    async uploadBlob(blob) {
-        const digest = RegistryClient.digest(blob);
-        const size = blob.length;
-        // Check if blob already exists
-        const headResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/${digest}`, { method: 'HEAD', redirect: 'follow' });
-        if (headResponse.status === 200) {
-            return {
-                mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM,
-                digest,
-                size,
-            };
-        }
-        // Retrieve upload location (session ID)
-        const postResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/blobs/uploads/`, { method: 'POST' }).then((0, error_1.ensureStatus)(202));
-        const location = postResponse.headers.get(constants_1.HEADER_LOCATION);
-        if (!location) {
-            throw new Error('Missing location for blob upload');
-        }
-        // Translate location to a full URL
-        const uploadLocation = new URL(location.startsWith('/') ? `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}${location}` : location);
-        // Add digest to query string
-        uploadLocation.searchParams.set('digest', digest);
-        // Upload blob
-        await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, uploadLocation.href, {
-            method: 'PUT',
-            body: blob,
-            headers: { [constants_1.HEADER_CONTENT_TYPE]: constants_1.CONTENT_TYPE_OCTET_STREAM },
-        }).then((0, error_1.ensureStatus)(201));
-        return { mediaType: constants_1.CONTENT_TYPE_OCTET_STREAM, digest, size };
-    }
-    // Checks for the existence of a manifest by reference
-    async checkManifest(reference) {
-        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, {
-            method: 'HEAD',
-            headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES },
-        }).then((0, error_1.ensureStatus)(200));
-        const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) ||
-            /* istanbul ignore next */ '';
-        const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ '';
-        const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) ||
-            /* istanbul ignore next */ 0;
-        return { mediaType, digest, size };
-    }
-    // Retrieves a manifest by reference
-    async getManifest(reference) {
-        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, {
-            headers: { [constants_1.HEADER_ACCEPT]: ALL_MANIFEST_MEDIA_TYPES },
-        }).then((0, error_1.ensureStatus)(200));
-        const body = await response.json();
-        const mediaType = response.headers.get(constants_1.HEADER_CONTENT_TYPE) ||
-            /* istanbul ignore next */ '';
-        const digest = response.headers.get(constants_1.HEADER_DIGEST) || /* istanbul ignore next */ '';
-        const size = Number(response.headers.get(constants_1.HEADER_CONTENT_LENGTH)) || 0;
-        const etag = response.headers.get(constants_1.HEADER_ETAG) || undefined;
-        return { body, mediaType, digest, size, etag };
-    }
-    // Uploads a manifest by digest. If specified, the reference will be used as
-    // the manifest tag.
-    async uploadManifest(manifest, options = {}) {
-        const digest = RegistryClient.digest(manifest);
-        const reference = options.reference || digest;
-        const contentType = options.mediaType || constants_1.CONTENT_TYPE_OCI_MANIFEST;
-        const headers = { [constants_1.HEADER_CONTENT_TYPE]: contentType };
-        if (options.etag) {
-            headers[constants_1.HEADER_IF_MATCH] = options.etag;
-        }
-        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/manifests/${reference}`, { method: 'PUT', body: manifest, headers }).then((0, error_1.ensureStatus)(201));
-        const subjectDigest = response.headers.get(constants_1.HEADER_OCI_SUBJECT) || undefined;
-        return {
-            mediaType: contentType,
-            digest,
-            size: manifest.length,
-            subjectDigest,
-        };
-    }
-    // Returns true if the registry supports the referrers API
-    async pingReferrers() {
-        const response = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, `${__classPrivateFieldGet(this, _RegistryClient_baseURL, "f")}/v2/${__classPrivateFieldGet(this, _RegistryClient_repository, "f")}/referrers/${exports.ZERO_DIGEST}`);
-        return response.status === 200;
-    }
-    static digest(blob) {
-        const hash = node_crypto_1.default.createHash('sha256');
-        hash.update(blob);
-        return `sha256:${hash.digest('hex')}`;
+  return Promise.resolve().then(function () {
+    if (!state.registry[name]) {
+      return method(options);
     }
+
+    return state.registry[name].reduce(function (method, registered) {
+      return registered.hook.bind(null, method, options);
+    }, method)();
+  });
 }
-exports.RegistryClient = RegistryClient;
-_RegistryClient_baseURL = new WeakMap(), _RegistryClient_repository = new WeakMap(), _RegistryClient_fetch = new WeakMap(), _RegistryClient_instances = new WeakSet(), _RegistryClient_fetchDistributionToken = async function _RegistryClient_fetchDistributionToken(creds, challenge) {
-    const basicAuth = (0, credentials_1.toBasicAuth)(creds);
-    const authURL = new URL(challenge.realm);
-    authURL.searchParams.set('service', challenge.service);
-    authURL.searchParams.set('scope', challenge.scope);
-    // Make token request with basic auth
-    const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, authURL.toString(), {
-        headers: { [constants_1.HEADER_AUTHORIZATION]: `Basic ${basicAuth}` },
-    }).then((0, error_1.ensureStatus)(200));
-    return tokenResponse.json().then((json) => json.access_token || json.token);
-}, _RegistryClient_fetchOAuth2Token = async function _RegistryClient_fetchOAuth2Token(creds, challenge) {
-    const body = new URLSearchParams({
-        service: challenge.service,
-        scope: challenge.scope,
-        username: creds.username,
-        password: creds.password,
-        grant_type: 'password',
-    });
-    // Make OAuth token request
-    const tokenResponse = await __classPrivateFieldGet(this, _RegistryClient_fetch, "f").call(this, challenge.realm, {
-        method: 'POST',
-        body,
-    }).then((0, error_1.ensureStatus)(200));
-    return tokenResponse.json().then((json) => json.access_token);
-};
-// Parses an auth challenge header into its components
-// https://datatracker.ietf.org/doc/html/rfc7235#section-4.1
-function parseChallenge(challenge) {
-    // Account for the possibility of spaces in the auth params
-    const [scheme, ...rest] = challenge.split(' ');
-    const authParams = rest.join(' ');
-    if (!['Basic', 'Bearer'].includes(scheme)) {
-        throw new Error(`Invalid challenge: ${challenge}`);
-    }
-    return {
-        scheme: scheme.toLocaleLowerCase(),
-        realm: singleMatch(authParams, /realm="(.+?)"/),
-        service: singleMatch(authParams, /service="(.+?)"/),
-        scope: singleMatch(authParams, /scope="(.+?)"/),
-    };
+
+
+/***/ }),
+
+/***/ 59934:
+/***/ ((module) => {
+
+module.exports = removeHook;
+
+function removeHook(state, name, method) {
+  if (!state.registry[name]) {
+    return;
+  }
+
+  var index = state.registry[name]
+    .map(function (registered) {
+      return registered.orig;
+    })
+    .indexOf(method);
+
+  if (index === -1) {
+    return;
+  }
+
+  state.registry[name].splice(index, 1);
 }
-// Returns the first capture group of a regex match, or an empty string
-const singleMatch = (str, regex) => str.match(regex)?.[1] || '';
 
 
-/***/ }),
+/***/ }),
+
+/***/ 63251:
+/***/ (function(module) {
+
+/**
+  * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support.
+  * https://github.com/SGrondin/bottleneck
+  */
+(function (global, factory) {
+	 true ? module.exports = factory() :
+	0;
+}(this, (function () { 'use strict';
+
+	var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
+
+	function getCjsExportFromNamespace (n) {
+		return n && n['default'] || n;
+	}
+
+	var load = function(received, defaults, onto = {}) {
+	  var k, ref, v;
+	  for (k in defaults) {
+	    v = defaults[k];
+	    onto[k] = (ref = received[k]) != null ? ref : v;
+	  }
+	  return onto;
+	};
+
+	var overwrite = function(received, defaults, onto = {}) {
+	  var k, v;
+	  for (k in received) {
+	    v = received[k];
+	    if (defaults[k] !== void 0) {
+	      onto[k] = v;
+	    }
+	  }
+	  return onto;
+	};
+
+	var parser = {
+		load: load,
+		overwrite: overwrite
+	};
+
+	var DLList;
+
+	DLList = class DLList {
+	  constructor(incr, decr) {
+	    this.incr = incr;
+	    this.decr = decr;
+	    this._first = null;
+	    this._last = null;
+	    this.length = 0;
+	  }
+
+	  push(value) {
+	    var node;
+	    this.length++;
+	    if (typeof this.incr === "function") {
+	      this.incr();
+	    }
+	    node = {
+	      value,
+	      prev: this._last,
+	      next: null
+	    };
+	    if (this._last != null) {
+	      this._last.next = node;
+	      this._last = node;
+	    } else {
+	      this._first = this._last = node;
+	    }
+	    return void 0;
+	  }
+
+	  shift() {
+	    var value;
+	    if (this._first == null) {
+	      return;
+	    } else {
+	      this.length--;
+	      if (typeof this.decr === "function") {
+	        this.decr();
+	      }
+	    }
+	    value = this._first.value;
+	    if ((this._first = this._first.next) != null) {
+	      this._first.prev = null;
+	    } else {
+	      this._last = null;
+	    }
+	    return value;
+	  }
+
+	  first() {
+	    if (this._first != null) {
+	      return this._first.value;
+	    }
+	  }
+
+	  getArray() {
+	    var node, ref, results;
+	    node = this._first;
+	    results = [];
+	    while (node != null) {
+	      results.push((ref = node, node = node.next, ref.value));
+	    }
+	    return results;
+	  }
+
+	  forEachShift(cb) {
+	    var node;
+	    node = this.shift();
+	    while (node != null) {
+	      (cb(node), node = this.shift());
+	    }
+	    return void 0;
+	  }
+
+	  debug() {
+	    var node, ref, ref1, ref2, results;
+	    node = this._first;
+	    results = [];
+	    while (node != null) {
+	      results.push((ref = node, node = node.next, {
+	        value: ref.value,
+	        prev: (ref1 = ref.prev) != null ? ref1.value : void 0,
+	        next: (ref2 = ref.next) != null ? ref2.value : void 0
+	      }));
+	    }
+	    return results;
+	  }
 
-/***/ 43049:
-/***/ ((__unused_webpack_module, exports) => {
+	};
 
-"use strict";
+	var DLList_1 = DLList;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.BaseBundleBuilder = void 0;
-// BaseBundleBuilder is a base class for BundleBuilder implementations. It
-// provides a the basic wokflow for signing and witnessing an artifact.
-// Subclasses must implement the `package` method to assemble a valid bundle
-// with the generated signature and verification material.
-class BaseBundleBuilder {
-    constructor(options) {
-        this.signer = options.signer;
-        this.witnesses = options.witnesses;
-    }
-    // Executes the signing/witnessing process for the given artifact.
-    async create(artifact) {
-        const signature = await this.prepare(artifact).then((blob) => this.signer.sign(blob));
-        const bundle = await this.package(artifact, signature);
-        // Invoke all of the witnesses in parallel
-        const verificationMaterials = await Promise.all(this.witnesses.map((witness) => witness.testify(bundle.content, publicKey(signature.key))));
-        // Collect the verification material from all of the witnesses
-        const tlogEntryList = [];
-        const timestampList = [];
-        verificationMaterials.forEach(({ tlogEntries, rfc3161Timestamps }) => {
-            tlogEntryList.push(...(tlogEntries ?? []));
-            timestampList.push(...(rfc3161Timestamps ?? []));
-        });
-        // Merge the collected verification material into the bundle
-        bundle.verificationMaterial.tlogEntries = tlogEntryList;
-        bundle.verificationMaterial.timestampVerificationData = {
-            rfc3161Timestamps: timestampList,
-        };
-        return bundle;
-    }
-    // Override this function to apply any pre-signing transformations to the
-    // artifact. The returned buffer will be signed by the signer. The default
-    // implementation simply returns the artifact data.
-    async prepare(artifact) {
-        return artifact.data;
-    }
-}
-exports.BaseBundleBuilder = BaseBundleBuilder;
-// Extracts the public key from a KeyMaterial. Returns either the public key
-// or the certificate, depending on the type of key material.
-function publicKey(key) {
-    switch (key.$case) {
-        case 'publicKey':
-            return key.publicKey;
-        case 'x509Certificate':
-            return key.certificate;
-    }
-}
+	var Events;
 
+	Events = class Events {
+	  constructor(instance) {
+	    this.instance = instance;
+	    this._events = {};
+	    if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) {
+	      throw new Error("An Emitter already exists for this object");
+	    }
+	    this.instance.on = (name, cb) => {
+	      return this._addListener(name, "many", cb);
+	    };
+	    this.instance.once = (name, cb) => {
+	      return this._addListener(name, "once", cb);
+	    };
+	    this.instance.removeAllListeners = (name = null) => {
+	      if (name != null) {
+	        return delete this._events[name];
+	      } else {
+	        return this._events = {};
+	      }
+	    };
+	  }
 
-/***/ }),
+	  _addListener(name, status, cb) {
+	    var base;
+	    if ((base = this._events)[name] == null) {
+	      base[name] = [];
+	    }
+	    this._events[name].push({cb, status});
+	    return this.instance;
+	  }
 
-/***/ 85192:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+	  listenerCount(name) {
+	    if (this._events[name] != null) {
+	      return this._events[name].length;
+	    } else {
+	      return 0;
+	    }
+	  }
 
-"use strict";
+	  async trigger(name, ...args) {
+	    var e, promises;
+	    try {
+	      if (name !== "debug") {
+	        this.trigger("debug", `Event triggered: ${name}`, args);
+	      }
+	      if (this._events[name] == null) {
+	        return;
+	      }
+	      this._events[name] = this._events[name].filter(function(listener) {
+	        return listener.status !== "none";
+	      });
+	      promises = this._events[name].map(async(listener) => {
+	        var e, returned;
+	        if (listener.status === "none") {
+	          return;
+	        }
+	        if (listener.status === "once") {
+	          listener.status = "none";
+	        }
+	        try {
+	          returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0;
+	          if (typeof (returned != null ? returned.then : void 0) === "function") {
+	            return (await returned);
+	          } else {
+	            return returned;
+	          }
+	        } catch (error) {
+	          e = error;
+	          {
+	            this.trigger("error", e);
+	          }
+	          return null;
+	        }
+	      });
+	      return ((await Promise.all(promises))).find(function(x) {
+	        return x != null;
+	      });
+	    } catch (error) {
+	      e = error;
+	      {
+	        this.trigger("error", e);
+	      }
+	      return null;
+	    }
+	  }
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toMessageSignatureBundle = toMessageSignatureBundle;
-exports.toDSSEBundle = toDSSEBundle;
-/*
-Copyright 2023 The Sigstore Authors.
+	};
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	var Events_1 = Events;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	var DLList$1, Events$1, Queues;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const sigstore = __importStar(__nccwpck_require__(61040));
-const util_1 = __nccwpck_require__(19100);
-// Helper functions for assembling the parts of a Sigstore bundle
-// Message signature bundle - $case: 'messageSignature'
-function toMessageSignatureBundle(artifact, signature) {
-    const digest = util_1.crypto.digest('sha256', artifact.data);
-    return sigstore.toMessageSignatureBundle({
-        digest,
-        signature: signature.signature,
-        certificate: signature.key.$case === 'x509Certificate'
-            ? util_1.pem.toDER(signature.key.certificate)
-            : undefined,
-        keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined,
-        certificateChain: true,
-    });
-}
-// DSSE envelope bundle - $case: 'dsseEnvelope'
-function toDSSEBundle(artifact, signature, certificateChain) {
-    return sigstore.toDSSEBundle({
-        artifact: artifact.data,
-        artifactType: artifact.type,
-        signature: signature.signature,
-        certificate: signature.key.$case === 'x509Certificate'
-            ? util_1.pem.toDER(signature.key.certificate)
-            : undefined,
-        keyHint: signature.key.$case === 'publicKey' ? signature.key.hint : undefined,
-        certificateChain,
-    });
-}
+	DLList$1 = DLList_1;
 
+	Events$1 = Events_1;
 
-/***/ }),
+	Queues = class Queues {
+	  constructor(num_priorities) {
+	    var i;
+	    this.Events = new Events$1(this);
+	    this._length = 0;
+	    this._lists = (function() {
+	      var j, ref, results;
+	      results = [];
+	      for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {
+	        results.push(new DLList$1((() => {
+	          return this.incr();
+	        }), (() => {
+	          return this.decr();
+	        })));
+	      }
+	      return results;
+	    }).call(this);
+	  }
 
-/***/ 83997:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	  incr() {
+	    if (this._length++ === 0) {
+	      return this.Events.trigger("leftzero");
+	    }
+	  }
 
-"use strict";
+	  decr() {
+	    if (--this._length === 0) {
+	      return this.Events.trigger("zero");
+	    }
+	  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DSSEBundleBuilder = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	  push(job) {
+	    return this._lists[job.options.priority].push(job);
+	  }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  queued(priority) {
+	    if (priority != null) {
+	      return this._lists[priority].length;
+	    } else {
+	      return this._length;
+	    }
+	  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  shiftAll(fn) {
+	    return this._lists.forEach(function(list) {
+	      return list.forEachShift(fn);
+	    });
+	  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const util_1 = __nccwpck_require__(19100);
-const base_1 = __nccwpck_require__(43049);
-const bundle_1 = __nccwpck_require__(85192);
-// BundleBuilder implementation for DSSE wrapped attestations
-class DSSEBundleBuilder extends base_1.BaseBundleBuilder {
-    constructor(options) {
-        super(options);
-        this.certificateChain = options.certificateChain ?? false;
-    }
-    // DSSE requires the artifact to be pre-encoded with the payload type
-    // before the signature is generated.
-    async prepare(artifact) {
-        const a = artifactDefaults(artifact);
-        return util_1.dsse.preAuthEncoding(a.type, a.data);
-    }
-    // Packages the artifact and signature into a DSSE bundle
-    async package(artifact, signature) {
-        return (0, bundle_1.toDSSEBundle)(artifactDefaults(artifact), signature, this.certificateChain);
-    }
-}
-exports.DSSEBundleBuilder = DSSEBundleBuilder;
-// Defaults the artifact type to an empty string if not provided
-function artifactDefaults(artifact) {
-    return {
-        ...artifact,
-        type: artifact.type ?? '',
-    };
-}
+	  getFirst(arr = this._lists) {
+	    var j, len, list;
+	    for (j = 0, len = arr.length; j < len; j++) {
+	      list = arr[j];
+	      if (list.length > 0) {
+	        return list;
+	      }
+	    }
+	    return [];
+	  }
 
+	  shiftLastFrom(priority) {
+	    return this.getFirst(this._lists.slice(priority).reverse()).shift();
+	  }
 
-/***/ }),
+	};
 
-/***/ 35530:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	var Queues_1 = Queues;
 
-"use strict";
+	var BottleneckError;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0;
-var dsse_1 = __nccwpck_require__(83997);
-Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return dsse_1.DSSEBundleBuilder; } }));
-var message_1 = __nccwpck_require__(8269);
-Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return message_1.MessageSignatureBundleBuilder; } }));
+	BottleneckError = class BottleneckError extends Error {};
 
+	var BottleneckError_1 = BottleneckError;
 
-/***/ }),
+	var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1;
 
-/***/ 8269:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	NUM_PRIORITIES = 10;
 
-"use strict";
+	DEFAULT_PRIORITY = 5;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MessageSignatureBundleBuilder = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	parser$1 = parser;
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	BottleneckError$1 = BottleneckError_1;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	Job = class Job {
+	  constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) {
+	    this.task = task;
+	    this.args = args;
+	    this.rejectOnDrop = rejectOnDrop;
+	    this.Events = Events;
+	    this._states = _states;
+	    this.Promise = Promise;
+	    this.options = parser$1.load(options, jobDefaults);
+	    this.options.priority = this._sanitizePriority(this.options.priority);
+	    if (this.options.id === jobDefaults.id) {
+	      this.options.id = `${this.options.id}-${this._randomIndex()}`;
+	    }
+	    this.promise = new this.Promise((_resolve, _reject) => {
+	      this._resolve = _resolve;
+	      this._reject = _reject;
+	    });
+	    this.retryCount = 0;
+	  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const base_1 = __nccwpck_require__(43049);
-const bundle_1 = __nccwpck_require__(85192);
-// BundleBuilder implementation for raw message signatures
-class MessageSignatureBundleBuilder extends base_1.BaseBundleBuilder {
-    constructor(options) {
-        super(options);
-    }
-    async package(artifact, signature) {
-        return (0, bundle_1.toMessageSignatureBundle)(artifact, signature);
-    }
-}
-exports.MessageSignatureBundleBuilder = MessageSignatureBundleBuilder;
+	  _sanitizePriority(priority) {
+	    var sProperty;
+	    sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;
+	    if (sProperty < 0) {
+	      return 0;
+	    } else if (sProperty > NUM_PRIORITIES - 1) {
+	      return NUM_PRIORITIES - 1;
+	    } else {
+	      return sProperty;
+	    }
+	  }
 
+	  _randomIndex() {
+	    return Math.random().toString(36).slice(2);
+	  }
 
-/***/ }),
+	  doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) {
+	    if (this._states.remove(this.options.id)) {
+	      if (this.rejectOnDrop) {
+	        this._reject(error != null ? error : new BottleneckError$1(message));
+	      }
+	      this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise});
+	      return true;
+	    } else {
+	      return false;
+	    }
+	  }
 
-/***/ 97841:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	  _assertStatus(expected) {
+	    var status;
+	    status = this._states.jobStatus(this.options.id);
+	    if (!(status === expected || (expected === "DONE" && status === null))) {
+	      throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`);
+	    }
+	  }
 
-"use strict";
+	  doReceive() {
+	    this._states.start(this.options.id);
+	    return this.Events.trigger("received", {args: this.args, options: this.options});
+	  }
 
-/*
-Copyright 2023 The Sigstore Authors.
+	  doQueue(reachedHWM, blocked) {
+	    this._assertStatus("RECEIVED");
+	    this._states.next(this.options.id);
+	    return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked});
+	  }
+
+	  doRun() {
+	    if (this.retryCount === 0) {
+	      this._assertStatus("QUEUED");
+	      this._states.next(this.options.id);
+	    } else {
+	      this._assertStatus("EXECUTING");
+	    }
+	    return this.Events.trigger("scheduled", {args: this.args, options: this.options});
+	  }
+
+	  async doExecute(chained, clearGlobalState, run, free) {
+	    var error, eventInfo, passed;
+	    if (this.retryCount === 0) {
+	      this._assertStatus("RUNNING");
+	      this._states.next(this.options.id);
+	    } else {
+	      this._assertStatus("EXECUTING");
+	    }
+	    eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};
+	    this.Events.trigger("executing", eventInfo);
+	    try {
+	      passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)));
+	      if (clearGlobalState()) {
+	        this.doDone(eventInfo);
+	        await free(this.options, eventInfo);
+	        this._assertStatus("DONE");
+	        return this._resolve(passed);
+	      }
+	    } catch (error1) {
+	      error = error1;
+	      return this._onFailure(error, eventInfo, clearGlobalState, run, free);
+	    }
+	  }
+
+	  doExpire(clearGlobalState, run, free) {
+	    var error, eventInfo;
+	    if (this._states.jobStatus(this.options.id === "RUNNING")) {
+	      this._states.next(this.options.id);
+	    }
+	    this._assertStatus("EXECUTING");
+	    eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};
+	    error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`);
+	    return this._onFailure(error, eventInfo, clearGlobalState, run, free);
+	  }
+
+	  async _onFailure(error, eventInfo, clearGlobalState, run, free) {
+	    var retry, retryAfter;
+	    if (clearGlobalState()) {
+	      retry = (await this.Events.trigger("failed", error, eventInfo));
+	      if (retry != null) {
+	        retryAfter = ~~retry;
+	        this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo);
+	        this.retryCount++;
+	        return run(retryAfter);
+	      } else {
+	        this.doDone(eventInfo);
+	        await free(this.options, eventInfo);
+	        this._assertStatus("DONE");
+	        return this._reject(error);
+	      }
+	    }
+	  }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  doDone(eventInfo) {
+	    this._assertStatus("EXECUTING");
+	    this._states.next(this.options.id);
+	    return this.Events.trigger("done", eventInfo);
+	  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	};
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.InternalError = void 0;
-exports.internalError = internalError;
-const error_1 = __nccwpck_require__(40369);
-class InternalError extends Error {
-    constructor({ code, message, cause, }) {
-        super(message);
-        this.name = this.constructor.name;
-        this.cause = cause;
-        this.code = code;
-    }
-}
-exports.InternalError = InternalError;
-function internalError(err, code, message) {
-    if (err instanceof error_1.HTTPError) {
-        message += ` - ${err.message}`;
-    }
-    throw new InternalError({
-        code: code,
-        message: message,
-        cause: err,
-    });
-}
+	var Job_1 = Job;
 
+	var BottleneckError$2, LocalDatastore, parser$2;
 
-/***/ }),
+	parser$2 = parser;
 
-/***/ 40369:
-/***/ ((__unused_webpack_module, exports) => {
+	BottleneckError$2 = BottleneckError_1;
 
-"use strict";
+	LocalDatastore = class LocalDatastore {
+	  constructor(instance, storeOptions, storeInstanceOptions) {
+	    this.instance = instance;
+	    this.storeOptions = storeOptions;
+	    this.clientId = this.instance._randomIndex();
+	    parser$2.load(storeInstanceOptions, storeInstanceOptions, this);
+	    this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now();
+	    this._running = 0;
+	    this._done = 0;
+	    this._unblockTime = 0;
+	    this.ready = this.Promise.resolve();
+	    this.clients = {};
+	    this._startHeartbeat();
+	  }
 
-/*
-Copyright 2023 The Sigstore Authors.
+	  _startHeartbeat() {
+	    var base;
+	    if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) {
+	      return typeof (base = (this.heartbeat = setInterval(() => {
+	        var amount, incr, maximum, now, reservoir;
+	        now = Date.now();
+	        if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) {
+	          this._lastReservoirRefresh = now;
+	          this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount;
+	          this.instance._drainAll(this.computeCapacity());
+	        }
+	        if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {
+	          ({
+	            reservoirIncreaseAmount: amount,
+	            reservoirIncreaseMaximum: maximum,
+	            reservoir
+	          } = this.storeOptions);
+	          this._lastReservoirIncrease = now;
+	          incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount;
+	          if (incr > 0) {
+	            this.storeOptions.reservoir += incr;
+	            return this.instance._drainAll(this.computeCapacity());
+	          }
+	        }
+	      }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0;
+	    } else {
+	      return clearInterval(this.heartbeat);
+	    }
+	  }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  async __publish__(message) {
+	    await this.yieldLoop();
+	    return this.instance.Events.trigger("message", message.toString());
+	  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  async __disconnect__(flush) {
+	    await this.yieldLoop();
+	    clearInterval(this.heartbeat);
+	    return this.Promise.resolve();
+	  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HTTPError = void 0;
-class HTTPError extends Error {
-    constructor({ status, message, location, }) {
-        super(`(${status}) ${message}`);
-        this.statusCode = status;
-        this.location = location;
-    }
-}
-exports.HTTPError = HTTPError;
+	  yieldLoop(t = 0) {
+	    return new this.Promise(function(resolve, reject) {
+	      return setTimeout(resolve, t);
+	    });
+	  }
 
+	  computePenalty() {
+	    var ref;
+	    return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000;
+	  }
 
-/***/ }),
+	  async __updateSettings__(options) {
+	    await this.yieldLoop();
+	    parser$2.overwrite(options, options, this.storeOptions);
+	    this._startHeartbeat();
+	    this.instance._drainAll(this.computeCapacity());
+	    return true;
+	  }
 
-/***/ 9823:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+	  async __running__() {
+	    await this.yieldLoop();
+	    return this._running;
+	  }
 
-"use strict";
+	  async __queued__() {
+	    await this.yieldLoop();
+	    return this.instance.queued();
+	  }
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.fetchWithRetry = fetchWithRetry;
-/*
-Copyright 2023 The Sigstore Authors.
+	  async __done__() {
+	    await this.yieldLoop();
+	    return this._done;
+	  }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  async __groupCheck__(time) {
+	    await this.yieldLoop();
+	    return (this._nextRequest + this.timeout) < time;
+	  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  computeCapacity() {
+	    var maxConcurrent, reservoir;
+	    ({maxConcurrent, reservoir} = this.storeOptions);
+	    if ((maxConcurrent != null) && (reservoir != null)) {
+	      return Math.min(maxConcurrent - this._running, reservoir);
+	    } else if (maxConcurrent != null) {
+	      return maxConcurrent - this._running;
+	    } else if (reservoir != null) {
+	      return reservoir;
+	    } else {
+	      return null;
+	    }
+	  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const http2_1 = __nccwpck_require__(85675);
-const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310));
-const proc_log_1 = __nccwpck_require__(26687);
-const promise_retry_1 = __importDefault(__nccwpck_require__(90390));
-const util_1 = __nccwpck_require__(19100);
-const error_1 = __nccwpck_require__(40369);
-const { HTTP2_HEADER_LOCATION, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_USER_AGENT, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_REQUEST_TIMEOUT, } = http2_1.constants;
-async function fetchWithRetry(url, options) {
-    return (0, promise_retry_1.default)(async (retry, attemptNum) => {
-        const method = options.method || 'POST';
-        const headers = {
-            [HTTP2_HEADER_USER_AGENT]: util_1.ua.getUserAgent(),
-            ...options.headers,
-        };
-        const response = await (0, make_fetch_happen_1.default)(url, {
-            method,
-            headers,
-            body: options.body,
-            timeout: options.timeout,
-            retry: false, // We're handling retries ourselves
-        }).catch((reason) => {
-            proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${reason}`);
-            return retry(reason);
-        });
-        if (response.ok) {
-            return response;
-        }
-        else {
-            const error = await errorFromResponse(response);
-            proc_log_1.log.http('fetch', `${method} ${url} attempt ${attemptNum} failed with ${response.status}`);
-            if (retryable(response.status)) {
-                return retry(error);
-            }
-            else {
-                throw error;
-            }
-        }
-    }, retryOpts(options.retry));
-}
-// Translate a Response into an HTTPError instance. This will attempt to parse
-// the response body for a message, but will default to the statusText if none
-// is found.
-const errorFromResponse = async (response) => {
-    let message = response.statusText;
-    const location = response.headers.get(HTTP2_HEADER_LOCATION) || undefined;
-    const contentType = response.headers.get(HTTP2_HEADER_CONTENT_TYPE);
-    // If response type is JSON, try to parse the body for a message
-    if (contentType?.includes('application/json')) {
-        try {
-            const body = await response.json();
-            message = body.message || message;
-        }
-        catch (e) {
-            // ignore
-        }
-    }
-    return new error_1.HTTPError({
-        status: response.status,
-        message: message,
-        location: location,
-    });
-};
-// Determine if a status code is retryable. This includes 5xx errors, 408, and
-// 429.
-const retryable = (status) => [HTTP_STATUS_REQUEST_TIMEOUT, HTTP_STATUS_TOO_MANY_REQUESTS].includes(status) || status >= HTTP_STATUS_INTERNAL_SERVER_ERROR;
-// Normalize the retry options to the format expected by promise-retry
-const retryOpts = (retry) => {
-    if (typeof retry === 'boolean') {
-        return { retries: retry ? 1 : 0 };
-    }
-    else if (typeof retry === 'number') {
-        return { retries: retry };
-    }
-    else {
-        return { retries: 0, ...retry };
-    }
-};
+	  conditionsCheck(weight) {
+	    var capacity;
+	    capacity = this.computeCapacity();
+	    return (capacity == null) || weight <= capacity;
+	  }
 
+	  async __incrementReservoir__(incr) {
+	    var reservoir;
+	    await this.yieldLoop();
+	    reservoir = this.storeOptions.reservoir += incr;
+	    this.instance._drainAll(this.computeCapacity());
+	    return reservoir;
+	  }
 
-/***/ }),
+	  async __currentReservoir__() {
+	    await this.yieldLoop();
+	    return this.storeOptions.reservoir;
+	  }
 
-/***/ 26819:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	  isBlocked(now) {
+	    return this._unblockTime >= now;
+	  }
 
-"use strict";
+	  check(weight, now) {
+	    return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0;
+	  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Fulcio = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	  async __check__(weight) {
+	    var now;
+	    await this.yieldLoop();
+	    now = Date.now();
+	    return this.check(weight, now);
+	  }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  async __register__(index, weight, expiration) {
+	    var now, wait;
+	    await this.yieldLoop();
+	    now = Date.now();
+	    if (this.conditionsCheck(weight)) {
+	      this._running += weight;
+	      if (this.storeOptions.reservoir != null) {
+	        this.storeOptions.reservoir -= weight;
+	      }
+	      wait = Math.max(this._nextRequest - now, 0);
+	      this._nextRequest = now + wait + this.storeOptions.minTime;
+	      return {
+	        success: true,
+	        wait,
+	        reservoir: this.storeOptions.reservoir
+	      };
+	    } else {
+	      return {
+	        success: false
+	      };
+	    }
+	  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  strategyIsBlock() {
+	    return this.storeOptions.strategy === 3;
+	  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const fetch_1 = __nccwpck_require__(9823);
-/**
- * Fulcio API client.
- */
-class Fulcio {
-    constructor(options) {
-        this.options = options;
-    }
-    async createSigningCertificate(request) {
-        const { baseURL, retry, timeout } = this.options;
-        const url = `${baseURL}/api/v2/signingCert`;
-        const response = await (0, fetch_1.fetchWithRetry)(url, {
-            headers: {
-                'Content-Type': 'application/json',
-            },
-            body: JSON.stringify(request),
-            timeout,
-            retry,
-        });
-        return response.json();
-    }
-}
-exports.Fulcio = Fulcio;
+	  async __submit__(queueLength, weight) {
+	    var blocked, now, reachedHWM;
+	    await this.yieldLoop();
+	    if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) {
+	      throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);
+	    }
+	    now = Date.now();
+	    reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now);
+	    blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));
+	    if (blocked) {
+	      this._unblockTime = now + this.computePenalty();
+	      this._nextRequest = this._unblockTime + this.storeOptions.minTime;
+	      this.instance._dropAllQueued();
+	    }
+	    return {
+	      reachedHWM,
+	      blocked,
+	      strategy: this.storeOptions.strategy
+	    };
+	  }
 
+	  async __free__(index, weight) {
+	    await this.yieldLoop();
+	    this._running -= weight;
+	    this._done += weight;
+	    this.instance._drainAll(this.computeCapacity());
+	    return {
+	      running: this._running
+	    };
+	  }
 
-/***/ }),
+	};
 
-/***/ 32688:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	var LocalDatastore_1 = LocalDatastore;
 
-"use strict";
+	var BottleneckError$3, States;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Rekor = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	BottleneckError$3 = BottleneckError_1;
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	States = class States {
+	  constructor(status1) {
+	    this.status = status1;
+	    this._jobs = {};
+	    this.counts = this.status.map(function() {
+	      return 0;
+	    });
+	  }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  next(id) {
+	    var current, next;
+	    current = this._jobs[id];
+	    next = current + 1;
+	    if ((current != null) && next < this.status.length) {
+	      this.counts[current]--;
+	      this.counts[next]++;
+	      return this._jobs[id]++;
+	    } else if (current != null) {
+	      this.counts[current]--;
+	      return delete this._jobs[id];
+	    }
+	  }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const fetch_1 = __nccwpck_require__(9823);
-/**
- * Rekor API client.
- */
-class Rekor {
-    constructor(options) {
-        this.options = options;
-    }
-    /**
-     * Create a new entry in the Rekor log.
-     * @param propsedEntry {ProposedEntry} Data to create a new entry
-     * @returns {Promise} The created entry
-     */
-    async createEntry(propsedEntry) {
-        const { baseURL, timeout, retry } = this.options;
-        const url = `${baseURL}/api/v1/log/entries`;
-        const response = await (0, fetch_1.fetchWithRetry)(url, {
-            headers: {
-                'Content-Type': 'application/json',
-                Accept: 'application/json',
-            },
-            body: JSON.stringify(propsedEntry),
-            timeout,
-            retry,
-        });
-        const data = await response.json();
-        return entryFromResponse(data);
-    }
-    /**
-     * Get an entry from the Rekor log.
-     * @param uuid {string} The UUID of the entry to retrieve
-     * @returns {Promise} The retrieved entry
-     */
-    async getEntry(uuid) {
-        const { baseURL, timeout, retry } = this.options;
-        const url = `${baseURL}/api/v1/log/entries/${uuid}`;
-        const response = await (0, fetch_1.fetchWithRetry)(url, {
-            method: 'GET',
-            headers: {
-                Accept: 'application/json',
-            },
-            timeout,
-            retry,
-        });
-        const data = await response.json();
-        return entryFromResponse(data);
-    }
-}
-exports.Rekor = Rekor;
-// Unpack the response from the Rekor API into a more convenient format.
-function entryFromResponse(data) {
-    const entries = Object.entries(data);
-    if (entries.length != 1) {
-        throw new Error('Received multiple entries in Rekor response');
-    }
-    // Grab UUID and entry data from the response
-    const [uuid, entry] = entries[0];
-    return {
-        ...entry,
-        uuid,
-    };
-}
+	  start(id) {
+	    var initial;
+	    initial = 0;
+	    this._jobs[id] = initial;
+	    return this.counts[initial]++;
+	  }
 
+	  remove(id) {
+	    var current;
+	    current = this._jobs[id];
+	    if (current != null) {
+	      this.counts[current]--;
+	      delete this._jobs[id];
+	    }
+	    return current != null;
+	  }
 
-/***/ }),
+	  jobStatus(id) {
+	    var ref;
+	    return (ref = this.status[this._jobs[id]]) != null ? ref : null;
+	  }
 
-/***/ 78963:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	  statusJobs(status) {
+	    var k, pos, ref, results, v;
+	    if (status != null) {
+	      pos = this.status.indexOf(status);
+	      if (pos < 0) {
+	        throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`);
+	      }
+	      ref = this._jobs;
+	      results = [];
+	      for (k in ref) {
+	        v = ref[k];
+	        if (v === pos) {
+	          results.push(k);
+	        }
+	      }
+	      return results;
+	    } else {
+	      return Object.keys(this._jobs);
+	    }
+	  }
 
-"use strict";
+	  statusCounts() {
+	    return this.counts.reduce(((acc, v, i) => {
+	      acc[this.status[i]] = v;
+	      return acc;
+	    }), {});
+	  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TimestampAuthority = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	};
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	var States_1 = States;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	var DLList$2, Sync;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const fetch_1 = __nccwpck_require__(9823);
-class TimestampAuthority {
-    constructor(options) {
-        this.options = options;
-    }
-    async createTimestamp(request) {
-        const { baseURL, timeout, retry } = this.options;
-        const url = `${baseURL}/api/v1/timestamp`;
-        const response = await (0, fetch_1.fetchWithRetry)(url, {
-            headers: {
-                'Content-Type': 'application/json',
-            },
-            body: JSON.stringify(request),
-            timeout,
-            retry,
-        });
-        return response.buffer();
-    }
-}
-exports.TimestampAuthority = TimestampAuthority;
+	DLList$2 = DLList_1;
 
+	Sync = class Sync {
+	  constructor(name, Promise) {
+	    this.schedule = this.schedule.bind(this);
+	    this.name = name;
+	    this.Promise = Promise;
+	    this._running = 0;
+	    this._queue = new DLList$2();
+	  }
 
-/***/ }),
+	  isEmpty() {
+	    return this._queue.length === 0;
+	  }
 
-/***/ 92092:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+	  async _tryToRun() {
+	    var args, cb, error, reject, resolve, returned, task;
+	    if ((this._running < 1) && this._queue.length > 0) {
+	      this._running++;
+	      ({task, args, resolve, reject} = this._queue.shift());
+	      cb = (await (async function() {
+	        try {
+	          returned = (await task(...args));
+	          return function() {
+	            return resolve(returned);
+	          };
+	        } catch (error1) {
+	          error = error1;
+	          return function() {
+	            return reject(error);
+	          };
+	        }
+	      })());
+	      this._running--;
+	      this._tryToRun();
+	      return cb();
+	    }
+	  }
 
-"use strict";
+	  schedule(task, ...args) {
+	    var promise, reject, resolve;
+	    resolve = reject = null;
+	    promise = new this.Promise(function(_resolve, _reject) {
+	      resolve = _resolve;
+	      return reject = _reject;
+	    });
+	    this._queue.push({task, args, resolve, reject});
+	    this._tryToRun();
+	    return promise;
+	  }
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.CIContextProvider = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	};
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	var Sync_1 = Sync;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	var version = "2.19.5";
+	var version$1 = {
+		version: version
+	};
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const make_fetch_happen_1 = __importDefault(__nccwpck_require__(39310));
-// Collection of all the CI-specific providers we have implemented
-const providers = [getGHAToken, getEnv];
-/**
- * CIContextProvider is a composite identity provider which will iterate
- * over all of the CI-specific providers and return the token from the first
- * one that resolves.
- */
-class CIContextProvider {
-    /* istanbul ignore next */
-    constructor(audience = 'sigstore') {
-        this.audience = audience;
-    }
-    // Invoke all registered ProviderFuncs and return the value of whichever one
-    // resolves first.
-    async getToken() {
-        return Promise.any(providers.map((getToken) => getToken(this.audience))).catch(() => Promise.reject('CI: no tokens available'));
-    }
-}
-exports.CIContextProvider = CIContextProvider;
-/**
- * getGHAToken can retrieve an OIDC token when running in a GitHub Actions
- * workflow
- */
-async function getGHAToken(audience) {
-    // Check to see if we're running in GitHub Actions
-    if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||
-        !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) {
-        return Promise.reject('no token available');
-    }
-    // Construct URL to request token w/ appropriate audience
-    const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);
-    url.searchParams.append('audience', audience);
-    const response = await (0, make_fetch_happen_1.default)(url.href, {
-        retry: 2,
-        headers: {
-            Accept: 'application/json',
-            Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`,
-        },
-    });
-    return response.json().then((data) => data.value);
-}
-/**
- * getEnv can retrieve an OIDC token from an environment variable.
- * This matches the behavior of https://github.com/sigstore/cosign/tree/main/pkg/providers/envvar
- */
-async function getEnv() {
-    if (!process.env.SIGSTORE_ID_TOKEN) {
-        return Promise.reject('no token available');
-    }
-    return process.env.SIGSTORE_ID_TOKEN;
-}
+	var version$2 = /*#__PURE__*/Object.freeze({
+		version: version,
+		default: version$1
+	});
 
+	var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
 
-/***/ }),
+	var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
 
-/***/ 55022:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
 
-"use strict";
+	var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.CIContextProvider = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	parser$3 = parser;
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	Events$2 = Events_1;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	RedisConnection$1 = require$$2;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-var ci_1 = __nccwpck_require__(92092);
-Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return ci_1.CIContextProvider; } }));
+	IORedisConnection$1 = require$$3;
 
+	Scripts$1 = require$$4;
 
-/***/ }),
+	Group = (function() {
+	  class Group {
+	    constructor(limiterOptions = {}) {
+	      this.deleteKey = this.deleteKey.bind(this);
+	      this.limiterOptions = limiterOptions;
+	      parser$3.load(this.limiterOptions, this.defaults, this);
+	      this.Events = new Events$2(this);
+	      this.instances = {};
+	      this.Bottleneck = Bottleneck_1;
+	      this._startAutoCleanup();
+	      this.sharedConnection = this.connection != null;
+	      if (this.connection == null) {
+	        if (this.limiterOptions.datastore === "redis") {
+	          this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));
+	        } else if (this.limiterOptions.datastore === "ioredis") {
+	          this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));
+	        }
+	      }
+	    }
 
-/***/ 15179:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	    key(key = "") {
+	      var ref;
+	      return (ref = this.instances[key]) != null ? ref : (() => {
+	        var limiter;
+	        limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {
+	          id: `${this.id}-${key}`,
+	          timeout: this.timeout,
+	          connection: this.connection
+	        }));
+	        this.Events.trigger("created", limiter, key);
+	        return limiter;
+	      })();
+	    }
 
-"use strict";
+	    async deleteKey(key = "") {
+	      var deleted, instance;
+	      instance = this.instances[key];
+	      if (this.connection) {
+	        deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)]));
+	      }
+	      if (instance != null) {
+	        delete this.instances[key];
+	        await instance.disconnect();
+	      }
+	      return (instance != null) || deleted > 0;
+	    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = exports.CIContextProvider = exports.InternalError = exports.MessageSignatureBundleBuilder = exports.DSSEBundleBuilder = void 0;
-var bundler_1 = __nccwpck_require__(35530);
-Object.defineProperty(exports, "DSSEBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.DSSEBundleBuilder; } }));
-Object.defineProperty(exports, "MessageSignatureBundleBuilder", ({ enumerable: true, get: function () { return bundler_1.MessageSignatureBundleBuilder; } }));
-var error_1 = __nccwpck_require__(97841);
-Object.defineProperty(exports, "InternalError", ({ enumerable: true, get: function () { return error_1.InternalError; } }));
-var identity_1 = __nccwpck_require__(55022);
-Object.defineProperty(exports, "CIContextProvider", ({ enumerable: true, get: function () { return identity_1.CIContextProvider; } }));
-var signer_1 = __nccwpck_require__(34342);
-Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return signer_1.DEFAULT_FULCIO_URL; } }));
-Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return signer_1.FulcioSigner; } }));
-var witness_1 = __nccwpck_require__(55383);
-Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return witness_1.DEFAULT_REKOR_URL; } }));
-Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return witness_1.RekorWitness; } }));
-Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return witness_1.TSAWitness; } }));
+	    limiters() {
+	      var k, ref, results, v;
+	      ref = this.instances;
+	      results = [];
+	      for (k in ref) {
+	        v = ref[k];
+	        results.push({
+	          key: k,
+	          limiter: v
+	        });
+	      }
+	      return results;
+	    }
 
+	    keys() {
+	      return Object.keys(this.instances);
+	    }
 
-/***/ }),
+	    async clusterKeys() {
+	      var cursor, end, found, i, k, keys, len, next, start;
+	      if (this.connection == null) {
+	        return this.Promise.resolve(this.keys());
+	      }
+	      keys = [];
+	      cursor = null;
+	      start = `b_${this.id}-`.length;
+	      end = "_settings".length;
+	      while (cursor !== 0) {
+	        [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000]));
+	        cursor = ~~next;
+	        for (i = 0, len = found.length; i < len; i++) {
+	          k = found[i];
+	          keys.push(k.slice(start, -end));
+	        }
+	      }
+	      return keys;
+	    }
 
-/***/ 5875:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	    _startAutoCleanup() {
+	      var base;
+	      clearInterval(this.interval);
+	      return typeof (base = (this.interval = setInterval(async() => {
+	        var e, k, ref, results, time, v;
+	        time = Date.now();
+	        ref = this.instances;
+	        results = [];
+	        for (k in ref) {
+	          v = ref[k];
+	          try {
+	            if ((await v._store.__groupCheck__(time))) {
+	              results.push(this.deleteKey(k));
+	            } else {
+	              results.push(void 0);
+	            }
+	          } catch (error) {
+	            e = error;
+	            results.push(v.Events.trigger("error", e));
+	          }
+	        }
+	        return results;
+	      }, this.timeout / 2))).unref === "function" ? base.unref() : void 0;
+	    }
 
-"use strict";
+	    updateSettings(options = {}) {
+	      parser$3.overwrite(options, this.defaults, this);
+	      parser$3.overwrite(options, options, this.limiterOptions);
+	      if (options.timeout != null) {
+	        return this._startAutoCleanup();
+	      }
+	    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.CAClient = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	    disconnect(flush = true) {
+	      var ref;
+	      if (!this.sharedConnection) {
+	        return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
+	      }
+	    }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  }
+	  Group.prototype.defaults = {
+	    timeout: 1000 * 60 * 5,
+	    connection: null,
+	    Promise: Promise,
+	    id: "group-key"
+	  };
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  return Group;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const error_1 = __nccwpck_require__(97841);
-const fulcio_1 = __nccwpck_require__(26819);
-class CAClient {
-    constructor(options) {
-        this.fulcio = new fulcio_1.Fulcio({
-            baseURL: options.fulcioBaseURL,
-            retry: options.retry,
-            timeout: options.timeout,
-        });
-    }
-    async createSigningCertificate(identityToken, publicKey, challenge) {
-        const request = toCertificateRequest(identityToken, publicKey, challenge);
-        try {
-            const resp = await this.fulcio.createSigningCertificate(request);
-            // Account for the fact that the response may contain either a
-            // signedCertificateEmbeddedSct or a signedCertificateDetachedSct.
-            const cert = resp.signedCertificateEmbeddedSct
-                ? resp.signedCertificateEmbeddedSct
-                : resp.signedCertificateDetachedSct;
-            return cert.chain.certificates;
-        }
-        catch (err) {
-            (0, error_1.internalError)(err, 'CA_CREATE_SIGNING_CERTIFICATE_ERROR', 'error creating signing certificate');
-        }
-    }
-}
-exports.CAClient = CAClient;
-function toCertificateRequest(identityToken, publicKey, challenge) {
-    return {
-        credentials: {
-            oidcIdentityToken: identityToken,
-        },
-        publicKeyRequest: {
-            publicKey: {
-                algorithm: 'ECDSA',
-                content: publicKey,
-            },
-            proofOfPossession: challenge.toString('base64'),
-        },
-    };
-}
+	}).call(commonjsGlobal);
 
+	var Group_1 = Group;
 
-/***/ }),
+	var Batcher, Events$3, parser$4;
 
-/***/ 97064:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+	parser$4 = parser;
 
-"use strict";
+	Events$3 = Events_1;
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.EphemeralSigner = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	Batcher = (function() {
+	  class Batcher {
+	    constructor(options = {}) {
+	      this.options = options;
+	      parser$4.load(this.options, this.defaults, this);
+	      this.Events = new Events$3(this);
+	      this._arr = [];
+	      this._resetPromise();
+	      this._lastFlush = Date.now();
+	    }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	    _resetPromise() {
+	      return this._promise = new this.Promise((res, rej) => {
+	        return this._resolve = res;
+	      });
+	    }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	    _flush() {
+	      clearTimeout(this._timeout);
+	      this._lastFlush = Date.now();
+	      this._resolve();
+	      this.Events.trigger("batch", this._arr);
+	      this._arr = [];
+	      return this._resetPromise();
+	    }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const crypto_1 = __importDefault(__nccwpck_require__(76982));
-const EC_KEYPAIR_TYPE = 'ec';
-const P256_CURVE = 'P-256';
-// Signer implementation which uses an ephemeral keypair to sign artifacts.
-// The private key lives only in memory and is tied to the lifetime of the
-// EphemeralSigner instance.
-class EphemeralSigner {
-    constructor() {
-        this.keypair = crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, {
-            namedCurve: P256_CURVE,
-        });
-    }
-    async sign(data) {
-        const signature = crypto_1.default.sign(null, data, this.keypair.privateKey);
-        const publicKey = this.keypair.publicKey
-            .export({ format: 'pem', type: 'spki' })
-            .toString('ascii');
-        return {
-            signature: signature,
-            key: { $case: 'publicKey', publicKey },
-        };
-    }
-}
-exports.EphemeralSigner = EphemeralSigner;
+	    add(data) {
+	      var ret;
+	      this._arr.push(data);
+	      ret = this._promise;
+	      if (this._arr.length === this.maxSize) {
+	        this._flush();
+	      } else if ((this.maxTime != null) && this._arr.length === 1) {
+	        this._timeout = setTimeout(() => {
+	          return this._flush();
+	        }, this.maxTime);
+	      }
+	      return ret;
+	    }
 
+	  }
+	  Batcher.prototype.defaults = {
+	    maxTime: null,
+	    maxSize: null,
+	    Promise: Promise
+	  };
 
-/***/ }),
+	  return Batcher;
 
-/***/ 26303:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	}).call(commonjsGlobal);
 
-"use strict";
+	var Batcher_1 = Batcher;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	var require$$8 = getCjsExportFromNamespace(version$2);
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5,
+	  splice = [].splice;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const error_1 = __nccwpck_require__(97841);
-const util_1 = __nccwpck_require__(19100);
-const ca_1 = __nccwpck_require__(5875);
-const ephemeral_1 = __nccwpck_require__(97064);
-exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev';
-// Signer implementation which can be used to decorate another signer
-// with a Fulcio-issued signing certificate for the signer's public key.
-// Must be instantiated with an identity provider which can provide a JWT
-// which represents the identity to be bound to the signing certificate.
-class FulcioSigner {
-    constructor(options) {
-        this.ca = new ca_1.CAClient({
-            ...options,
-            fulcioBaseURL: options.fulcioBaseURL || /* istanbul ignore next */ exports.DEFAULT_FULCIO_URL,
-        });
-        this.identityProvider = options.identityProvider;
-        this.keyHolder = options.keyHolder || new ephemeral_1.EphemeralSigner();
-    }
-    async sign(data) {
-        // Retrieve identity token from the supplied identity provider
-        const identityToken = await this.getIdentityToken();
-        // Extract challenge claim from OIDC token
-        let subject;
-        try {
-            subject = util_1.oidc.extractJWTSubject(identityToken);
-        }
-        catch (err) {
-            throw new error_1.InternalError({
-                code: 'IDENTITY_TOKEN_PARSE_ERROR',
-                message: `invalid identity token: ${identityToken}`,
-                cause: err,
-            });
-        }
-        // Construct challenge value by signing the subject claim
-        const challenge = await this.keyHolder.sign(Buffer.from(subject));
-        if (challenge.key.$case !== 'publicKey') {
-            throw new error_1.InternalError({
-                code: 'CA_CREATE_SIGNING_CERTIFICATE_ERROR',
-                message: 'unexpected format for signing key',
-            });
-        }
-        // Create signing certificate
-        const certificates = await this.ca.createSigningCertificate(identityToken, challenge.key.publicKey, challenge.signature);
-        // Generate artifact signature
-        const signature = await this.keyHolder.sign(data);
-        // Specifically returning only the first certificate in the chain
-        // as the key.
-        return {
-            signature: signature.signature,
-            key: {
-                $case: 'x509Certificate',
-                certificate: certificates[0],
-            },
-        };
-    }
-    async getIdentityToken() {
-        try {
-            return await this.identityProvider.getToken();
-        }
-        catch (err) {
-            throw new error_1.InternalError({
-                code: 'IDENTITY_TOKEN_READ_ERROR',
-                message: 'error retrieving identity token',
-                cause: err,
-            });
-        }
-    }
-}
-exports.FulcioSigner = FulcioSigner;
+	NUM_PRIORITIES$1 = 10;
 
+	DEFAULT_PRIORITY$1 = 5;
 
-/***/ }),
+	parser$5 = parser;
 
-/***/ 34342:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	Queues$1 = Queues_1;
 
-"use strict";
+	Job$1 = Job_1;
 
-/* istanbul ignore file */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.FulcioSigner = exports.DEFAULT_FULCIO_URL = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	LocalDatastore$1 = LocalDatastore_1;
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	RedisDatastore$1 = require$$4$1;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	Events$4 = Events_1;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-var fulcio_1 = __nccwpck_require__(26303);
-Object.defineProperty(exports, "DEFAULT_FULCIO_URL", ({ enumerable: true, get: function () { return fulcio_1.DEFAULT_FULCIO_URL; } }));
-Object.defineProperty(exports, "FulcioSigner", ({ enumerable: true, get: function () { return fulcio_1.FulcioSigner; } }));
+	States$1 = States_1;
 
+	Sync$1 = Sync_1;
 
-/***/ }),
+	Bottleneck = (function() {
+	  class Bottleneck {
+	    constructor(options = {}, ...invalid) {
+	      var storeInstanceOptions, storeOptions;
+	      this._addToQueue = this._addToQueue.bind(this);
+	      this._validateOptions(options, invalid);
+	      parser$5.load(options, this.instanceDefaults, this);
+	      this._queues = new Queues$1(NUM_PRIORITIES$1);
+	      this._scheduled = {};
+	      this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
+	      this._limiter = null;
+	      this.Events = new Events$4(this);
+	      this._submitLock = new Sync$1("submit", this.Promise);
+	      this._registerLock = new Sync$1("register", this.Promise);
+	      storeOptions = parser$5.load(options, this.storeDefaults, {});
+	      this._store = (function() {
+	        if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) {
+	          storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {});
+	          return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);
+	        } else if (this.datastore === "local") {
+	          storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {});
+	          return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);
+	        } else {
+	          throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);
+	        }
+	      }).call(this);
+	      this._queues.on("leftzero", () => {
+	        var ref;
+	        return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0;
+	      });
+	      this._queues.on("zero", () => {
+	        var ref;
+	        return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0;
+	      });
+	    }
 
-/***/ 19100:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+	    _validateOptions(options, invalid) {
+	      if (!((options != null) && typeof options === "object" && invalid.length === 0)) {
+	        throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.");
+	      }
+	    }
 
-"use strict";
+	    ready() {
+	      return this._store.ready;
+	    }
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ua = exports.oidc = exports.pem = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	    clients() {
+	      return this._store.clients;
+	    }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	    channel() {
+	      return `b_${this.id}`;
+	    }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	    channel_client() {
+	      return `b_${this.id}_${this._store.clientId}`;
+	    }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-var core_1 = __nccwpck_require__(83917);
-Object.defineProperty(exports, "crypto", ({ enumerable: true, get: function () { return core_1.crypto; } }));
-Object.defineProperty(exports, "dsse", ({ enumerable: true, get: function () { return core_1.dsse; } }));
-Object.defineProperty(exports, "encoding", ({ enumerable: true, get: function () { return core_1.encoding; } }));
-Object.defineProperty(exports, "json", ({ enumerable: true, get: function () { return core_1.json; } }));
-Object.defineProperty(exports, "pem", ({ enumerable: true, get: function () { return core_1.pem; } }));
-exports.oidc = __importStar(__nccwpck_require__(81963));
-exports.ua = __importStar(__nccwpck_require__(81268));
+	    publish(message) {
+	      return this._store.__publish__(message);
+	    }
 
+	    disconnect(flush = true) {
+	      return this._store.__disconnect__(flush);
+	    }
 
-/***/ }),
+	    chain(_limiter) {
+	      this._limiter = _limiter;
+	      return this;
+	    }
 
-/***/ 81963:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	    queued(priority) {
+	      return this._queues.queued(priority);
+	    }
 
-"use strict";
+	    clusterQueued() {
+	      return this._store.__queued__();
+	    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.extractJWTSubject = extractJWTSubject;
-/*
-Copyright 2023 The Sigstore Authors.
+	    empty() {
+	      return this.queued() === 0 && this._submitLock.isEmpty();
+	    }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	    running() {
+	      return this._store.__running__();
+	    }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	    done() {
+	      return this._store.__done__();
+	    }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const core_1 = __nccwpck_require__(83917);
-function extractJWTSubject(jwt) {
-    const parts = jwt.split('.', 3);
-    const payload = JSON.parse(core_1.encoding.base64Decode(parts[1]));
-    switch (payload.iss) {
-        case 'https://accounts.google.com':
-        case 'https://oauth2.sigstore.dev/auth':
-            return payload.email;
-        default:
-            return payload.sub;
-    }
-}
+	    jobStatus(id) {
+	      return this._states.jobStatus(id);
+	    }
 
+	    jobs(status) {
+	      return this._states.statusJobs(status);
+	    }
 
-/***/ }),
+	    counts() {
+	      return this._states.statusCounts();
+	    }
 
-/***/ 81268:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+	    _randomIndex() {
+	      return Math.random().toString(36).slice(2);
+	    }
 
-"use strict";
+	    check(weight = 1) {
+	      return this._store.__check__(weight);
+	    }
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getUserAgent = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	    _clearGlobalState(index) {
+	      if (this._scheduled[index] != null) {
+	        clearTimeout(this._scheduled[index].expiration);
+	        delete this._scheduled[index];
+	        return true;
+	      } else {
+	        return false;
+	      }
+	    }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	    async _free(index, job, options, eventInfo) {
+	      var e, running;
+	      try {
+	        ({running} = (await this._store.__free__(index, options.weight)));
+	        this.Events.trigger("debug", `Freed ${options.id}`, eventInfo);
+	        if (running === 0 && this.empty()) {
+	          return this.Events.trigger("idle");
+	        }
+	      } catch (error1) {
+	        e = error1;
+	        return this.Events.trigger("error", e);
+	      }
+	    }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	    _run(index, job, wait) {
+	      var clearGlobalState, free, run;
+	      job.doRun();
+	      clearGlobalState = this._clearGlobalState.bind(this, index);
+	      run = this._run.bind(this, index, job);
+	      free = this._free.bind(this, index, job);
+	      return this._scheduled[index] = {
+	        timeout: setTimeout(() => {
+	          return job.doExecute(this._limiter, clearGlobalState, run, free);
+	        }, wait),
+	        expiration: job.options.expiration != null ? setTimeout(function() {
+	          return job.doExpire(clearGlobalState, run, free);
+	        }, wait + job.options.expiration) : void 0,
+	        job: job
+	      };
+	    }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const os_1 = __importDefault(__nccwpck_require__(70857));
-// Format User-Agent:  /  ()
-// source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
-const getUserAgent = () => {
-    const packageVersion = (__nccwpck_require__(85896)/* .version */ .rE);
-    const nodeVersion = process.version;
-    const platformName = os_1.default.platform();
-    const archName = os_1.default.arch();
-    return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`;
-};
-exports.getUserAgent = getUserAgent;
+	    _drainOne(capacity) {
+	      return this._registerLock.schedule(() => {
+	        var args, index, next, options, queue;
+	        if (this.queued() === 0) {
+	          return this.Promise.resolve(null);
+	        }
+	        queue = this._queues.getFirst();
+	        ({options, args} = next = queue.first());
+	        if ((capacity != null) && options.weight > capacity) {
+	          return this.Promise.resolve(null);
+	        }
+	        this.Events.trigger("debug", `Draining ${options.id}`, {args, options});
+	        index = this._randomIndex();
+	        return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => {
+	          var empty;
+	          this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options});
+	          if (success) {
+	            queue.shift();
+	            empty = this.empty();
+	            if (empty) {
+	              this.Events.trigger("empty");
+	            }
+	            if (reservoir === 0) {
+	              this.Events.trigger("depleted", empty);
+	            }
+	            this._run(index, next, wait);
+	            return this.Promise.resolve(options.weight);
+	          } else {
+	            return this.Promise.resolve(null);
+	          }
+	        });
+	      });
+	    }
 
+	    _drainAll(capacity, total = 0) {
+	      return this._drainOne(capacity).then((drained) => {
+	        var newCapacity;
+	        if (drained != null) {
+	          newCapacity = capacity != null ? capacity - drained : capacity;
+	          return this._drainAll(newCapacity, total + drained);
+	        } else {
+	          return this.Promise.resolve(total);
+	        }
+	      }).catch((e) => {
+	        return this.Events.trigger("error", e);
+	      });
+	    }
 
-/***/ }),
+	    _dropAllQueued(message) {
+	      return this._queues.shiftAll(function(job) {
+	        return job.doDrop({message});
+	      });
+	    }
 
-/***/ 55383:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	    stop(options = {}) {
+	      var done, waitForExecuting;
+	      options = parser$5.load(options, this.stopDefaults);
+	      waitForExecuting = (at) => {
+	        var finished;
+	        finished = () => {
+	          var counts;
+	          counts = this._states.counts;
+	          return (counts[0] + counts[1] + counts[2] + counts[3]) === at;
+	        };
+	        return new this.Promise((resolve, reject) => {
+	          if (finished()) {
+	            return resolve();
+	          } else {
+	            return this.on("done", () => {
+	              if (finished()) {
+	                this.removeAllListeners("done");
+	                return resolve();
+	              }
+	            });
+	          }
+	        });
+	      };
+	      done = options.dropWaitingJobs ? (this._run = function(index, next) {
+	        return next.doDrop({
+	          message: options.dropErrorMessage
+	        });
+	      }, this._drainOne = () => {
+	        return this.Promise.resolve(null);
+	      }, this._registerLock.schedule(() => {
+	        return this._submitLock.schedule(() => {
+	          var k, ref, v;
+	          ref = this._scheduled;
+	          for (k in ref) {
+	            v = ref[k];
+	            if (this.jobStatus(v.job.options.id) === "RUNNING") {
+	              clearTimeout(v.timeout);
+	              clearTimeout(v.expiration);
+	              v.job.doDrop({
+	                message: options.dropErrorMessage
+	              });
+	            }
+	          }
+	          this._dropAllQueued(options.dropErrorMessage);
+	          return waitForExecuting(0);
+	        });
+	      })) : this.schedule({
+	        priority: NUM_PRIORITIES$1 - 1,
+	        weight: 0
+	      }, () => {
+	        return waitForExecuting(1);
+	      });
+	      this._receive = function(job) {
+	        return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage));
+	      };
+	      this.stop = () => {
+	        return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
+	      };
+	      return done;
+	    }
 
-"use strict";
+	    async _addToQueue(job) {
+	      var args, blocked, error, options, reachedHWM, shifted, strategy;
+	      ({args, options} = job);
+	      try {
+	        ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight)));
+	      } catch (error1) {
+	        error = error1;
+	        this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error});
+	        job.doDrop({error});
+	        return false;
+	      }
+	      if (blocked) {
+	        job.doDrop();
+	        return true;
+	      } else if (reachedHWM) {
+	        shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;
+	        if (shifted != null) {
+	          shifted.doDrop();
+	        }
+	        if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) {
+	          if (shifted == null) {
+	            job.doDrop();
+	          }
+	          return reachedHWM;
+	        }
+	      }
+	      job.doQueue(reachedHWM, blocked);
+	      this._queues.push(job);
+	      await this._drainAll();
+	      return reachedHWM;
+	    }
 
-/* istanbul ignore file */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TSAWitness = exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	    _receive(job) {
+	      if (this._states.jobStatus(job.options.id) != null) {
+	        job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`));
+	        return false;
+	      } else {
+	        job.doReceive();
+	        return this._submitLock.schedule(this._addToQueue, job);
+	      }
+	    }
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	    submit(...args) {
+	      var cb, fn, job, options, ref, ref1, task;
+	      if (typeof args[0] === "function") {
+	        ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1);
+	        options = parser$5.load({}, this.jobDefaults);
+	      } else {
+	        ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1);
+	        options = parser$5.load(options, this.jobDefaults);
+	      }
+	      task = (...args) => {
+	        return new this.Promise(function(resolve, reject) {
+	          return fn(...args, function(...args) {
+	            return (args[0] != null ? reject : resolve)(args);
+	          });
+	        });
+	      };
+	      job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
+	      job.promise.then(function(args) {
+	        return typeof cb === "function" ? cb(...args) : void 0;
+	      }).catch(function(args) {
+	        if (Array.isArray(args)) {
+	          return typeof cb === "function" ? cb(...args) : void 0;
+	        } else {
+	          return typeof cb === "function" ? cb(args) : void 0;
+	        }
+	      });
+	      return this._receive(job);
+	    }
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	    schedule(...args) {
+	      var job, options, task;
+	      if (typeof args[0] === "function") {
+	        [task, ...args] = args;
+	        options = {};
+	      } else {
+	        [options, task, ...args] = args;
+	      }
+	      job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
+	      this._receive(job);
+	      return job.promise;
+	    }
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-var tlog_1 = __nccwpck_require__(2566);
-Object.defineProperty(exports, "DEFAULT_REKOR_URL", ({ enumerable: true, get: function () { return tlog_1.DEFAULT_REKOR_URL; } }));
-Object.defineProperty(exports, "RekorWitness", ({ enumerable: true, get: function () { return tlog_1.RekorWitness; } }));
-var tsa_1 = __nccwpck_require__(66936);
-Object.defineProperty(exports, "TSAWitness", ({ enumerable: true, get: function () { return tsa_1.TSAWitness; } }));
+	    wrap(fn) {
+	      var schedule, wrapped;
+	      schedule = this.schedule.bind(this);
+	      wrapped = function(...args) {
+	        return schedule(fn.bind(this), ...args);
+	      };
+	      wrapped.withOptions = function(options, ...args) {
+	        return schedule(options, fn, ...args);
+	      };
+	      return wrapped;
+	    }
 
+	    async updateSettings(options = {}) {
+	      await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults));
+	      parser$5.overwrite(options, this.instanceDefaults, this);
+	      return this;
+	    }
 
-/***/ }),
+	    currentReservoir() {
+	      return this._store.__currentReservoir__();
+	    }
 
-/***/ 42815:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	    incrementReservoir(incr = 0) {
+	      return this._store.__incrementReservoir__(incr);
+	    }
 
-"use strict";
+	  }
+	  Bottleneck.default = Bottleneck;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TLogClient = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	  Bottleneck.Events = Events$4;
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  Bottleneck.version = Bottleneck.prototype.version = require$$8.version;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  Bottleneck.strategy = Bottleneck.prototype.strategy = {
+	    LEAK: 1,
+	    OVERFLOW: 2,
+	    OVERFLOW_PRIORITY: 4,
+	    BLOCK: 3
+	  };
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const error_1 = __nccwpck_require__(97841);
-const error_2 = __nccwpck_require__(40369);
-const rekor_1 = __nccwpck_require__(32688);
-class TLogClient {
-    constructor(options) {
-        this.fetchOnConflict = options.fetchOnConflict ?? false;
-        this.rekor = new rekor_1.Rekor({
-            baseURL: options.rekorBaseURL,
-            retry: options.retry,
-            timeout: options.timeout,
-        });
-    }
-    async createEntry(proposedEntry) {
-        let entry;
-        try {
-            entry = await this.rekor.createEntry(proposedEntry);
-        }
-        catch (err) {
-            // If the entry already exists, fetch it (if enabled)
-            if (entryExistsError(err) && this.fetchOnConflict) {
-                // Grab the UUID of the existing entry from the location header
-                /* istanbul ignore next */
-                const uuid = err.location.split('/').pop() || '';
-                try {
-                    entry = await this.rekor.getEntry(uuid);
-                }
-                catch (err) {
-                    (0, error_1.internalError)(err, 'TLOG_FETCH_ENTRY_ERROR', 'error fetching tlog entry');
-                }
-            }
-            else {
-                (0, error_1.internalError)(err, 'TLOG_CREATE_ENTRY_ERROR', 'error creating tlog entry');
-            }
-        }
-        return entry;
-    }
-}
-exports.TLogClient = TLogClient;
-function entryExistsError(value) {
-    return (value instanceof error_2.HTTPError &&
-        value.statusCode === 409 &&
-        value.location !== undefined);
-}
+	  Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;
 
+	  Bottleneck.Group = Bottleneck.prototype.Group = Group_1;
 
-/***/ }),
+	  Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2;
 
-/***/ 97890:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	  Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3;
 
-"use strict";
+	  Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toProposedEntry = toProposedEntry;
-/*
-Copyright 2023 The Sigstore Authors.
+	  Bottleneck.prototype.jobDefaults = {
+	    priority: DEFAULT_PRIORITY$1,
+	    weight: 1,
+	    expiration: null,
+	    id: ""
+	  };
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	  Bottleneck.prototype.storeDefaults = {
+	    maxConcurrent: null,
+	    minTime: 0,
+	    highWater: null,
+	    strategy: Bottleneck.prototype.strategy.LEAK,
+	    penalty: null,
+	    reservoir: null,
+	    reservoirRefreshInterval: null,
+	    reservoirRefreshAmount: null,
+	    reservoirIncreaseInterval: null,
+	    reservoirIncreaseAmount: null,
+	    reservoirIncreaseMaximum: null
+	  };
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	  Bottleneck.prototype.localStoreDefaults = {
+	    Promise: Promise,
+	    timeout: null,
+	    heartbeatInterval: 250
+	  };
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const bundle_1 = __nccwpck_require__(61040);
-const util_1 = __nccwpck_require__(19100);
-const SHA256_ALGORITHM = 'sha256';
-function toProposedEntry(content, publicKey, 
-// TODO: Remove this parameter once have completely switched to 'dsse' entries
-entryType = 'dsse') {
-    switch (content.$case) {
-        case 'dsseEnvelope':
-            // TODO: Remove this conditional once have completely ditched "intoto" entries
-            if (entryType === 'intoto') {
-                return toProposedIntotoEntry(content.dsseEnvelope, publicKey);
-            }
-            return toProposedDSSEEntry(content.dsseEnvelope, publicKey);
-        case 'messageSignature':
-            return toProposedHashedRekordEntry(content.messageSignature, publicKey);
-    }
-}
-// Returns a properly formatted Rekor "hashedrekord" entry for the given digest
-// and signature
-function toProposedHashedRekordEntry(messageSignature, publicKey) {
-    const hexDigest = messageSignature.messageDigest.digest.toString('hex');
-    const b64Signature = messageSignature.signature.toString('base64');
-    const b64Key = util_1.encoding.base64Encode(publicKey);
-    return {
-        apiVersion: '0.0.1',
-        kind: 'hashedrekord',
-        spec: {
-            data: {
-                hash: {
-                    algorithm: SHA256_ALGORITHM,
-                    value: hexDigest,
-                },
-            },
-            signature: {
-                content: b64Signature,
-                publicKey: {
-                    content: b64Key,
-                },
-            },
-        },
-    };
-}
-// Returns a properly formatted Rekor "dsse" entry for the given DSSE envelope
-// and signature
-function toProposedDSSEEntry(envelope, publicKey) {
-    const envelopeJSON = JSON.stringify((0, bundle_1.envelopeToJSON)(envelope));
-    const encodedKey = util_1.encoding.base64Encode(publicKey);
-    return {
-        apiVersion: '0.0.1',
-        kind: 'dsse',
-        spec: {
-            proposedContent: {
-                envelope: envelopeJSON,
-                verifiers: [encodedKey],
-            },
-        },
-    };
-}
-// Returns a properly formatted Rekor "intoto" entry for the given DSSE
-// envelope and signature
-function toProposedIntotoEntry(envelope, publicKey) {
-    // Calculate the value for the payloadHash field in the Rekor entry
-    const payloadHash = util_1.crypto
-        .digest(SHA256_ALGORITHM, envelope.payload)
-        .toString('hex');
-    // Calculate the value for the hash field in the Rekor entry
-    const envelopeHash = calculateDSSEHash(envelope, publicKey);
-    // Collect values for re-creating the DSSE envelope.
-    // Double-encode payload and signature cause that's what Rekor expects
-    const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64'));
-    const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64'));
-    const keyid = envelope.signatures[0].keyid;
-    const encodedKey = util_1.encoding.base64Encode(publicKey);
-    // Create the envelope portion of the entry. Note the inclusion of the
-    // publicKey in the signature struct is not a standard part of a DSSE
-    // envelope, but is required by Rekor.
-    const dsse = {
-        payloadType: envelope.payloadType,
-        payload: payload,
-        signatures: [{ sig, publicKey: encodedKey }],
-    };
-    // If the keyid is an empty string, Rekor seems to remove it altogether. We
-    // need to do the same here so that we can properly recreate the entry for
-    // verification.
-    if (keyid.length > 0) {
-        dsse.signatures[0].keyid = keyid;
-    }
-    return {
-        apiVersion: '0.0.2',
-        kind: 'intoto',
-        spec: {
-            content: {
-                envelope: dsse,
-                hash: { algorithm: SHA256_ALGORITHM, value: envelopeHash },
-                payloadHash: { algorithm: SHA256_ALGORITHM, value: payloadHash },
-            },
-        },
-    };
-}
-// Calculates the hash of a DSSE envelope for inclusion in a Rekor entry.
-// There is no standard way to do this, so the scheme we're using as as
-// follows:
-//  * payload is base64 encoded
-//  * signature is base64 encoded (only the first signature is used)
-//  * keyid is included ONLY if it is NOT an empty string
-//  * The resulting JSON is canonicalized and hashed to a hex string
-function calculateDSSEHash(envelope, publicKey) {
-    const dsse = {
-        payloadType: envelope.payloadType,
-        payload: envelope.payload.toString('base64'),
-        signatures: [
-            { sig: envelope.signatures[0].sig.toString('base64'), publicKey },
-        ],
-    };
-    // If the keyid is an empty string, Rekor seems to remove it altogether.
-    if (envelope.signatures[0].keyid.length > 0) {
-        dsse.signatures[0].keyid = envelope.signatures[0].keyid;
-    }
-    return util_1.crypto
-        .digest(SHA256_ALGORITHM, util_1.json.canonicalize(dsse))
-        .toString('hex');
-}
+	  Bottleneck.prototype.redisStoreDefaults = {
+	    Promise: Promise,
+	    timeout: null,
+	    heartbeatInterval: 5000,
+	    clientTimeout: 10000,
+	    Redis: null,
+	    clientOptions: {},
+	    clusterNodes: null,
+	    clearDatastore: false,
+	    connection: null
+	  };
 
+	  Bottleneck.prototype.instanceDefaults = {
+	    datastore: "local",
+	    connection: null,
+	    id: "",
+	    rejectOnDrop: true,
+	    trackDoneStatus: false,
+	    Promise: Promise
+	  };
 
-/***/ }),
+	  Bottleneck.prototype.stopDefaults = {
+	    enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
+	    dropWaitingJobs: true,
+	    dropErrorMessage: "This limiter has been stopped."
+	  };
 
-/***/ 2566:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+	  return Bottleneck;
 
-"use strict";
+	}).call(commonjsGlobal);
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RekorWitness = exports.DEFAULT_REKOR_URL = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+	var Bottleneck_1 = Bottleneck;
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+	var lib = Bottleneck_1;
 
-    http://www.apache.org/licenses/LICENSE-2.0
+	return lib;
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const util_1 = __nccwpck_require__(19100);
-const client_1 = __nccwpck_require__(42815);
-const entry_1 = __nccwpck_require__(97890);
-exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev';
-class RekorWitness {
-    constructor(options) {
-        this.entryType = options.entryType;
-        this.tlog = new client_1.TLogClient({
-            ...options,
-            rekorBaseURL: options.rekorBaseURL || /* istanbul ignore next */ exports.DEFAULT_REKOR_URL,
-        });
-    }
-    async testify(content, publicKey) {
-        const proposedEntry = (0, entry_1.toProposedEntry)(content, publicKey, this.entryType);
-        const entry = await this.tlog.createEntry(proposedEntry);
-        return toTransparencyLogEntry(entry);
-    }
-}
-exports.RekorWitness = RekorWitness;
-function toTransparencyLogEntry(entry) {
-    const logID = Buffer.from(entry.logID, 'hex');
-    // Parse entry body so we can extract the kind and version.
-    const bodyJSON = util_1.encoding.base64Decode(entry.body);
-    const entryBody = JSON.parse(bodyJSON);
-    const promise = entry?.verification?.signedEntryTimestamp
-        ? inclusionPromise(entry.verification.signedEntryTimestamp)
-        : undefined;
-    const proof = entry?.verification?.inclusionProof
-        ? inclusionProof(entry.verification.inclusionProof)
-        : undefined;
-    const tlogEntry = {
-        logIndex: entry.logIndex.toString(),
-        logId: {
-            keyId: logID,
-        },
-        integratedTime: entry.integratedTime.toString(),
-        kindVersion: {
-            kind: entryBody.kind,
-            version: entryBody.apiVersion,
-        },
-        inclusionPromise: promise,
-        inclusionProof: proof,
-        canonicalizedBody: Buffer.from(entry.body, 'base64'),
-    };
-    return {
-        tlogEntries: [tlogEntry],
-    };
-}
-function inclusionPromise(promise) {
-    return {
-        signedEntryTimestamp: Buffer.from(promise, 'base64'),
-    };
-}
-function inclusionProof(proof) {
-    return {
-        logIndex: proof.logIndex.toString(),
-        treeSize: proof.treeSize.toString(),
-        rootHash: Buffer.from(proof.rootHash, 'hex'),
-        hashes: proof.hashes.map((h) => Buffer.from(h, 'hex')),
-        checkpoint: {
-            envelope: proof.checkpoint,
-        },
-    };
-}
+})));
 
 
 /***/ }),
 
-/***/ 97409:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TSAClient = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+/***/ 94691:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    http://www.apache.org/licenses/LICENSE-2.0
+var concatMap = __nccwpck_require__(97087);
+var balanced = __nccwpck_require__(59380);
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const error_1 = __nccwpck_require__(97841);
-const tsa_1 = __nccwpck_require__(78963);
-const util_1 = __nccwpck_require__(19100);
-const SHA256_ALGORITHM = 'sha256';
-class TSAClient {
-    constructor(options) {
-        this.tsa = new tsa_1.TimestampAuthority({
-            baseURL: options.tsaBaseURL,
-            retry: options.retry,
-            timeout: options.timeout,
-        });
-    }
-    async createTimestamp(signature) {
-        const request = {
-            artifactHash: util_1.crypto
-                .digest(SHA256_ALGORITHM, signature)
-                .toString('base64'),
-            hashAlgorithm: SHA256_ALGORITHM,
-        };
-        try {
-            return await this.tsa.createTimestamp(request);
-        }
-        catch (err) {
-            (0, error_1.internalError)(err, 'TSA_CREATE_TIMESTAMP_ERROR', 'error creating timestamp');
-        }
-    }
+module.exports = expandTop;
+
+var escSlash = '\0SLASH'+Math.random()+'\0';
+var escOpen = '\0OPEN'+Math.random()+'\0';
+var escClose = '\0CLOSE'+Math.random()+'\0';
+var escComma = '\0COMMA'+Math.random()+'\0';
+var escPeriod = '\0PERIOD'+Math.random()+'\0';
+
+function numeric(str) {
+  return parseInt(str, 10) == str
+    ? parseInt(str, 10)
+    : str.charCodeAt(0);
 }
-exports.TSAClient = TSAClient;
 
+function escapeBraces(str) {
+  return str.split('\\\\').join(escSlash)
+            .split('\\{').join(escOpen)
+            .split('\\}').join(escClose)
+            .split('\\,').join(escComma)
+            .split('\\.').join(escPeriod);
+}
 
-/***/ }),
+function unescapeBraces(str) {
+  return str.split(escSlash).join('\\')
+            .split(escOpen).join('{')
+            .split(escClose).join('}')
+            .split(escComma).join(',')
+            .split(escPeriod).join('.');
+}
 
-/***/ 66936:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-"use strict";
+// Basically just str.split(","), but handling cases
+// where we have nested braced sections, which should be
+// treated as individual members, like {a,{b,c},d}
+function parseCommaParts(str) {
+  if (!str)
+    return [''];
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TSAWitness = void 0;
-/*
-Copyright 2023 The Sigstore Authors.
+  var parts = [];
+  var m = balanced('{', '}', str);
 
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
+  if (!m)
+    return str.split(',');
 
-    http://www.apache.org/licenses/LICENSE-2.0
+  var pre = m.pre;
+  var body = m.body;
+  var post = m.post;
+  var p = pre.split(',');
 
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-const client_1 = __nccwpck_require__(97409);
-class TSAWitness {
-    constructor(options) {
-        this.tsa = new client_1.TSAClient({
-            tsaBaseURL: options.tsaBaseURL,
-            retry: options.retry,
-            timeout: options.timeout,
-        });
-    }
-    async testify(content) {
-        const signature = extractSignature(content);
-        const timestamp = await this.tsa.createTimestamp(signature);
-        return {
-            rfc3161Timestamps: [{ signedTimestamp: timestamp }],
-        };
-    }
-}
-exports.TSAWitness = TSAWitness;
-function extractSignature(content) {
-    switch (content.$case) {
-        case 'dsseEnvelope':
-            return content.dsseEnvelope.signatures[0].sig;
-        case 'messageSignature':
-            return content.messageSignature.signature;
-    }
-}
+  p[p.length-1] += '{' + body + '}';
+  var postParts = parseCommaParts(post);
+  if (post.length) {
+    p[p.length-1] += postParts.shift();
+    p.push.apply(p, postParts);
+  }
 
+  parts.push.apply(parts, p);
 
-/***/ }),
+  return parts;
+}
 
-/***/ 15183:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+function expandTop(str) {
+  if (!str)
+    return [];
 
-"use strict";
+  // I don't know why Bash 4.3 does this, but it does.
+  // Anything starting with {} will have the first two bytes preserved
+  // but *only* at the top level, so {},a}b will not expand to anything,
+  // but a{},b}c will be expanded to [a}c,abc].
+  // One could argue that this is a bug in Bash, but since the goal of
+  // this module is to match Bash's rules, we escape a leading {}
+  if (str.substr(0, 2) === '{}') {
+    str = '\\{\\}' + str.substr(2);
+  }
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.req = exports.json = exports.toBuffer = void 0;
-const http = __importStar(__nccwpck_require__(58611));
-const https = __importStar(__nccwpck_require__(65692));
-async function toBuffer(stream) {
-    let length = 0;
-    const chunks = [];
-    for await (const chunk of stream) {
-        length += chunk.length;
-        chunks.push(chunk);
-    }
-    return Buffer.concat(chunks, length);
+  return expand(escapeBraces(str), true).map(unescapeBraces);
 }
-exports.toBuffer = toBuffer;
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-async function json(stream) {
-    const buf = await toBuffer(stream);
-    const str = buf.toString('utf8');
-    try {
-        return JSON.parse(str);
-    }
-    catch (_err) {
-        const err = _err;
-        err.message += ` (input: ${str})`;
-        throw err;
-    }
+
+function identity(e) {
+  return e;
 }
-exports.json = json;
-function req(url, opts = {}) {
-    const href = typeof url === 'string' ? url : url.href;
-    const req = (href.startsWith('https:') ? https : http).request(url, opts);
-    const promise = new Promise((resolve, reject) => {
-        req
-            .once('response', resolve)
-            .once('error', reject)
-            .end();
-    });
-    req.then = promise.then.bind(promise);
-    return req;
+
+function embrace(str) {
+  return '{' + str + '}';
+}
+function isPadded(el) {
+  return /^-?0\d/.test(el);
 }
-exports.req = req;
-//# sourceMappingURL=helpers.js.map
 
-/***/ }),
+function lte(i, y) {
+  return i <= y;
+}
+function gte(i, y) {
+  return i >= y;
+}
 
-/***/ 98894:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+function expand(str, isTop) {
+  var expansions = [];
 
-"use strict";
+  var m = balanced('{', '}', str);
+  if (!m || /\$$/.test(m.pre)) return [str];
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
-    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Agent = void 0;
-const net = __importStar(__nccwpck_require__(69278));
-const http = __importStar(__nccwpck_require__(58611));
-const https_1 = __nccwpck_require__(65692);
-__exportStar(__nccwpck_require__(15183), exports);
-const INTERNAL = Symbol('AgentBaseInternalState');
-class Agent extends http.Agent {
-    constructor(opts) {
-        super(opts);
-        this[INTERNAL] = {};
-    }
-    /**
-     * Determine whether this is an `http` or `https` request.
-     */
-    isSecureEndpoint(options) {
-        if (options) {
-            // First check the `secureEndpoint` property explicitly, since this
-            // means that a parent `Agent` is "passing through" to this instance.
-            // eslint-disable-next-line @typescript-eslint/no-explicit-any
-            if (typeof options.secureEndpoint === 'boolean') {
-                return options.secureEndpoint;
-            }
-            // If no explicit `secure` endpoint, check if `protocol` property is
-            // set. This will usually be the case since using a full string URL
-            // or `URL` instance should be the most common usage.
-            if (typeof options.protocol === 'string') {
-                return options.protocol === 'https:';
-            }
-        }
-        // Finally, if no `protocol` property was set, then fall back to
-        // checking the stack trace of the current call stack, and try to
-        // detect the "https" module.
-        const { stack } = new Error();
-        if (typeof stack !== 'string')
-            return false;
-        return stack
-            .split('\n')
-            .some((l) => l.indexOf('(https.js:') !== -1 ||
-            l.indexOf('node:https:') !== -1);
-    }
-    // In order to support async signatures in `connect()` and Node's native
-    // connection pooling in `http.Agent`, the array of sockets for each origin
-    // has to be updated synchronously. This is so the length of the array is
-    // accurate when `addRequest()` is next called. We achieve this by creating a
-    // fake socket and adding it to `sockets[origin]` and incrementing
-    // `totalSocketCount`.
-    incrementSockets(name) {
-        // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no
-        // need to create a fake socket because Node.js native connection pooling
-        // will never be invoked.
-        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
-            return null;
-        }
-        // All instances of `sockets` are expected TypeScript errors. The
-        // alternative is to add it as a private property of this class but that
-        // will break TypeScript subclassing.
-        if (!this.sockets[name]) {
-            // @ts-expect-error `sockets` is readonly in `@types/node`
-            this.sockets[name] = [];
-        }
-        const fakeSocket = new net.Socket({ writable: false });
-        this.sockets[name].push(fakeSocket);
-        // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
-        this.totalSocketCount++;
-        return fakeSocket;
-    }
-    decrementSockets(name, socket) {
-        if (!this.sockets[name] || socket === null) {
-            return;
-        }
-        const sockets = this.sockets[name];
-        const index = sockets.indexOf(socket);
-        if (index !== -1) {
-            sockets.splice(index, 1);
-            // @ts-expect-error  `totalSocketCount` isn't defined in `@types/node`
-            this.totalSocketCount--;
-            if (sockets.length === 0) {
-                // @ts-expect-error `sockets` is readonly in `@types/node`
-                delete this.sockets[name];
-            }
-        }
-    }
-    // In order to properly update the socket pool, we need to call `getName()` on
-    // the core `https.Agent` if it is a secureEndpoint.
-    getName(options) {
-        const secureEndpoint = typeof options.secureEndpoint === 'boolean'
-            ? options.secureEndpoint
-            : this.isSecureEndpoint(options);
-        if (secureEndpoint) {
-            // @ts-expect-error `getName()` isn't defined in `@types/node`
-            return https_1.Agent.prototype.getName.call(this, options);
-        }
-        // @ts-expect-error `getName()` isn't defined in `@types/node`
-        return super.getName(options);
+  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+  var isSequence = isNumericSequence || isAlphaSequence;
+  var isOptions = m.body.indexOf(',') >= 0;
+  if (!isSequence && !isOptions) {
+    // {a},b}
+    if (m.post.match(/,.*\}/)) {
+      str = m.pre + '{' + m.body + escClose + m.post;
+      return expand(str);
     }
-    createSocket(req, options, cb) {
-        const connectOpts = {
-            ...options,
-            secureEndpoint: this.isSecureEndpoint(options),
-        };
-        const name = this.getName(connectOpts);
-        const fakeSocket = this.incrementSockets(name);
-        Promise.resolve()
-            .then(() => this.connect(req, connectOpts))
-            .then((socket) => {
-            this.decrementSockets(name, fakeSocket);
-            if (socket instanceof http.Agent) {
-                // @ts-expect-error `addRequest()` isn't defined in `@types/node`
-                return socket.addRequest(req, connectOpts);
-            }
-            this[INTERNAL].currentSocket = socket;
-            // @ts-expect-error `createSocket()` isn't defined in `@types/node`
-            super.createSocket(req, options, cb);
-        }, (err) => {
-            this.decrementSockets(name, fakeSocket);
-            cb(err);
+    return [str];
+  }
+
+  var n;
+  if (isSequence) {
+    n = m.body.split(/\.\./);
+  } else {
+    n = parseCommaParts(m.body);
+    if (n.length === 1) {
+      // x{{a,b}}y ==> x{a}y x{b}y
+      n = expand(n[0], false).map(embrace);
+      if (n.length === 1) {
+        var post = m.post.length
+          ? expand(m.post, false)
+          : [''];
+        return post.map(function(p) {
+          return m.pre + n[0] + p;
         });
+      }
     }
-    createConnection() {
-        const socket = this[INTERNAL].currentSocket;
-        this[INTERNAL].currentSocket = undefined;
-        if (!socket) {
-            throw new Error('No socket was returned in the `connect()` function');
-        }
-        return socket;
-    }
-    get defaultPort() {
-        return (this[INTERNAL].defaultPort ??
-            (this.protocol === 'https:' ? 443 : 80));
-    }
-    set defaultPort(v) {
-        if (this[INTERNAL]) {
-            this[INTERNAL].defaultPort = v;
-        }
-    }
-    get protocol() {
-        return (this[INTERNAL].protocol ??
-            (this.isSecureEndpoint() ? 'https:' : 'http:'));
+  }
+
+  // at this point, n is the parts, and we know it's not a comma set
+  // with a single entry.
+
+  // no need to expand pre, since it is guaranteed to be free of brace-sets
+  var pre = m.pre;
+  var post = m.post.length
+    ? expand(m.post, false)
+    : [''];
+
+  var N;
+
+  if (isSequence) {
+    var x = numeric(n[0]);
+    var y = numeric(n[1]);
+    var width = Math.max(n[0].length, n[1].length)
+    var incr = n.length == 3
+      ? Math.abs(numeric(n[2]))
+      : 1;
+    var test = lte;
+    var reverse = y < x;
+    if (reverse) {
+      incr *= -1;
+      test = gte;
     }
-    set protocol(v) {
-        if (this[INTERNAL]) {
-            this[INTERNAL].protocol = v;
+    var pad = n.some(isPadded);
+
+    N = [];
+
+    for (var i = x; test(i, y); i += incr) {
+      var c;
+      if (isAlphaSequence) {
+        c = String.fromCharCode(i);
+        if (c === '\\')
+          c = '';
+      } else {
+        c = String(i);
+        if (pad) {
+          var need = width - c.length;
+          if (need > 0) {
+            var z = new Array(need + 1).join('0');
+            if (i < 0)
+              c = '-' + z + c.slice(1);
+            else
+              c = z + c;
+          }
         }
+      }
+      N.push(c);
     }
-}
-exports.Agent = Agent;
-//# sourceMappingURL=index.js.map
-
-/***/ }),
+  } else {
+    N = concatMap(n, function(el) { return expand(el, false) });
+  }
 
-/***/ 59380:
-/***/ ((module) => {
+  for (var j = 0; j < N.length; j++) {
+    for (var k = 0; k < post.length; k++) {
+      var expansion = pre + N[j] + post[k];
+      if (!isTop || isSequence || expansion)
+        expansions.push(expansion);
+    }
+  }
 
-"use strict";
+  return expansions;
+}
 
-module.exports = balanced;
-function balanced(a, b, str) {
-  if (a instanceof RegExp) a = maybeMatch(a, str);
-  if (b instanceof RegExp) b = maybeMatch(b, str);
 
-  var r = range(a, b, str);
 
-  return r && {
-    start: r[0],
-    end: r[1],
-    pre: str.slice(0, r[0]),
-    body: str.slice(r[0] + a.length, r[1]),
-    post: str.slice(r[1] + b.length)
-  };
-}
+/***/ }),
 
-function maybeMatch(reg, str) {
-  var m = str.match(reg);
-  return m ? m[0] : null;
-}
+/***/ 40233:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-balanced.range = range;
-function range(a, b, str) {
-  var begs, beg, left, right, result;
-  var ai = str.indexOf(a);
-  var bi = str.indexOf(b, ai + 1);
-  var i = ai;
+"use strict";
 
-  if (ai >= 0 && bi > 0) {
-    if(a===b) {
-      return [ai, bi];
-    }
-    begs = [];
-    left = str.length;
 
-    while (i >= 0 && !result) {
-      if (i == ai) {
-        begs.push(i);
-        ai = str.indexOf(a, i + 1);
-      } else if (begs.length == 1) {
-        result = [ begs.pop(), bi ];
-      } else {
-        beg = begs.pop();
-        if (beg < left) {
-          left = beg;
-          right = bi;
-        }
+const contentVer = (__nccwpck_require__(4038)/* ["cache-version"].content */ .MH.Q)
+const hashToSegments = __nccwpck_require__(99704)
+const path = __nccwpck_require__(16928)
+const ssri = __nccwpck_require__(68951)
 
-        bi = str.indexOf(b, i + 1);
-      }
+// Current format of content file path:
+//
+// sha512-BaSE64Hex= ->
+// ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee
+//
+module.exports = contentPath
 
-      i = ai < bi && ai >= 0 ? ai : bi;
-    }
+function contentPath (cache, integrity) {
+  const sri = ssri.parse(integrity, { single: true })
+  // contentPath is the *strongest* algo given
+  return path.join(
+    contentDir(cache),
+    sri.algorithm,
+    ...hashToSegments(sri.hexDigest())
+  )
+}
 
-    if (begs.length) {
-      result = [ left, right ];
-    }
-  }
+module.exports.contentDir = contentDir
 
-  return result;
+function contentDir (cache) {
+  return path.join(cache, `content-v${contentVer}`)
 }
 
 
 /***/ }),
 
-/***/ 52732:
+/***/ 39398:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-var register = __nccwpck_require__(11063);
-var addHook = __nccwpck_require__(22027);
-var removeHook = __nccwpck_require__(59934);
+"use strict";
 
-// bind with array of arguments: https://stackoverflow.com/a/21792913
-var bind = Function.bind;
-var bindable = bind.bind(bind);
 
-function bindApi(hook, state, name) {
-  var removeHookRef = bindable(removeHook, null).apply(
-    null,
-    name ? [state, name] : [state]
-  );
-  hook.api = { remove: removeHookRef };
-  hook.remove = removeHookRef;
-  ["before", "error", "after", "wrap"].forEach(function (kind) {
-    var args = name ? [state, kind, name] : [state, kind];
-    hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);
-  });
-}
+const fs = __nccwpck_require__(91943)
+const fsm = __nccwpck_require__(25032)
+const ssri = __nccwpck_require__(68951)
+const contentPath = __nccwpck_require__(40233)
+const Pipeline = __nccwpck_require__(52899)
 
-function HookSingular() {
-  var singularHookName = "h";
-  var singularHookState = {
-    registry: {},
-  };
-  var singularHook = register.bind(null, singularHookState, singularHookName);
-  bindApi(singularHook, singularHookState, singularHookName);
-  return singularHook;
-}
+module.exports = read
 
-function HookCollection() {
-  var state = {
-    registry: {},
-  };
+const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024
+async function read (cache, integrity, opts = {}) {
+  const { size } = opts
+  const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
+    // get size
+    const stat = size ? { size } : await fs.stat(cpath)
+    return { stat, cpath, sri }
+  })
 
-  var hook = register.bind(null, state);
-  bindApi(hook, state);
+  if (stat.size > MAX_SINGLE_READ_SIZE) {
+    return readPipeline(cpath, stat.size, sri, new Pipeline()).concat()
+  }
 
-  return hook;
-}
+  const data = await fs.readFile(cpath, { encoding: null })
 
-var collectionHookDeprecationMessageDisplayed = false;
-function Hook() {
-  if (!collectionHookDeprecationMessageDisplayed) {
-    console.warn(
-      '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4'
-    );
-    collectionHookDeprecationMessageDisplayed = true;
+  if (stat.size !== data.length) {
+    throw sizeError(stat.size, data.length)
   }
-  return HookCollection();
+
+  if (!ssri.checkData(data, sri)) {
+    throw integrityError(sri, cpath)
+  }
+
+  return data
 }
 
-Hook.Singular = HookSingular.bind();
-Hook.Collection = HookCollection.bind();
+const readPipeline = (cpath, size, sri, stream) => {
+  stream.push(
+    new fsm.ReadStream(cpath, {
+      size,
+      readSize: MAX_SINGLE_READ_SIZE,
+    }),
+    ssri.integrityStream({
+      integrity: sri,
+      size,
+    })
+  )
+  return stream
+}
 
-module.exports = Hook;
-// expose constructors as a named property for TypeScript
-module.exports.Hook = Hook;
-module.exports.Singular = Hook.Singular;
-module.exports.Collection = Hook.Collection;
+module.exports.stream = readStream
+module.exports.readStream = readStream
 
+function readStream (cache, integrity, opts = {}) {
+  const { size } = opts
+  const stream = new Pipeline()
+  // Set all this up to run on the stream and then just return the stream
+  Promise.resolve().then(async () => {
+    const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
+      // get size
+      const stat = size ? { size } : await fs.stat(cpath)
+      return { stat, cpath, sri }
+    })
 
-/***/ }),
+    return readPipeline(cpath, stat.size, sri, stream)
+  }).catch(err => stream.emit('error', err))
 
-/***/ 22027:
-/***/ ((module) => {
+  return stream
+}
 
-module.exports = addHook;
+module.exports.copy = copy
 
-function addHook(state, kind, name, hook) {
-  var orig = hook;
-  if (!state.registry[name]) {
-    state.registry[name] = [];
-  }
+function copy (cache, integrity, dest) {
+  return withContentSri(cache, integrity, (cpath) => {
+    return fs.copyFile(cpath, dest)
+  })
+}
 
-  if (kind === "before") {
-    hook = function (method, options) {
-      return Promise.resolve()
-        .then(orig.bind(null, options))
-        .then(method.bind(null, options));
-    };
-  }
+module.exports.hasContent = hasContent
 
-  if (kind === "after") {
-    hook = function (method, options) {
-      var result;
-      return Promise.resolve()
-        .then(method.bind(null, options))
-        .then(function (result_) {
-          result = result_;
-          return orig(result, options);
-        })
-        .then(function () {
-          return result;
-        });
-    };
+async function hasContent (cache, integrity) {
+  if (!integrity) {
+    return false
   }
 
-  if (kind === "error") {
-    hook = function (method, options) {
-      return Promise.resolve()
-        .then(method.bind(null, options))
-        .catch(function (error) {
-          return orig(error, options);
-        });
-    };
-  }
+  try {
+    return await withContentSri(cache, integrity, async (cpath, sri) => {
+      const stat = await fs.stat(cpath)
+      return { size: stat.size, sri, stat }
+    })
+  } catch (err) {
+    if (err.code === 'ENOENT') {
+      return false
+    }
 
-  state.registry[name].push({
-    hook: hook,
-    orig: orig,
-  });
+    if (err.code === 'EPERM') {
+      /* istanbul ignore else */
+      if (process.platform !== 'win32') {
+        throw err
+      } else {
+        return false
+      }
+    }
+  }
 }
 
+async function withContentSri (cache, integrity, fn) {
+  const sri = ssri.parse(integrity)
+  // If `integrity` has multiple entries, pick the first digest
+  // with available local data.
+  const algo = sri.pickAlgorithm()
+  const digests = sri[algo]
 
-/***/ }),
-
-/***/ 11063:
-/***/ ((module) => {
-
-module.exports = register;
-
-function register(state, name, method, options) {
-  if (typeof method !== "function") {
-    throw new Error("method for before hook must be a function");
-  }
+  if (digests.length <= 1) {
+    const cpath = contentPath(cache, digests[0])
+    return fn(cpath, digests[0])
+  } else {
+    // Can't use race here because a generic error can happen before
+    // a ENOENT error, and can happen before a valid result
+    const results = await Promise.all(digests.map(async (meta) => {
+      try {
+        return await withContentSri(cache, meta, fn)
+      } catch (err) {
+        if (err.code === 'ENOENT') {
+          return Object.assign(
+            new Error('No matching content found for ' + sri.toString()),
+            { code: 'ENOENT' }
+          )
+        }
+        return err
+      }
+    }))
+    // Return the first non error if it is found
+    const result = results.find((r) => !(r instanceof Error))
+    if (result) {
+      return result
+    }
 
-  if (!options) {
-    options = {};
-  }
+    // Throw the No matching content found error
+    const enoentError = results.find((r) => r.code === 'ENOENT')
+    if (enoentError) {
+      throw enoentError
+    }
 
-  if (Array.isArray(name)) {
-    return name.reverse().reduce(function (callback, name) {
-      return register.bind(null, state, name, callback, options);
-    }, method)();
+    // Throw generic error
+    throw results.find((r) => r instanceof Error)
   }
+}
 
-  return Promise.resolve().then(function () {
-    if (!state.registry[name]) {
-      return method(options);
-    }
+function sizeError (expected, found) {
+  /* eslint-disable-next-line max-len */
+  const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
+  err.expected = expected
+  err.found = found
+  err.code = 'EBADSIZE'
+  return err
+}
 
-    return state.registry[name].reduce(function (method, registered) {
-      return registered.hook.bind(null, method, options);
-    }, method)();
-  });
+function integrityError (sri, path) {
+  const err = new Error(`Integrity verification failed for ${sri} (${path})`)
+  err.code = 'EINTEGRITY'
+  err.sri = sri
+  err.path = path
+  return err
 }
 
 
 /***/ }),
 
-/***/ 59934:
-/***/ ((module) => {
+/***/ 92447:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-module.exports = removeHook;
+"use strict";
 
-function removeHook(state, name, method) {
-  if (!state.registry[name]) {
-    return;
-  }
 
-  var index = state.registry[name]
-    .map(function (registered) {
-      return registered.orig;
-    })
-    .indexOf(method);
+const fs = __nccwpck_require__(91943)
+const contentPath = __nccwpck_require__(40233)
+const { hasContent } = __nccwpck_require__(39398)
 
-  if (index === -1) {
-    return;
-  }
+module.exports = rm
 
-  state.registry[name].splice(index, 1);
+async function rm (cache, integrity) {
+  const content = await hasContent(cache, integrity)
+  // ~pretty~ sure we can't end up with a content lacking sri, but be safe
+  if (content && content.sri) {
+    await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true })
+    return true
+  } else {
+    return false
+  }
 }
 
 
 /***/ }),
 
-/***/ 63251:
-/***/ (function(module) {
+/***/ 93699:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-/**
-  * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support.
-  * https://github.com/SGrondin/bottleneck
-  */
-(function (global, factory) {
-	 true ? module.exports = factory() :
-	0;
-}(this, (function () { 'use strict';
+"use strict";
 
-	var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
 
-	function getCjsExportFromNamespace (n) {
-		return n && n['default'] || n;
-	}
+const events = __nccwpck_require__(24434)
 
-	var load = function(received, defaults, onto = {}) {
-	  var k, ref, v;
-	  for (k in defaults) {
-	    v = defaults[k];
-	    onto[k] = (ref = received[k]) != null ? ref : v;
-	  }
-	  return onto;
-	};
+const contentPath = __nccwpck_require__(40233)
+const fs = __nccwpck_require__(91943)
+const { moveFile } = __nccwpck_require__(88437)
+const { Minipass } = __nccwpck_require__(78275)
+const Pipeline = __nccwpck_require__(52899)
+const Flush = __nccwpck_require__(37633)
+const path = __nccwpck_require__(16928)
+const ssri = __nccwpck_require__(68951)
+const uniqueFilename = __nccwpck_require__(46019)
+const fsm = __nccwpck_require__(25032)
 
-	var overwrite = function(received, defaults, onto = {}) {
-	  var k, v;
-	  for (k in received) {
-	    v = received[k];
-	    if (defaults[k] !== void 0) {
-	      onto[k] = v;
-	    }
-	  }
-	  return onto;
-	};
+module.exports = write
 
-	var parser = {
-		load: load,
-		overwrite: overwrite
-	};
+// Cache of move operations in process so we don't duplicate
+const moveOperations = new Map()
 
-	var DLList;
+async function write (cache, data, opts = {}) {
+  const { algorithms, size, integrity } = opts
 
-	DLList = class DLList {
-	  constructor(incr, decr) {
-	    this.incr = incr;
-	    this.decr = decr;
-	    this._first = null;
-	    this._last = null;
-	    this.length = 0;
-	  }
+  if (typeof size === 'number' && data.length !== size) {
+    throw sizeError(size, data.length)
+  }
 
-	  push(value) {
-	    var node;
-	    this.length++;
-	    if (typeof this.incr === "function") {
-	      this.incr();
-	    }
-	    node = {
-	      value,
-	      prev: this._last,
-	      next: null
-	    };
-	    if (this._last != null) {
-	      this._last.next = node;
-	      this._last = node;
-	    } else {
-	      this._first = this._last = node;
-	    }
-	    return void 0;
-	  }
+  const sri = ssri.fromData(data, algorithms ? { algorithms } : {})
+  if (integrity && !ssri.checkData(data, integrity, opts)) {
+    throw checksumError(integrity, sri)
+  }
 
-	  shift() {
-	    var value;
-	    if (this._first == null) {
-	      return;
-	    } else {
-	      this.length--;
-	      if (typeof this.decr === "function") {
-	        this.decr();
-	      }
-	    }
-	    value = this._first.value;
-	    if ((this._first = this._first.next) != null) {
-	      this._first.prev = null;
-	    } else {
-	      this._last = null;
-	    }
-	    return value;
-	  }
+  for (const algo in sri) {
+    const tmp = await makeTmp(cache, opts)
+    const hash = sri[algo].toString()
+    try {
+      await fs.writeFile(tmp.target, data, { flag: 'wx' })
+      await moveToDestination(tmp, cache, hash, opts)
+    } finally {
+      if (!tmp.moved) {
+        await fs.rm(tmp.target, { recursive: true, force: true })
+      }
+    }
+  }
+  return { integrity: sri, size: data.length }
+}
 
-	  first() {
-	    if (this._first != null) {
-	      return this._first.value;
-	    }
-	  }
+module.exports.stream = writeStream
 
-	  getArray() {
-	    var node, ref, results;
-	    node = this._first;
-	    results = [];
-	    while (node != null) {
-	      results.push((ref = node, node = node.next, ref.value));
-	    }
-	    return results;
-	  }
+// writes proxied to the 'inputStream' that is passed to the Promise
+// 'end' is deferred until content is handled.
+class CacacheWriteStream extends Flush {
+  constructor (cache, opts) {
+    super()
+    this.opts = opts
+    this.cache = cache
+    this.inputStream = new Minipass()
+    this.inputStream.on('error', er => this.emit('error', er))
+    this.inputStream.on('drain', () => this.emit('drain'))
+    this.handleContentP = null
+  }
 
-	  forEachShift(cb) {
-	    var node;
-	    node = this.shift();
-	    while (node != null) {
-	      (cb(node), node = this.shift());
-	    }
-	    return void 0;
-	  }
+  write (chunk, encoding, cb) {
+    if (!this.handleContentP) {
+      this.handleContentP = handleContent(
+        this.inputStream,
+        this.cache,
+        this.opts
+      )
+      this.handleContentP.catch(error => this.emit('error', error))
+    }
+    return this.inputStream.write(chunk, encoding, cb)
+  }
+
+  flush (cb) {
+    this.inputStream.end(() => {
+      if (!this.handleContentP) {
+        const e = new Error('Cache input stream was empty')
+        e.code = 'ENODATA'
+        // empty streams are probably emitting end right away.
+        // defer this one tick by rejecting a promise on it.
+        return Promise.reject(e).catch(cb)
+      }
+      // eslint-disable-next-line promise/catch-or-return
+      this.handleContentP.then(
+        (res) => {
+          res.integrity && this.emit('integrity', res.integrity)
+          // eslint-disable-next-line promise/always-return
+          res.size !== null && this.emit('size', res.size)
+          cb()
+        },
+        (er) => cb(er)
+      )
+    })
+  }
+}
+
+function writeStream (cache, opts = {}) {
+  return new CacacheWriteStream(cache, opts)
+}
+
+async function handleContent (inputStream, cache, opts) {
+  const tmp = await makeTmp(cache, opts)
+  try {
+    const res = await pipeToTmp(inputStream, cache, tmp.target, opts)
+    await moveToDestination(
+      tmp,
+      cache,
+      res.integrity,
+      opts
+    )
+    return res
+  } finally {
+    if (!tmp.moved) {
+      await fs.rm(tmp.target, { recursive: true, force: true })
+    }
+  }
+}
 
-	  debug() {
-	    var node, ref, ref1, ref2, results;
-	    node = this._first;
-	    results = [];
-	    while (node != null) {
-	      results.push((ref = node, node = node.next, {
-	        value: ref.value,
-	        prev: (ref1 = ref.prev) != null ? ref1.value : void 0,
-	        next: (ref2 = ref.next) != null ? ref2.value : void 0
-	      }));
-	    }
-	    return results;
-	  }
+async function pipeToTmp (inputStream, cache, tmpTarget, opts) {
+  const outStream = new fsm.WriteStream(tmpTarget, {
+    flags: 'wx',
+  })
 
-	};
+  if (opts.integrityEmitter) {
+    // we need to create these all simultaneously since they can fire in any order
+    const [integrity, size] = await Promise.all([
+      events.once(opts.integrityEmitter, 'integrity').then(res => res[0]),
+      events.once(opts.integrityEmitter, 'size').then(res => res[0]),
+      new Pipeline(inputStream, outStream).promise(),
+    ])
+    return { integrity, size }
+  }
 
-	var DLList_1 = DLList;
+  let integrity
+  let size
+  const hashStream = ssri.integrityStream({
+    integrity: opts.integrity,
+    algorithms: opts.algorithms,
+    size: opts.size,
+  })
+  hashStream.on('integrity', i => {
+    integrity = i
+  })
+  hashStream.on('size', s => {
+    size = s
+  })
 
-	var Events;
+  const pipeline = new Pipeline(inputStream, hashStream, outStream)
+  await pipeline.promise()
+  return { integrity, size }
+}
 
-	Events = class Events {
-	  constructor(instance) {
-	    this.instance = instance;
-	    this._events = {};
-	    if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) {
-	      throw new Error("An Emitter already exists for this object");
-	    }
-	    this.instance.on = (name, cb) => {
-	      return this._addListener(name, "many", cb);
-	    };
-	    this.instance.once = (name, cb) => {
-	      return this._addListener(name, "once", cb);
-	    };
-	    this.instance.removeAllListeners = (name = null) => {
-	      if (name != null) {
-	        return delete this._events[name];
-	      } else {
-	        return this._events = {};
-	      }
-	    };
-	  }
+async function makeTmp (cache, opts) {
+  const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix)
+  await fs.mkdir(path.dirname(tmpTarget), { recursive: true })
+  return {
+    target: tmpTarget,
+    moved: false,
+  }
+}
 
-	  _addListener(name, status, cb) {
-	    var base;
-	    if ((base = this._events)[name] == null) {
-	      base[name] = [];
-	    }
-	    this._events[name].push({cb, status});
-	    return this.instance;
-	  }
+async function moveToDestination (tmp, cache, sri) {
+  const destination = contentPath(cache, sri)
+  const destDir = path.dirname(destination)
+  if (moveOperations.has(destination)) {
+    return moveOperations.get(destination)
+  }
+  moveOperations.set(
+    destination,
+    fs.mkdir(destDir, { recursive: true })
+      .then(async () => {
+        await moveFile(tmp.target, destination, { overwrite: false })
+        tmp.moved = true
+        return tmp.moved
+      })
+      .catch(err => {
+        if (!err.message.startsWith('The destination file exists')) {
+          throw Object.assign(err, { code: 'EEXIST' })
+        }
+      }).finally(() => {
+        moveOperations.delete(destination)
+      })
 
-	  listenerCount(name) {
-	    if (this._events[name] != null) {
-	      return this._events[name].length;
-	    } else {
-	      return 0;
-	    }
-	  }
+  )
+  return moveOperations.get(destination)
+}
 
-	  async trigger(name, ...args) {
-	    var e, promises;
-	    try {
-	      if (name !== "debug") {
-	        this.trigger("debug", `Event triggered: ${name}`, args);
-	      }
-	      if (this._events[name] == null) {
-	        return;
-	      }
-	      this._events[name] = this._events[name].filter(function(listener) {
-	        return listener.status !== "none";
-	      });
-	      promises = this._events[name].map(async(listener) => {
-	        var e, returned;
-	        if (listener.status === "none") {
-	          return;
-	        }
-	        if (listener.status === "once") {
-	          listener.status = "none";
-	        }
-	        try {
-	          returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0;
-	          if (typeof (returned != null ? returned.then : void 0) === "function") {
-	            return (await returned);
-	          } else {
-	            return returned;
-	          }
-	        } catch (error) {
-	          e = error;
-	          {
-	            this.trigger("error", e);
-	          }
-	          return null;
-	        }
-	      });
-	      return ((await Promise.all(promises))).find(function(x) {
-	        return x != null;
-	      });
-	    } catch (error) {
-	      e = error;
-	      {
-	        this.trigger("error", e);
-	      }
-	      return null;
-	    }
-	  }
+function sizeError (expected, found) {
+  /* eslint-disable-next-line max-len */
+  const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
+  err.expected = expected
+  err.found = found
+  err.code = 'EBADSIZE'
+  return err
+}
 
-	};
+function checksumError (expected, found) {
+  const err = new Error(`Integrity check failed:
+  Wanted: ${expected}
+   Found: ${found}`)
+  err.code = 'EINTEGRITY'
+  err.expected = expected
+  err.found = found
+  return err
+}
 
-	var Events_1 = Events;
 
-	var DLList$1, Events$1, Queues;
+/***/ }),
 
-	DLList$1 = DLList_1;
+/***/ 26575:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	Events$1 = Events_1;
+"use strict";
 
-	Queues = class Queues {
-	  constructor(num_priorities) {
-	    var i;
-	    this.Events = new Events$1(this);
-	    this._length = 0;
-	    this._lists = (function() {
-	      var j, ref, results;
-	      results = [];
-	      for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {
-	        results.push(new DLList$1((() => {
-	          return this.incr();
-	        }), (() => {
-	          return this.decr();
-	        })));
-	      }
-	      return results;
-	    }).call(this);
-	  }
 
-	  incr() {
-	    if (this._length++ === 0) {
-	      return this.Events.trigger("leftzero");
-	    }
-	  }
+const crypto = __nccwpck_require__(76982)
+const {
+  appendFile,
+  mkdir,
+  readFile,
+  readdir,
+  rm,
+  writeFile,
+} = __nccwpck_require__(91943)
+const { Minipass } = __nccwpck_require__(78275)
+const path = __nccwpck_require__(16928)
+const ssri = __nccwpck_require__(68951)
+const uniqueFilename = __nccwpck_require__(46019)
 
-	  decr() {
-	    if (--this._length === 0) {
-	      return this.Events.trigger("zero");
-	    }
-	  }
+const contentPath = __nccwpck_require__(40233)
+const hashToSegments = __nccwpck_require__(99704)
+const indexV = (__nccwpck_require__(4038)/* ["cache-version"].index */ .MH.P)
+const { moveFile } = __nccwpck_require__(88437)
 
-	  push(job) {
-	    return this._lists[job.options.priority].push(job);
-	  }
+const lsStreamConcurrency = 5
 
-	  queued(priority) {
-	    if (priority != null) {
-	      return this._lists[priority].length;
-	    } else {
-	      return this._length;
-	    }
-	  }
+module.exports.NotFoundError = class NotFoundError extends Error {
+  constructor (cache, key) {
+    super(`No cache entry for ${key} found in ${cache}`)
+    this.code = 'ENOENT'
+    this.cache = cache
+    this.key = key
+  }
+}
 
-	  shiftAll(fn) {
-	    return this._lists.forEach(function(list) {
-	      return list.forEachShift(fn);
-	    });
-	  }
+module.exports.compact = compact
 
-	  getFirst(arr = this._lists) {
-	    var j, len, list;
-	    for (j = 0, len = arr.length; j < len; j++) {
-	      list = arr[j];
-	      if (list.length > 0) {
-	        return list;
-	      }
-	    }
-	    return [];
-	  }
+async function compact (cache, key, matchFn, opts = {}) {
+  const bucket = bucketPath(cache, key)
+  const entries = await bucketEntries(bucket)
+  const newEntries = []
+  // we loop backwards because the bottom-most result is the newest
+  // since we add new entries with appendFile
+  for (let i = entries.length - 1; i >= 0; --i) {
+    const entry = entries[i]
+    // a null integrity could mean either a delete was appended
+    // or the user has simply stored an index that does not map
+    // to any content. we determine if the user wants to keep the
+    // null integrity based on the validateEntry function passed in options.
+    // if the integrity is null and no validateEntry is provided, we break
+    // as we consider the null integrity to be a deletion of everything
+    // that came before it.
+    if (entry.integrity === null && !opts.validateEntry) {
+      break
+    }
 
-	  shiftLastFrom(priority) {
-	    return this.getFirst(this._lists.slice(priority).reverse()).shift();
-	  }
+    // if this entry is valid, and it is either the first entry or
+    // the newEntries array doesn't already include an entry that
+    // matches this one based on the provided matchFn, then we add
+    // it to the beginning of our list
+    if ((!opts.validateEntry || opts.validateEntry(entry) === true) &&
+      (newEntries.length === 0 ||
+        !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) {
+      newEntries.unshift(entry)
+    }
+  }
 
-	};
+  const newIndex = '\n' + newEntries.map((entry) => {
+    const stringified = JSON.stringify(entry)
+    const hash = hashEntry(stringified)
+    return `${hash}\t${stringified}`
+  }).join('\n')
 
-	var Queues_1 = Queues;
+  const setup = async () => {
+    const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix)
+    await mkdir(path.dirname(target), { recursive: true })
+    return {
+      target,
+      moved: false,
+    }
+  }
 
-	var BottleneckError;
+  const teardown = async (tmp) => {
+    if (!tmp.moved) {
+      return rm(tmp.target, { recursive: true, force: true })
+    }
+  }
 
-	BottleneckError = class BottleneckError extends Error {};
+  const write = async (tmp) => {
+    await writeFile(tmp.target, newIndex, { flag: 'wx' })
+    await mkdir(path.dirname(bucket), { recursive: true })
+    // we use @npmcli/move-file directly here because we
+    // want to overwrite the existing file
+    await moveFile(tmp.target, bucket)
+    tmp.moved = true
+  }
 
-	var BottleneckError_1 = BottleneckError;
+  // write the file atomically
+  const tmp = await setup()
+  try {
+    await write(tmp)
+  } finally {
+    await teardown(tmp)
+  }
 
-	var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1;
+  // we reverse the list we generated such that the newest
+  // entries come first in order to make looping through them easier
+  // the true passed to formatEntry tells it to keep null
+  // integrity values, if they made it this far it's because
+  // validateEntry returned true, and as such we should return it
+  return newEntries.reverse().map((entry) => formatEntry(cache, entry, true))
+}
 
-	NUM_PRIORITIES = 10;
+module.exports.insert = insert
 
-	DEFAULT_PRIORITY = 5;
+async function insert (cache, key, integrity, opts = {}) {
+  const { metadata, size, time } = opts
+  const bucket = bucketPath(cache, key)
+  const entry = {
+    key,
+    integrity: integrity && ssri.stringify(integrity),
+    time: time || Date.now(),
+    size,
+    metadata,
+  }
+  try {
+    await mkdir(path.dirname(bucket), { recursive: true })
+    const stringified = JSON.stringify(entry)
+    // NOTE - Cleverness ahoy!
+    //
+    // This works because it's tremendously unlikely for an entry to corrupt
+    // another while still preserving the string length of the JSON in
+    // question. So, we just slap the length in there and verify it on read.
+    //
+    // Thanks to @isaacs for the whiteboarding session that ended up with
+    // this.
+    await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`)
+  } catch (err) {
+    if (err.code === 'ENOENT') {
+      return undefined
+    }
 
-	parser$1 = parser;
+    throw err
+  }
+  return formatEntry(cache, entry)
+}
 
-	BottleneckError$1 = BottleneckError_1;
+module.exports.find = find
 
-	Job = class Job {
-	  constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) {
-	    this.task = task;
-	    this.args = args;
-	    this.rejectOnDrop = rejectOnDrop;
-	    this.Events = Events;
-	    this._states = _states;
-	    this.Promise = Promise;
-	    this.options = parser$1.load(options, jobDefaults);
-	    this.options.priority = this._sanitizePriority(this.options.priority);
-	    if (this.options.id === jobDefaults.id) {
-	      this.options.id = `${this.options.id}-${this._randomIndex()}`;
-	    }
-	    this.promise = new this.Promise((_resolve, _reject) => {
-	      this._resolve = _resolve;
-	      this._reject = _reject;
-	    });
-	    this.retryCount = 0;
-	  }
+async function find (cache, key) {
+  const bucket = bucketPath(cache, key)
+  try {
+    const entries = await bucketEntries(bucket)
+    return entries.reduce((latest, next) => {
+      if (next && next.key === key) {
+        return formatEntry(cache, next)
+      } else {
+        return latest
+      }
+    }, null)
+  } catch (err) {
+    if (err.code === 'ENOENT') {
+      return null
+    } else {
+      throw err
+    }
+  }
+}
 
-	  _sanitizePriority(priority) {
-	    var sProperty;
-	    sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;
-	    if (sProperty < 0) {
-	      return 0;
-	    } else if (sProperty > NUM_PRIORITIES - 1) {
-	      return NUM_PRIORITIES - 1;
-	    } else {
-	      return sProperty;
-	    }
-	  }
+module.exports["delete"] = del
 
-	  _randomIndex() {
-	    return Math.random().toString(36).slice(2);
-	  }
+function del (cache, key, opts = {}) {
+  if (!opts.removeFully) {
+    return insert(cache, key, null, opts)
+  }
 
-	  doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) {
-	    if (this._states.remove(this.options.id)) {
-	      if (this.rejectOnDrop) {
-	        this._reject(error != null ? error : new BottleneckError$1(message));
-	      }
-	      this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise});
-	      return true;
-	    } else {
-	      return false;
-	    }
-	  }
+  const bucket = bucketPath(cache, key)
+  return rm(bucket, { recursive: true, force: true })
+}
 
-	  _assertStatus(expected) {
-	    var status;
-	    status = this._states.jobStatus(this.options.id);
-	    if (!(status === expected || (expected === "DONE" && status === null))) {
-	      throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`);
-	    }
-	  }
+module.exports.lsStream = lsStream
 
-	  doReceive() {
-	    this._states.start(this.options.id);
-	    return this.Events.trigger("received", {args: this.args, options: this.options});
-	  }
+function lsStream (cache) {
+  const indexDir = bucketDir(cache)
+  const stream = new Minipass({ objectMode: true })
 
-	  doQueue(reachedHWM, blocked) {
-	    this._assertStatus("RECEIVED");
-	    this._states.next(this.options.id);
-	    return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked});
-	  }
+  // Set all this up to run on the stream and then just return the stream
+  Promise.resolve().then(async () => {
+    const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606))
+    const buckets = await readdirOrEmpty(indexDir)
+    await pMap(buckets, async (bucket) => {
+      const bucketPath = path.join(indexDir, bucket)
+      const subbuckets = await readdirOrEmpty(bucketPath)
+      await pMap(subbuckets, async (subbucket) => {
+        const subbucketPath = path.join(bucketPath, subbucket)
 
-	  doRun() {
-	    if (this.retryCount === 0) {
-	      this._assertStatus("QUEUED");
-	      this._states.next(this.options.id);
-	    } else {
-	      this._assertStatus("EXECUTING");
-	    }
-	    return this.Events.trigger("scheduled", {args: this.args, options: this.options});
-	  }
+        // "/cachename//./*"
+        const subbucketEntries = await readdirOrEmpty(subbucketPath)
+        await pMap(subbucketEntries, async (entry) => {
+          const entryPath = path.join(subbucketPath, entry)
+          try {
+            const entries = await bucketEntries(entryPath)
+            // using a Map here prevents duplicate keys from showing up
+            // twice, I guess?
+            const reduced = entries.reduce((acc, entry) => {
+              acc.set(entry.key, entry)
+              return acc
+            }, new Map())
+            // reduced is a map of key => entry
+            for (const entry of reduced.values()) {
+              const formatted = formatEntry(cache, entry)
+              if (formatted) {
+                stream.write(formatted)
+              }
+            }
+          } catch (err) {
+            if (err.code === 'ENOENT') {
+              return undefined
+            }
+            throw err
+          }
+        },
+        { concurrency: lsStreamConcurrency })
+      },
+      { concurrency: lsStreamConcurrency })
+    },
+    { concurrency: lsStreamConcurrency })
+    stream.end()
+    return stream
+  }).catch(err => stream.emit('error', err))
 
-	  async doExecute(chained, clearGlobalState, run, free) {
-	    var error, eventInfo, passed;
-	    if (this.retryCount === 0) {
-	      this._assertStatus("RUNNING");
-	      this._states.next(this.options.id);
-	    } else {
-	      this._assertStatus("EXECUTING");
-	    }
-	    eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};
-	    this.Events.trigger("executing", eventInfo);
-	    try {
-	      passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)));
-	      if (clearGlobalState()) {
-	        this.doDone(eventInfo);
-	        await free(this.options, eventInfo);
-	        this._assertStatus("DONE");
-	        return this._resolve(passed);
-	      }
-	    } catch (error1) {
-	      error = error1;
-	      return this._onFailure(error, eventInfo, clearGlobalState, run, free);
-	    }
-	  }
+  return stream
+}
 
-	  doExpire(clearGlobalState, run, free) {
-	    var error, eventInfo;
-	    if (this._states.jobStatus(this.options.id === "RUNNING")) {
-	      this._states.next(this.options.id);
-	    }
-	    this._assertStatus("EXECUTING");
-	    eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};
-	    error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`);
-	    return this._onFailure(error, eventInfo, clearGlobalState, run, free);
-	  }
+module.exports.ls = ls
 
-	  async _onFailure(error, eventInfo, clearGlobalState, run, free) {
-	    var retry, retryAfter;
-	    if (clearGlobalState()) {
-	      retry = (await this.Events.trigger("failed", error, eventInfo));
-	      if (retry != null) {
-	        retryAfter = ~~retry;
-	        this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo);
-	        this.retryCount++;
-	        return run(retryAfter);
-	      } else {
-	        this.doDone(eventInfo);
-	        await free(this.options, eventInfo);
-	        this._assertStatus("DONE");
-	        return this._reject(error);
-	      }
-	    }
-	  }
+async function ls (cache) {
+  const entries = await lsStream(cache).collect()
+  return entries.reduce((acc, xs) => {
+    acc[xs.key] = xs
+    return acc
+  }, {})
+}
 
-	  doDone(eventInfo) {
-	    this._assertStatus("EXECUTING");
-	    this._states.next(this.options.id);
-	    return this.Events.trigger("done", eventInfo);
-	  }
+module.exports.bucketEntries = bucketEntries
 
-	};
+async function bucketEntries (bucket, filter) {
+  const data = await readFile(bucket, 'utf8')
+  return _bucketEntries(data, filter)
+}
 
-	var Job_1 = Job;
+function _bucketEntries (data) {
+  const entries = []
+  data.split('\n').forEach((entry) => {
+    if (!entry) {
+      return
+    }
 
-	var BottleneckError$2, LocalDatastore, parser$2;
+    const pieces = entry.split('\t')
+    if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) {
+      // Hash is no good! Corruption or malice? Doesn't matter!
+      // EJECT EJECT
+      return
+    }
+    let obj
+    try {
+      obj = JSON.parse(pieces[1])
+    } catch (_) {
+      // eslint-ignore-next-line no-empty-block
+    }
+    // coverage disabled here, no need to test with an entry that parses to something falsey
+    // istanbul ignore else
+    if (obj) {
+      entries.push(obj)
+    }
+  })
+  return entries
+}
 
-	parser$2 = parser;
+module.exports.bucketDir = bucketDir
 
-	BottleneckError$2 = BottleneckError_1;
+function bucketDir (cache) {
+  return path.join(cache, `index-v${indexV}`)
+}
 
-	LocalDatastore = class LocalDatastore {
-	  constructor(instance, storeOptions, storeInstanceOptions) {
-	    this.instance = instance;
-	    this.storeOptions = storeOptions;
-	    this.clientId = this.instance._randomIndex();
-	    parser$2.load(storeInstanceOptions, storeInstanceOptions, this);
-	    this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now();
-	    this._running = 0;
-	    this._done = 0;
-	    this._unblockTime = 0;
-	    this.ready = this.Promise.resolve();
-	    this.clients = {};
-	    this._startHeartbeat();
-	  }
+module.exports.bucketPath = bucketPath
 
-	  _startHeartbeat() {
-	    var base;
-	    if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) {
-	      return typeof (base = (this.heartbeat = setInterval(() => {
-	        var amount, incr, maximum, now, reservoir;
-	        now = Date.now();
-	        if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) {
-	          this._lastReservoirRefresh = now;
-	          this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount;
-	          this.instance._drainAll(this.computeCapacity());
-	        }
-	        if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {
-	          ({
-	            reservoirIncreaseAmount: amount,
-	            reservoirIncreaseMaximum: maximum,
-	            reservoir
-	          } = this.storeOptions);
-	          this._lastReservoirIncrease = now;
-	          incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount;
-	          if (incr > 0) {
-	            this.storeOptions.reservoir += incr;
-	            return this.instance._drainAll(this.computeCapacity());
-	          }
-	        }
-	      }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0;
-	    } else {
-	      return clearInterval(this.heartbeat);
-	    }
-	  }
+function bucketPath (cache, key) {
+  const hashed = hashKey(key)
+  return path.join.apply(
+    path,
+    [bucketDir(cache)].concat(hashToSegments(hashed))
+  )
+}
 
-	  async __publish__(message) {
-	    await this.yieldLoop();
-	    return this.instance.Events.trigger("message", message.toString());
-	  }
+module.exports.hashKey = hashKey
 
-	  async __disconnect__(flush) {
-	    await this.yieldLoop();
-	    clearInterval(this.heartbeat);
-	    return this.Promise.resolve();
-	  }
+function hashKey (key) {
+  return hash(key, 'sha256')
+}
 
-	  yieldLoop(t = 0) {
-	    return new this.Promise(function(resolve, reject) {
-	      return setTimeout(resolve, t);
-	    });
-	  }
+module.exports.hashEntry = hashEntry
 
-	  computePenalty() {
-	    var ref;
-	    return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000;
-	  }
+function hashEntry (str) {
+  return hash(str, 'sha1')
+}
 
-	  async __updateSettings__(options) {
-	    await this.yieldLoop();
-	    parser$2.overwrite(options, options, this.storeOptions);
-	    this._startHeartbeat();
-	    this.instance._drainAll(this.computeCapacity());
-	    return true;
-	  }
+function hash (str, digest) {
+  return crypto
+    .createHash(digest)
+    .update(str)
+    .digest('hex')
+}
 
-	  async __running__() {
-	    await this.yieldLoop();
-	    return this._running;
-	  }
+function formatEntry (cache, entry, keepAll) {
+  // Treat null digests as deletions. They'll shadow any previous entries.
+  if (!entry.integrity && !keepAll) {
+    return null
+  }
 
-	  async __queued__() {
-	    await this.yieldLoop();
-	    return this.instance.queued();
-	  }
+  return {
+    key: entry.key,
+    integrity: entry.integrity,
+    path: entry.integrity ? contentPath(cache, entry.integrity) : undefined,
+    size: entry.size,
+    time: entry.time,
+    metadata: entry.metadata,
+  }
+}
 
-	  async __done__() {
-	    await this.yieldLoop();
-	    return this._done;
-	  }
+function readdirOrEmpty (dir) {
+  return readdir(dir).catch((err) => {
+    if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
+      return []
+    }
 
-	  async __groupCheck__(time) {
-	    await this.yieldLoop();
-	    return (this._nextRequest + this.timeout) < time;
-	  }
+    throw err
+  })
+}
 
-	  computeCapacity() {
-	    var maxConcurrent, reservoir;
-	    ({maxConcurrent, reservoir} = this.storeOptions);
-	    if ((maxConcurrent != null) && (reservoir != null)) {
-	      return Math.min(maxConcurrent - this._running, reservoir);
-	    } else if (maxConcurrent != null) {
-	      return maxConcurrent - this._running;
-	    } else if (reservoir != null) {
-	      return reservoir;
-	    } else {
-	      return null;
-	    }
-	  }
 
-	  conditionsCheck(weight) {
-	    var capacity;
-	    capacity = this.computeCapacity();
-	    return (capacity == null) || weight <= capacity;
-	  }
+/***/ }),
 
-	  async __incrementReservoir__(incr) {
-	    var reservoir;
-	    await this.yieldLoop();
-	    reservoir = this.storeOptions.reservoir += incr;
-	    this.instance._drainAll(this.computeCapacity());
-	    return reservoir;
-	  }
+/***/ 19690:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	  async __currentReservoir__() {
-	    await this.yieldLoop();
-	    return this.storeOptions.reservoir;
-	  }
+"use strict";
 
-	  isBlocked(now) {
-	    return this._unblockTime >= now;
-	  }
 
-	  check(weight, now) {
-	    return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0;
-	  }
+const Collect = __nccwpck_require__(11757)
+const { Minipass } = __nccwpck_require__(78275)
+const Pipeline = __nccwpck_require__(52899)
 
-	  async __check__(weight) {
-	    var now;
-	    await this.yieldLoop();
-	    now = Date.now();
-	    return this.check(weight, now);
-	  }
+const index = __nccwpck_require__(26575)
+const memo = __nccwpck_require__(56068)
+const read = __nccwpck_require__(39398)
 
-	  async __register__(index, weight, expiration) {
-	    var now, wait;
-	    await this.yieldLoop();
-	    now = Date.now();
-	    if (this.conditionsCheck(weight)) {
-	      this._running += weight;
-	      if (this.storeOptions.reservoir != null) {
-	        this.storeOptions.reservoir -= weight;
-	      }
-	      wait = Math.max(this._nextRequest - now, 0);
-	      this._nextRequest = now + wait + this.storeOptions.minTime;
-	      return {
-	        success: true,
-	        wait,
-	        reservoir: this.storeOptions.reservoir
-	      };
-	    } else {
-	      return {
-	        success: false
-	      };
-	    }
-	  }
+async function getData (cache, key, opts = {}) {
+  const { integrity, memoize, size } = opts
+  const memoized = memo.get(cache, key, opts)
+  if (memoized && memoize !== false) {
+    return {
+      metadata: memoized.entry.metadata,
+      data: memoized.data,
+      integrity: memoized.entry.integrity,
+      size: memoized.entry.size,
+    }
+  }
 
-	  strategyIsBlock() {
-	    return this.storeOptions.strategy === 3;
-	  }
+  const entry = await index.find(cache, key, opts)
+  if (!entry) {
+    throw new index.NotFoundError(cache, key)
+  }
+  const data = await read(cache, entry.integrity, { integrity, size })
+  if (memoize) {
+    memo.put(cache, entry, data, opts)
+  }
 
-	  async __submit__(queueLength, weight) {
-	    var blocked, now, reachedHWM;
-	    await this.yieldLoop();
-	    if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) {
-	      throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);
-	    }
-	    now = Date.now();
-	    reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now);
-	    blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));
-	    if (blocked) {
-	      this._unblockTime = now + this.computePenalty();
-	      this._nextRequest = this._unblockTime + this.storeOptions.minTime;
-	      this.instance._dropAllQueued();
-	    }
-	    return {
-	      reachedHWM,
-	      blocked,
-	      strategy: this.storeOptions.strategy
-	    };
-	  }
+  return {
+    data,
+    metadata: entry.metadata,
+    size: entry.size,
+    integrity: entry.integrity,
+  }
+}
+module.exports = getData
 
-	  async __free__(index, weight) {
-	    await this.yieldLoop();
-	    this._running -= weight;
-	    this._done += weight;
-	    this.instance._drainAll(this.computeCapacity());
-	    return {
-	      running: this._running
-	    };
-	  }
+async function getDataByDigest (cache, key, opts = {}) {
+  const { integrity, memoize, size } = opts
+  const memoized = memo.get.byDigest(cache, key, opts)
+  if (memoized && memoize !== false) {
+    return memoized
+  }
 
-	};
+  const res = await read(cache, key, { integrity, size })
+  if (memoize) {
+    memo.put.byDigest(cache, key, res, opts)
+  }
+  return res
+}
+module.exports.byDigest = getDataByDigest
 
-	var LocalDatastore_1 = LocalDatastore;
+const getMemoizedStream = (memoized) => {
+  const stream = new Minipass()
+  stream.on('newListener', function (ev, cb) {
+    ev === 'metadata' && cb(memoized.entry.metadata)
+    ev === 'integrity' && cb(memoized.entry.integrity)
+    ev === 'size' && cb(memoized.entry.size)
+  })
+  stream.end(memoized.data)
+  return stream
+}
 
-	var BottleneckError$3, States;
+function getStream (cache, key, opts = {}) {
+  const { memoize, size } = opts
+  const memoized = memo.get(cache, key, opts)
+  if (memoized && memoize !== false) {
+    return getMemoizedStream(memoized)
+  }
 
-	BottleneckError$3 = BottleneckError_1;
+  const stream = new Pipeline()
+  // Set all this up to run on the stream and then just return the stream
+  Promise.resolve().then(async () => {
+    const entry = await index.find(cache, key)
+    if (!entry) {
+      throw new index.NotFoundError(cache, key)
+    }
 
-	States = class States {
-	  constructor(status1) {
-	    this.status = status1;
-	    this._jobs = {};
-	    this.counts = this.status.map(function() {
-	      return 0;
-	    });
-	  }
+    stream.emit('metadata', entry.metadata)
+    stream.emit('integrity', entry.integrity)
+    stream.emit('size', entry.size)
+    stream.on('newListener', function (ev, cb) {
+      ev === 'metadata' && cb(entry.metadata)
+      ev === 'integrity' && cb(entry.integrity)
+      ev === 'size' && cb(entry.size)
+    })
 
-	  next(id) {
-	    var current, next;
-	    current = this._jobs[id];
-	    next = current + 1;
-	    if ((current != null) && next < this.status.length) {
-	      this.counts[current]--;
-	      this.counts[next]++;
-	      return this._jobs[id]++;
-	    } else if (current != null) {
-	      this.counts[current]--;
-	      return delete this._jobs[id];
-	    }
-	  }
+    const src = read.readStream(
+      cache,
+      entry.integrity,
+      { ...opts, size: typeof size !== 'number' ? entry.size : size }
+    )
 
-	  start(id) {
-	    var initial;
-	    initial = 0;
-	    this._jobs[id] = initial;
-	    return this.counts[initial]++;
-	  }
+    if (memoize) {
+      const memoStream = new Collect.PassThrough()
+      memoStream.on('collect', data => memo.put(cache, entry, data, opts))
+      stream.unshift(memoStream)
+    }
+    stream.unshift(src)
+    return stream
+  }).catch((err) => stream.emit('error', err))
 
-	  remove(id) {
-	    var current;
-	    current = this._jobs[id];
-	    if (current != null) {
-	      this.counts[current]--;
-	      delete this._jobs[id];
-	    }
-	    return current != null;
-	  }
+  return stream
+}
 
-	  jobStatus(id) {
-	    var ref;
-	    return (ref = this.status[this._jobs[id]]) != null ? ref : null;
-	  }
+module.exports.stream = getStream
 
-	  statusJobs(status) {
-	    var k, pos, ref, results, v;
-	    if (status != null) {
-	      pos = this.status.indexOf(status);
-	      if (pos < 0) {
-	        throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`);
-	      }
-	      ref = this._jobs;
-	      results = [];
-	      for (k in ref) {
-	        v = ref[k];
-	        if (v === pos) {
-	          results.push(k);
-	        }
-	      }
-	      return results;
-	    } else {
-	      return Object.keys(this._jobs);
-	    }
-	  }
+function getStreamDigest (cache, integrity, opts = {}) {
+  const { memoize } = opts
+  const memoized = memo.get.byDigest(cache, integrity, opts)
+  if (memoized && memoize !== false) {
+    const stream = new Minipass()
+    stream.end(memoized)
+    return stream
+  } else {
+    const stream = read.readStream(cache, integrity, opts)
+    if (!memoize) {
+      return stream
+    }
 
-	  statusCounts() {
-	    return this.counts.reduce(((acc, v, i) => {
-	      acc[this.status[i]] = v;
-	      return acc;
-	    }), {});
-	  }
+    const memoStream = new Collect.PassThrough()
+    memoStream.on('collect', data => memo.put.byDigest(
+      cache,
+      integrity,
+      data,
+      opts
+    ))
+    return new Pipeline(stream, memoStream)
+  }
+}
 
-	};
+module.exports.stream.byDigest = getStreamDigest
 
-	var States_1 = States;
+function info (cache, key, opts = {}) {
+  const { memoize } = opts
+  const memoized = memo.get(cache, key, opts)
+  if (memoized && memoize !== false) {
+    return Promise.resolve(memoized.entry)
+  } else {
+    return index.find(cache, key)
+  }
+}
+module.exports.info = info
 
-	var DLList$2, Sync;
+async function copy (cache, key, dest, opts = {}) {
+  const entry = await index.find(cache, key, opts)
+  if (!entry) {
+    throw new index.NotFoundError(cache, key)
+  }
+  await read.copy(cache, entry.integrity, dest, opts)
+  return {
+    metadata: entry.metadata,
+    size: entry.size,
+    integrity: entry.integrity,
+  }
+}
 
-	DLList$2 = DLList_1;
+module.exports.copy = copy
 
-	Sync = class Sync {
-	  constructor(name, Promise) {
-	    this.schedule = this.schedule.bind(this);
-	    this.name = name;
-	    this.Promise = Promise;
-	    this._running = 0;
-	    this._queue = new DLList$2();
-	  }
+async function copyByDigest (cache, key, dest, opts = {}) {
+  await read.copy(cache, key, dest, opts)
+  return key
+}
 
-	  isEmpty() {
-	    return this._queue.length === 0;
-	  }
+module.exports.copy.byDigest = copyByDigest
 
-	  async _tryToRun() {
-	    var args, cb, error, reject, resolve, returned, task;
-	    if ((this._running < 1) && this._queue.length > 0) {
-	      this._running++;
-	      ({task, args, resolve, reject} = this._queue.shift());
-	      cb = (await (async function() {
-	        try {
-	          returned = (await task(...args));
-	          return function() {
-	            return resolve(returned);
-	          };
-	        } catch (error1) {
-	          error = error1;
-	          return function() {
-	            return reject(error);
-	          };
-	        }
-	      })());
-	      this._running--;
-	      this._tryToRun();
-	      return cb();
-	    }
-	  }
+module.exports.hasContent = read.hasContent
 
-	  schedule(task, ...args) {
-	    var promise, reject, resolve;
-	    resolve = reject = null;
-	    promise = new this.Promise(function(_resolve, _reject) {
-	      resolve = _resolve;
-	      return reject = _reject;
-	    });
-	    this._queue.push({task, args, resolve, reject});
-	    this._tryToRun();
-	    return promise;
-	  }
 
-	};
+/***/ }),
 
-	var Sync_1 = Sync;
+/***/ 85742:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	var version = "2.19.5";
-	var version$1 = {
-		version: version
-	};
+"use strict";
 
-	var version$2 = /*#__PURE__*/Object.freeze({
-		version: version,
-		default: version$1
-	});
 
-	var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
+const get = __nccwpck_require__(19690)
+const put = __nccwpck_require__(94283)
+const rm = __nccwpck_require__(30793)
+const verify = __nccwpck_require__(37621)
+const { clearMemoized } = __nccwpck_require__(56068)
+const tmp = __nccwpck_require__(63990)
+const index = __nccwpck_require__(26575)
 
-	var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
+module.exports.index = {}
+module.exports.index.compact = index.compact
+module.exports.index.insert = index.insert
 
-	var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
+module.exports.ls = index.ls
+module.exports.ls.stream = index.lsStream
 
-	var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3;
+module.exports.get = get
+module.exports.get.byDigest = get.byDigest
+module.exports.get.stream = get.stream
+module.exports.get.stream.byDigest = get.stream.byDigest
+module.exports.get.copy = get.copy
+module.exports.get.copy.byDigest = get.copy.byDigest
+module.exports.get.info = get.info
+module.exports.get.hasContent = get.hasContent
 
-	parser$3 = parser;
+module.exports.put = put
+module.exports.put.stream = put.stream
 
-	Events$2 = Events_1;
+module.exports.rm = rm.entry
+module.exports.rm.all = rm.all
+module.exports.rm.entry = module.exports.rm
+module.exports.rm.content = rm.content
 
-	RedisConnection$1 = require$$2;
+module.exports.clearMemoized = clearMemoized
 
-	IORedisConnection$1 = require$$3;
+module.exports.tmp = {}
+module.exports.tmp.mkdir = tmp.mkdir
+module.exports.tmp.withTmp = tmp.withTmp
 
-	Scripts$1 = require$$4;
+module.exports.verify = verify
+module.exports.verify.lastRun = verify.lastRun
 
-	Group = (function() {
-	  class Group {
-	    constructor(limiterOptions = {}) {
-	      this.deleteKey = this.deleteKey.bind(this);
-	      this.limiterOptions = limiterOptions;
-	      parser$3.load(this.limiterOptions, this.defaults, this);
-	      this.Events = new Events$2(this);
-	      this.instances = {};
-	      this.Bottleneck = Bottleneck_1;
-	      this._startAutoCleanup();
-	      this.sharedConnection = this.connection != null;
-	      if (this.connection == null) {
-	        if (this.limiterOptions.datastore === "redis") {
-	          this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));
-	        } else if (this.limiterOptions.datastore === "ioredis") {
-	          this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));
-	        }
-	      }
-	    }
 
-	    key(key = "") {
-	      var ref;
-	      return (ref = this.instances[key]) != null ? ref : (() => {
-	        var limiter;
-	        limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {
-	          id: `${this.id}-${key}`,
-	          timeout: this.timeout,
-	          connection: this.connection
-	        }));
-	        this.Events.trigger("created", limiter, key);
-	        return limiter;
-	      })();
-	    }
+/***/ }),
 
-	    async deleteKey(key = "") {
-	      var deleted, instance;
-	      instance = this.instances[key];
-	      if (this.connection) {
-	        deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)]));
-	      }
-	      if (instance != null) {
-	        delete this.instances[key];
-	        await instance.disconnect();
-	      }
-	      return (instance != null) || deleted > 0;
-	    }
+/***/ 56068:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	    limiters() {
-	      var k, ref, results, v;
-	      ref = this.instances;
-	      results = [];
-	      for (k in ref) {
-	        v = ref[k];
-	        results.push({
-	          key: k,
-	          limiter: v
-	        });
-	      }
-	      return results;
-	    }
+"use strict";
 
-	    keys() {
-	      return Object.keys(this.instances);
-	    }
 
-	    async clusterKeys() {
-	      var cursor, end, found, i, k, keys, len, next, start;
-	      if (this.connection == null) {
-	        return this.Promise.resolve(this.keys());
-	      }
-	      keys = [];
-	      cursor = null;
-	      start = `b_${this.id}-`.length;
-	      end = "_settings".length;
-	      while (cursor !== 0) {
-	        [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000]));
-	        cursor = ~~next;
-	        for (i = 0, len = found.length; i < len; i++) {
-	          k = found[i];
-	          keys.push(k.slice(start, -end));
-	        }
-	      }
-	      return keys;
-	    }
+const { LRUCache } = __nccwpck_require__(83193)
 
-	    _startAutoCleanup() {
-	      var base;
-	      clearInterval(this.interval);
-	      return typeof (base = (this.interval = setInterval(async() => {
-	        var e, k, ref, results, time, v;
-	        time = Date.now();
-	        ref = this.instances;
-	        results = [];
-	        for (k in ref) {
-	          v = ref[k];
-	          try {
-	            if ((await v._store.__groupCheck__(time))) {
-	              results.push(this.deleteKey(k));
-	            } else {
-	              results.push(void 0);
-	            }
-	          } catch (error) {
-	            e = error;
-	            results.push(v.Events.trigger("error", e));
-	          }
-	        }
-	        return results;
-	      }, this.timeout / 2))).unref === "function" ? base.unref() : void 0;
-	    }
+const MEMOIZED = new LRUCache({
+  max: 500,
+  maxSize: 50 * 1024 * 1024, // 50MB
+  ttl: 3 * 60 * 1000, // 3 minutes
+  sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length,
+})
 
-	    updateSettings(options = {}) {
-	      parser$3.overwrite(options, this.defaults, this);
-	      parser$3.overwrite(options, options, this.limiterOptions);
-	      if (options.timeout != null) {
-	        return this._startAutoCleanup();
-	      }
-	    }
+module.exports.clearMemoized = clearMemoized
 
-	    disconnect(flush = true) {
-	      var ref;
-	      if (!this.sharedConnection) {
-	        return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
-	      }
-	    }
+function clearMemoized () {
+  const old = {}
+  MEMOIZED.forEach((v, k) => {
+    old[k] = v
+  })
+  MEMOIZED.clear()
+  return old
+}
 
-	  }
-	  Group.prototype.defaults = {
-	    timeout: 1000 * 60 * 5,
-	    connection: null,
-	    Promise: Promise,
-	    id: "group-key"
-	  };
+module.exports.put = put
 
-	  return Group;
+function put (cache, entry, data, opts) {
+  pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data })
+  putDigest(cache, entry.integrity, data, opts)
+}
 
-	}).call(commonjsGlobal);
+module.exports.put.byDigest = putDigest
 
-	var Group_1 = Group;
+function putDigest (cache, integrity, data, opts) {
+  pickMem(opts).set(`digest:${cache}:${integrity}`, data)
+}
 
-	var Batcher, Events$3, parser$4;
+module.exports.get = get
 
-	parser$4 = parser;
+function get (cache, key, opts) {
+  return pickMem(opts).get(`key:${cache}:${key}`)
+}
 
-	Events$3 = Events_1;
+module.exports.get.byDigest = getDigest
 
-	Batcher = (function() {
-	  class Batcher {
-	    constructor(options = {}) {
-	      this.options = options;
-	      parser$4.load(this.options, this.defaults, this);
-	      this.Events = new Events$3(this);
-	      this._arr = [];
-	      this._resetPromise();
-	      this._lastFlush = Date.now();
-	    }
+function getDigest (cache, integrity, opts) {
+  return pickMem(opts).get(`digest:${cache}:${integrity}`)
+}
 
-	    _resetPromise() {
-	      return this._promise = new this.Promise((res, rej) => {
-	        return this._resolve = res;
-	      });
-	    }
+class ObjProxy {
+  constructor (obj) {
+    this.obj = obj
+  }
 
-	    _flush() {
-	      clearTimeout(this._timeout);
-	      this._lastFlush = Date.now();
-	      this._resolve();
-	      this.Events.trigger("batch", this._arr);
-	      this._arr = [];
-	      return this._resetPromise();
-	    }
+  get (key) {
+    return this.obj[key]
+  }
 
-	    add(data) {
-	      var ret;
-	      this._arr.push(data);
-	      ret = this._promise;
-	      if (this._arr.length === this.maxSize) {
-	        this._flush();
-	      } else if ((this.maxTime != null) && this._arr.length === 1) {
-	        this._timeout = setTimeout(() => {
-	          return this._flush();
-	        }, this.maxTime);
-	      }
-	      return ret;
-	    }
+  set (key, val) {
+    this.obj[key] = val
+  }
+}
 
-	  }
-	  Batcher.prototype.defaults = {
-	    maxTime: null,
-	    maxSize: null,
-	    Promise: Promise
-	  };
+function pickMem (opts) {
+  if (!opts || !opts.memoize) {
+    return MEMOIZED
+  } else if (opts.memoize.get && opts.memoize.set) {
+    return opts.memoize
+  } else if (typeof opts.memoize === 'object') {
+    return new ObjProxy(opts.memoize)
+  } else {
+    return MEMOIZED
+  }
+}
 
-	  return Batcher;
 
-	}).call(commonjsGlobal);
+/***/ }),
 
-	var Batcher_1 = Batcher;
+/***/ 94283:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');
+"use strict";
 
-	var require$$8 = getCjsExportFromNamespace(version$2);
 
-	var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5,
-	  splice = [].splice;
+const index = __nccwpck_require__(26575)
+const memo = __nccwpck_require__(56068)
+const write = __nccwpck_require__(93699)
+const Flush = __nccwpck_require__(37633)
+const { PassThrough } = __nccwpck_require__(11757)
+const Pipeline = __nccwpck_require__(52899)
 
-	NUM_PRIORITIES$1 = 10;
+const putOpts = (opts) => ({
+  algorithms: ['sha512'],
+  ...opts,
+})
 
-	DEFAULT_PRIORITY$1 = 5;
+module.exports = putData
 
-	parser$5 = parser;
+async function putData (cache, key, data, opts = {}) {
+  const { memoize } = opts
+  opts = putOpts(opts)
+  const res = await write(cache, data, opts)
+  const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size })
+  if (memoize) {
+    memo.put(cache, entry, data, opts)
+  }
 
-	Queues$1 = Queues_1;
+  return res.integrity
+}
 
-	Job$1 = Job_1;
+module.exports.stream = putStream
 
-	LocalDatastore$1 = LocalDatastore_1;
+function putStream (cache, key, opts = {}) {
+  const { memoize } = opts
+  opts = putOpts(opts)
+  let integrity
+  let size
+  let error
 
-	RedisDatastore$1 = require$$4$1;
+  let memoData
+  const pipeline = new Pipeline()
+  // first item in the pipeline is the memoizer, because we need
+  // that to end first and get the collected data.
+  if (memoize) {
+    const memoizer = new PassThrough().on('collect', data => {
+      memoData = data
+    })
+    pipeline.push(memoizer)
+  }
 
-	Events$4 = Events_1;
+  // contentStream is a write-only, not a passthrough
+  // no data comes out of it.
+  const contentStream = write.stream(cache, opts)
+    .on('integrity', (int) => {
+      integrity = int
+    })
+    .on('size', (s) => {
+      size = s
+    })
+    .on('error', (err) => {
+      error = err
+    })
 
-	States$1 = States_1;
+  pipeline.push(contentStream)
 
-	Sync$1 = Sync_1;
+  // last but not least, we write the index and emit hash and size,
+  // and memoize if we're doing that
+  pipeline.push(new Flush({
+    async flush () {
+      if (!error) {
+        const entry = await index.insert(cache, key, integrity, { ...opts, size })
+        if (memoize && memoData) {
+          memo.put(cache, entry, memoData, opts)
+        }
+        pipeline.emit('integrity', integrity)
+        pipeline.emit('size', size)
+      }
+    },
+  }))
 
-	Bottleneck = (function() {
-	  class Bottleneck {
-	    constructor(options = {}, ...invalid) {
-	      var storeInstanceOptions, storeOptions;
-	      this._addToQueue = this._addToQueue.bind(this);
-	      this._validateOptions(options, invalid);
-	      parser$5.load(options, this.instanceDefaults, this);
-	      this._queues = new Queues$1(NUM_PRIORITIES$1);
-	      this._scheduled = {};
-	      this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
-	      this._limiter = null;
-	      this.Events = new Events$4(this);
-	      this._submitLock = new Sync$1("submit", this.Promise);
-	      this._registerLock = new Sync$1("register", this.Promise);
-	      storeOptions = parser$5.load(options, this.storeDefaults, {});
-	      this._store = (function() {
-	        if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) {
-	          storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {});
-	          return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);
-	        } else if (this.datastore === "local") {
-	          storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {});
-	          return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);
-	        } else {
-	          throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);
-	        }
-	      }).call(this);
-	      this._queues.on("leftzero", () => {
-	        var ref;
-	        return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0;
-	      });
-	      this._queues.on("zero", () => {
-	        var ref;
-	        return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0;
-	      });
-	    }
+  return pipeline
+}
+
+
+/***/ }),
 
-	    _validateOptions(options, invalid) {
-	      if (!((options != null) && typeof options === "object" && invalid.length === 0)) {
-	        throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.");
-	      }
-	    }
+/***/ 30793:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	    ready() {
-	      return this._store.ready;
-	    }
+"use strict";
 
-	    clients() {
-	      return this._store.clients;
-	    }
 
-	    channel() {
-	      return `b_${this.id}`;
-	    }
+const { rm } = __nccwpck_require__(91943)
+const glob = __nccwpck_require__(6337)
+const index = __nccwpck_require__(26575)
+const memo = __nccwpck_require__(56068)
+const path = __nccwpck_require__(16928)
+const rmContent = __nccwpck_require__(92447)
 
-	    channel_client() {
-	      return `b_${this.id}_${this._store.clientId}`;
-	    }
+module.exports = entry
+module.exports.entry = entry
 
-	    publish(message) {
-	      return this._store.__publish__(message);
-	    }
+function entry (cache, key, opts) {
+  memo.clearMemoized()
+  return index.delete(cache, key, opts)
+}
 
-	    disconnect(flush = true) {
-	      return this._store.__disconnect__(flush);
-	    }
+module.exports.content = content
 
-	    chain(_limiter) {
-	      this._limiter = _limiter;
-	      return this;
-	    }
+function content (cache, integrity) {
+  memo.clearMemoized()
+  return rmContent(cache, integrity)
+}
 
-	    queued(priority) {
-	      return this._queues.queued(priority);
-	    }
+module.exports.all = all
 
-	    clusterQueued() {
-	      return this._store.__queued__();
-	    }
+async function all (cache) {
+  memo.clearMemoized()
+  const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true })
+  return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true })))
+}
 
-	    empty() {
-	      return this.queued() === 0 && this._submitLock.isEmpty();
-	    }
 
-	    running() {
-	      return this._store.__running__();
-	    }
+/***/ }),
 
-	    done() {
-	      return this._store.__done__();
-	    }
+/***/ 6337:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	    jobStatus(id) {
-	      return this._states.jobStatus(id);
-	    }
+"use strict";
 
-	    jobs(status) {
-	      return this._states.statusJobs(status);
-	    }
 
-	    counts() {
-	      return this._states.statusCounts();
-	    }
+const { glob } = __nccwpck_require__(67471)
+const path = __nccwpck_require__(16928)
 
-	    _randomIndex() {
-	      return Math.random().toString(36).slice(2);
-	    }
+const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep)
+module.exports = (path, options) => glob(globify(path), options)
 
-	    check(weight = 1) {
-	      return this._store.__check__(weight);
-	    }
 
-	    _clearGlobalState(index) {
-	      if (this._scheduled[index] != null) {
-	        clearTimeout(this._scheduled[index].expiration);
-	        delete this._scheduled[index];
-	        return true;
-	      } else {
-	        return false;
-	      }
-	    }
+/***/ }),
 
-	    async _free(index, job, options, eventInfo) {
-	      var e, running;
-	      try {
-	        ({running} = (await this._store.__free__(index, options.weight)));
-	        this.Events.trigger("debug", `Freed ${options.id}`, eventInfo);
-	        if (running === 0 && this.empty()) {
-	          return this.Events.trigger("idle");
-	        }
-	      } catch (error1) {
-	        e = error1;
-	        return this.Events.trigger("error", e);
-	      }
-	    }
+/***/ 99704:
+/***/ ((module) => {
 
-	    _run(index, job, wait) {
-	      var clearGlobalState, free, run;
-	      job.doRun();
-	      clearGlobalState = this._clearGlobalState.bind(this, index);
-	      run = this._run.bind(this, index, job);
-	      free = this._free.bind(this, index, job);
-	      return this._scheduled[index] = {
-	        timeout: setTimeout(() => {
-	          return job.doExecute(this._limiter, clearGlobalState, run, free);
-	        }, wait),
-	        expiration: job.options.expiration != null ? setTimeout(function() {
-	          return job.doExpire(clearGlobalState, run, free);
-	        }, wait + job.options.expiration) : void 0,
-	        job: job
-	      };
-	    }
+"use strict";
 
-	    _drainOne(capacity) {
-	      return this._registerLock.schedule(() => {
-	        var args, index, next, options, queue;
-	        if (this.queued() === 0) {
-	          return this.Promise.resolve(null);
-	        }
-	        queue = this._queues.getFirst();
-	        ({options, args} = next = queue.first());
-	        if ((capacity != null) && options.weight > capacity) {
-	          return this.Promise.resolve(null);
-	        }
-	        this.Events.trigger("debug", `Draining ${options.id}`, {args, options});
-	        index = this._randomIndex();
-	        return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => {
-	          var empty;
-	          this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options});
-	          if (success) {
-	            queue.shift();
-	            empty = this.empty();
-	            if (empty) {
-	              this.Events.trigger("empty");
-	            }
-	            if (reservoir === 0) {
-	              this.Events.trigger("depleted", empty);
-	            }
-	            this._run(index, next, wait);
-	            return this.Promise.resolve(options.weight);
-	          } else {
-	            return this.Promise.resolve(null);
-	          }
-	        });
-	      });
-	    }
 
-	    _drainAll(capacity, total = 0) {
-	      return this._drainOne(capacity).then((drained) => {
-	        var newCapacity;
-	        if (drained != null) {
-	          newCapacity = capacity != null ? capacity - drained : capacity;
-	          return this._drainAll(newCapacity, total + drained);
-	        } else {
-	          return this.Promise.resolve(total);
-	        }
-	      }).catch((e) => {
-	        return this.Events.trigger("error", e);
-	      });
-	    }
+module.exports = hashToSegments
 
-	    _dropAllQueued(message) {
-	      return this._queues.shiftAll(function(job) {
-	        return job.doDrop({message});
-	      });
-	    }
+function hashToSegments (hash) {
+  return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)]
+}
 
-	    stop(options = {}) {
-	      var done, waitForExecuting;
-	      options = parser$5.load(options, this.stopDefaults);
-	      waitForExecuting = (at) => {
-	        var finished;
-	        finished = () => {
-	          var counts;
-	          counts = this._states.counts;
-	          return (counts[0] + counts[1] + counts[2] + counts[3]) === at;
-	        };
-	        return new this.Promise((resolve, reject) => {
-	          if (finished()) {
-	            return resolve();
-	          } else {
-	            return this.on("done", () => {
-	              if (finished()) {
-	                this.removeAllListeners("done");
-	                return resolve();
-	              }
-	            });
-	          }
-	        });
-	      };
-	      done = options.dropWaitingJobs ? (this._run = function(index, next) {
-	        return next.doDrop({
-	          message: options.dropErrorMessage
-	        });
-	      }, this._drainOne = () => {
-	        return this.Promise.resolve(null);
-	      }, this._registerLock.schedule(() => {
-	        return this._submitLock.schedule(() => {
-	          var k, ref, v;
-	          ref = this._scheduled;
-	          for (k in ref) {
-	            v = ref[k];
-	            if (this.jobStatus(v.job.options.id) === "RUNNING") {
-	              clearTimeout(v.timeout);
-	              clearTimeout(v.expiration);
-	              v.job.doDrop({
-	                message: options.dropErrorMessage
-	              });
-	            }
-	          }
-	          this._dropAllQueued(options.dropErrorMessage);
-	          return waitForExecuting(0);
-	        });
-	      })) : this.schedule({
-	        priority: NUM_PRIORITIES$1 - 1,
-	        weight: 0
-	      }, () => {
-	        return waitForExecuting(1);
-	      });
-	      this._receive = function(job) {
-	        return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage));
-	      };
-	      this.stop = () => {
-	        return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
-	      };
-	      return done;
-	    }
 
-	    async _addToQueue(job) {
-	      var args, blocked, error, options, reachedHWM, shifted, strategy;
-	      ({args, options} = job);
-	      try {
-	        ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight)));
-	      } catch (error1) {
-	        error = error1;
-	        this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error});
-	        job.doDrop({error});
-	        return false;
-	      }
-	      if (blocked) {
-	        job.doDrop();
-	        return true;
-	      } else if (reachedHWM) {
-	        shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;
-	        if (shifted != null) {
-	          shifted.doDrop();
-	        }
-	        if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) {
-	          if (shifted == null) {
-	            job.doDrop();
-	          }
-	          return reachedHWM;
-	        }
-	      }
-	      job.doQueue(reachedHWM, blocked);
-	      this._queues.push(job);
-	      await this._drainAll();
-	      return reachedHWM;
-	    }
+/***/ }),
 
-	    _receive(job) {
-	      if (this._states.jobStatus(job.options.id) != null) {
-	        job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`));
-	        return false;
-	      } else {
-	        job.doReceive();
-	        return this._submitLock.schedule(this._addToQueue, job);
-	      }
-	    }
+/***/ 63990:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	    submit(...args) {
-	      var cb, fn, job, options, ref, ref1, task;
-	      if (typeof args[0] === "function") {
-	        ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1);
-	        options = parser$5.load({}, this.jobDefaults);
-	      } else {
-	        ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1);
-	        options = parser$5.load(options, this.jobDefaults);
-	      }
-	      task = (...args) => {
-	        return new this.Promise(function(resolve, reject) {
-	          return fn(...args, function(...args) {
-	            return (args[0] != null ? reject : resolve)(args);
-	          });
-	        });
-	      };
-	      job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
-	      job.promise.then(function(args) {
-	        return typeof cb === "function" ? cb(...args) : void 0;
-	      }).catch(function(args) {
-	        if (Array.isArray(args)) {
-	          return typeof cb === "function" ? cb(...args) : void 0;
-	        } else {
-	          return typeof cb === "function" ? cb(args) : void 0;
-	        }
-	      });
-	      return this._receive(job);
-	    }
+"use strict";
 
-	    schedule(...args) {
-	      var job, options, task;
-	      if (typeof args[0] === "function") {
-	        [task, ...args] = args;
-	        options = {};
-	      } else {
-	        [options, task, ...args] = args;
-	      }
-	      job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
-	      this._receive(job);
-	      return job.promise;
-	    }
 
-	    wrap(fn) {
-	      var schedule, wrapped;
-	      schedule = this.schedule.bind(this);
-	      wrapped = function(...args) {
-	        return schedule(fn.bind(this), ...args);
-	      };
-	      wrapped.withOptions = function(options, ...args) {
-	        return schedule(options, fn, ...args);
-	      };
-	      return wrapped;
-	    }
+const { withTempDir } = __nccwpck_require__(88437)
+const fs = __nccwpck_require__(91943)
+const path = __nccwpck_require__(16928)
 
-	    async updateSettings(options = {}) {
-	      await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults));
-	      parser$5.overwrite(options, this.instanceDefaults, this);
-	      return this;
-	    }
+module.exports.mkdir = mktmpdir
 
-	    currentReservoir() {
-	      return this._store.__currentReservoir__();
-	    }
+async function mktmpdir (cache, opts = {}) {
+  const { tmpPrefix } = opts
+  const tmpDir = path.join(cache, 'tmp')
+  await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' })
+  // do not use path.join(), it drops the trailing / if tmpPrefix is unset
+  const target = `${tmpDir}${path.sep}${tmpPrefix || ''}`
+  return fs.mkdtemp(target, { owner: 'inherit' })
+}
 
-	    incrementReservoir(incr = 0) {
-	      return this._store.__incrementReservoir__(incr);
-	    }
+module.exports.withTmp = withTmp
 
-	  }
-	  Bottleneck.default = Bottleneck;
+function withTmp (cache, opts, cb) {
+  if (!cb) {
+    cb = opts
+    opts = {}
+  }
+  return withTempDir(path.join(cache, 'tmp'), cb, opts)
+}
 
-	  Bottleneck.Events = Events$4;
 
-	  Bottleneck.version = Bottleneck.prototype.version = require$$8.version;
+/***/ }),
 
-	  Bottleneck.strategy = Bottleneck.prototype.strategy = {
-	    LEAK: 1,
-	    OVERFLOW: 2,
-	    OVERFLOW_PRIORITY: 4,
-	    BLOCK: 3
-	  };
+/***/ 37621:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-	  Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;
+"use strict";
 
-	  Bottleneck.Group = Bottleneck.prototype.Group = Group_1;
 
-	  Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2;
+const {
+  mkdir,
+  readFile,
+  rm,
+  stat,
+  truncate,
+  writeFile,
+} = __nccwpck_require__(91943)
+const contentPath = __nccwpck_require__(40233)
+const fsm = __nccwpck_require__(25032)
+const glob = __nccwpck_require__(6337)
+const index = __nccwpck_require__(26575)
+const path = __nccwpck_require__(16928)
+const ssri = __nccwpck_require__(68951)
 
-	  Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3;
+const hasOwnProperty = (obj, key) =>
+  Object.prototype.hasOwnProperty.call(obj, key)
 
-	  Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;
+const verifyOpts = (opts) => ({
+  concurrency: 20,
+  log: { silly () {} },
+  ...opts,
+})
 
-	  Bottleneck.prototype.jobDefaults = {
-	    priority: DEFAULT_PRIORITY$1,
-	    weight: 1,
-	    expiration: null,
-	    id: ""
-	  };
+module.exports = verify
 
-	  Bottleneck.prototype.storeDefaults = {
-	    maxConcurrent: null,
-	    minTime: 0,
-	    highWater: null,
-	    strategy: Bottleneck.prototype.strategy.LEAK,
-	    penalty: null,
-	    reservoir: null,
-	    reservoirRefreshInterval: null,
-	    reservoirRefreshAmount: null,
-	    reservoirIncreaseInterval: null,
-	    reservoirIncreaseAmount: null,
-	    reservoirIncreaseMaximum: null
-	  };
+async function verify (cache, opts) {
+  opts = verifyOpts(opts)
+  opts.log.silly('verify', 'verifying cache at', cache)
 
-	  Bottleneck.prototype.localStoreDefaults = {
-	    Promise: Promise,
-	    timeout: null,
-	    heartbeatInterval: 250
-	  };
+  const steps = [
+    markStartTime,
+    fixPerms,
+    garbageCollect,
+    rebuildIndex,
+    cleanTmp,
+    writeVerifile,
+    markEndTime,
+  ]
+
+  const stats = {}
+  for (const step of steps) {
+    const label = step.name
+    const start = new Date()
+    const s = await step(cache, opts)
+    if (s) {
+      Object.keys(s).forEach((k) => {
+        stats[k] = s[k]
+      })
+    }
+    const end = new Date()
+    if (!stats.runTime) {
+      stats.runTime = {}
+    }
+    stats.runTime[label] = end - start
+  }
+  stats.runTime.total = stats.endTime - stats.startTime
+  opts.log.silly(
+    'verify',
+    'verification finished for',
+    cache,
+    'in',
+    `${stats.runTime.total}ms`
+  )
+  return stats
+}
+
+async function markStartTime () {
+  return { startTime: new Date() }
+}
+
+async function markEndTime () {
+  return { endTime: new Date() }
+}
+
+async function fixPerms (cache, opts) {
+  opts.log.silly('verify', 'fixing cache permissions')
+  await mkdir(cache, { recursive: true })
+  return null
+}
+
+// Implements a naive mark-and-sweep tracing garbage collector.
+//
+// The algorithm is basically as follows:
+// 1. Read (and filter) all index entries ("pointers")
+// 2. Mark each integrity value as "live"
+// 3. Read entire filesystem tree in `content-vX/` dir
+// 4. If content is live, verify its checksum and delete it if it fails
+// 5. If content is not marked as live, rm it.
+//
+async function garbageCollect (cache, opts) {
+  opts.log.silly('verify', 'garbage collecting content')
+  const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606))
+  const indexStream = index.lsStream(cache)
+  const liveContent = new Set()
+  indexStream.on('data', (entry) => {
+    if (opts.filter && !opts.filter(entry)) {
+      return
+    }
 
-	  Bottleneck.prototype.redisStoreDefaults = {
-	    Promise: Promise,
-	    timeout: null,
-	    heartbeatInterval: 5000,
-	    clientTimeout: 10000,
-	    Redis: null,
-	    clientOptions: {},
-	    clusterNodes: null,
-	    clearDatastore: false,
-	    connection: null
-	  };
+    // integrity is stringified, re-parse it so we can get each hash
+    const integrity = ssri.parse(entry.integrity)
+    for (const algo in integrity) {
+      liveContent.add(integrity[algo].toString())
+    }
+  })
+  await new Promise((resolve, reject) => {
+    indexStream.on('end', resolve).on('error', reject)
+  })
+  const contentDir = contentPath.contentDir(cache)
+  const files = await glob(path.join(contentDir, '**'), {
+    follow: false,
+    nodir: true,
+    nosort: true,
+  })
+  const stats = {
+    verifiedContent: 0,
+    reclaimedCount: 0,
+    reclaimedSize: 0,
+    badContentCount: 0,
+    keptSize: 0,
+  }
+  await pMap(
+    files,
+    async (f) => {
+      const split = f.split(/[/\\]/)
+      const digest = split.slice(split.length - 3).join('')
+      const algo = split[split.length - 4]
+      const integrity = ssri.fromHex(digest, algo)
+      if (liveContent.has(integrity.toString())) {
+        const info = await verifyContent(f, integrity)
+        if (!info.valid) {
+          stats.reclaimedCount++
+          stats.badContentCount++
+          stats.reclaimedSize += info.size
+        } else {
+          stats.verifiedContent++
+          stats.keptSize += info.size
+        }
+      } else {
+        // No entries refer to this content. We can delete.
+        stats.reclaimedCount++
+        const s = await stat(f)
+        await rm(f, { recursive: true, force: true })
+        stats.reclaimedSize += s.size
+      }
+      return stats
+    },
+    { concurrency: opts.concurrency }
+  )
+  return stats
+}
 
-	  Bottleneck.prototype.instanceDefaults = {
-	    datastore: "local",
-	    connection: null,
-	    id: "",
-	    rejectOnDrop: true,
-	    trackDoneStatus: false,
-	    Promise: Promise
-	  };
+async function verifyContent (filepath, sri) {
+  const contentInfo = {}
+  try {
+    const { size } = await stat(filepath)
+    contentInfo.size = size
+    contentInfo.valid = true
+    await ssri.checkStream(new fsm.ReadStream(filepath), sri)
+  } catch (err) {
+    if (err.code === 'ENOENT') {
+      return { size: 0, valid: false }
+    }
+    if (err.code !== 'EINTEGRITY') {
+      throw err
+    }
 
-	  Bottleneck.prototype.stopDefaults = {
-	    enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
-	    dropWaitingJobs: true,
-	    dropErrorMessage: "This limiter has been stopped."
-	  };
+    await rm(filepath, { recursive: true, force: true })
+    contentInfo.valid = false
+  }
+  return contentInfo
+}
 
-	  return Bottleneck;
+async function rebuildIndex (cache, opts) {
+  opts.log.silly('verify', 'rebuilding index')
+  const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606))
+  const entries = await index.ls(cache)
+  const stats = {
+    missingContent: 0,
+    rejectedEntries: 0,
+    totalEntries: 0,
+  }
+  const buckets = {}
+  for (const k in entries) {
+    /* istanbul ignore else */
+    if (hasOwnProperty(entries, k)) {
+      const hashed = index.hashKey(k)
+      const entry = entries[k]
+      const excluded = opts.filter && !opts.filter(entry)
+      excluded && stats.rejectedEntries++
+      if (buckets[hashed] && !excluded) {
+        buckets[hashed].push(entry)
+      } else if (buckets[hashed] && excluded) {
+        // skip
+      } else if (excluded) {
+        buckets[hashed] = []
+        buckets[hashed]._path = index.bucketPath(cache, k)
+      } else {
+        buckets[hashed] = [entry]
+        buckets[hashed]._path = index.bucketPath(cache, k)
+      }
+    }
+  }
+  await pMap(
+    Object.keys(buckets),
+    (key) => {
+      return rebuildBucket(cache, buckets[key], stats, opts)
+    },
+    { concurrency: opts.concurrency }
+  )
+  return stats
+}
 
-	}).call(commonjsGlobal);
+async function rebuildBucket (cache, bucket, stats) {
+  await truncate(bucket._path)
+  // This needs to be serialized because cacache explicitly
+  // lets very racy bucket conflicts clobber each other.
+  for (const entry of bucket) {
+    const content = contentPath(cache, entry.integrity)
+    try {
+      await stat(content)
+      await index.insert(cache, entry.key, entry.integrity, {
+        metadata: entry.metadata,
+        size: entry.size,
+        time: entry.time,
+      })
+      stats.totalEntries++
+    } catch (err) {
+      if (err.code === 'ENOENT') {
+        stats.rejectedEntries++
+        stats.missingContent++
+      } else {
+        throw err
+      }
+    }
+  }
+}
 
-	var Bottleneck_1 = Bottleneck;
+function cleanTmp (cache, opts) {
+  opts.log.silly('verify', 'cleaning tmp directory')
+  return rm(path.join(cache, 'tmp'), { recursive: true, force: true })
+}
 
-	var lib = Bottleneck_1;
+async function writeVerifile (cache, opts) {
+  const verifile = path.join(cache, '_lastverified')
+  opts.log.silly('verify', 'writing verifile to ' + verifile)
+  return writeFile(verifile, `${Date.now()}`)
+}
 
-	return lib;
+module.exports.lastRun = lastRun
 
-})));
+async function lastRun (cache) {
+  const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' })
+  return new Date(+data)
+}
 
 
 /***/ }),
 
-/***/ 94691:
+/***/ 45177:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-var concatMap = __nccwpck_require__(97087);
 var balanced = __nccwpck_require__(59380);
 
 module.exports = expandTop;
@@ -21410,10 +20616,6 @@ function expandTop(str) {
   return expand(escapeBraces(str), true).map(unescapeBraces);
 }
 
-function identity(e) {
-  return e;
-}
-
 function embrace(str) {
   return '{' + str + '}';
 }
@@ -21432,42 +20634,7 @@ function expand(str, isTop) {
   var expansions = [];
 
   var m = balanced('{', '}', str);
-  if (!m || /\$$/.test(m.pre)) return [str];
-
-  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
-  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
-  var isSequence = isNumericSequence || isAlphaSequence;
-  var isOptions = m.body.indexOf(',') >= 0;
-  if (!isSequence && !isOptions) {
-    // {a},b}
-    if (m.post.match(/,.*\}/)) {
-      str = m.pre + '{' + m.body + escClose + m.post;
-      return expand(str);
-    }
-    return [str];
-  }
-
-  var n;
-  if (isSequence) {
-    n = m.body.split(/\.\./);
-  } else {
-    n = parseCommaParts(m.body);
-    if (n.length === 1) {
-      // x{{a,b}}y ==> x{a}y x{b}y
-      n = expand(n[0], false).map(embrace);
-      if (n.length === 1) {
-        var post = m.post.length
-          ? expand(m.post, false)
-          : [''];
-        return post.map(function(p) {
-          return m.pre + n[0] + p;
-        });
-      }
-    }
-  }
-
-  // at this point, n is the parts, and we know it's not a comma set
-  // with a single entry.
+  if (!m) return [str];
 
   // no need to expand pre, since it is guaranteed to be free of brace-sets
   var pre = m.pre;
@@ -21475,55 +20642,97 @@ function expand(str, isTop) {
     ? expand(m.post, false)
     : [''];
 
-  var N;
+  if (/\$$/.test(m.pre)) {    
+    for (var k = 0; k < post.length; k++) {
+      var expansion = pre+ '{' + m.body + '}' + post[k];
+      expansions.push(expansion);
+    }
+  } else {
+    var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+    var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+    var isSequence = isNumericSequence || isAlphaSequence;
+    var isOptions = m.body.indexOf(',') >= 0;
+    if (!isSequence && !isOptions) {
+      // {a},b}
+      if (m.post.match(/,.*\}/)) {
+        str = m.pre + '{' + m.body + escClose + m.post;
+        return expand(str);
+      }
+      return [str];
+    }
 
-  if (isSequence) {
-    var x = numeric(n[0]);
-    var y = numeric(n[1]);
-    var width = Math.max(n[0].length, n[1].length)
-    var incr = n.length == 3
-      ? Math.abs(numeric(n[2]))
-      : 1;
-    var test = lte;
-    var reverse = y < x;
-    if (reverse) {
-      incr *= -1;
-      test = gte;
+    var n;
+    if (isSequence) {
+      n = m.body.split(/\.\./);
+    } else {
+      n = parseCommaParts(m.body);
+      if (n.length === 1) {
+        // x{{a,b}}y ==> x{a}y x{b}y
+        n = expand(n[0], false).map(embrace);
+        if (n.length === 1) {
+          return post.map(function(p) {
+            return m.pre + n[0] + p;
+          });
+        }
+      }
     }
-    var pad = n.some(isPadded);
 
-    N = [];
+    // at this point, n is the parts, and we know it's not a comma set
+    // with a single entry.
+    var N;
 
-    for (var i = x; test(i, y); i += incr) {
-      var c;
-      if (isAlphaSequence) {
-        c = String.fromCharCode(i);
-        if (c === '\\')
-          c = '';
-      } else {
-        c = String(i);
-        if (pad) {
-          var need = width - c.length;
-          if (need > 0) {
-            var z = new Array(need + 1).join('0');
-            if (i < 0)
-              c = '-' + z + c.slice(1);
-            else
-              c = z + c;
+    if (isSequence) {
+      var x = numeric(n[0]);
+      var y = numeric(n[1]);
+      var width = Math.max(n[0].length, n[1].length)
+      var incr = n.length == 3
+        ? Math.abs(numeric(n[2]))
+        : 1;
+      var test = lte;
+      var reverse = y < x;
+      if (reverse) {
+        incr *= -1;
+        test = gte;
+      }
+      var pad = n.some(isPadded);
+
+      N = [];
+
+      for (var i = x; test(i, y); i += incr) {
+        var c;
+        if (isAlphaSequence) {
+          c = String.fromCharCode(i);
+          if (c === '\\')
+            c = '';
+        } else {
+          c = String(i);
+          if (pad) {
+            var need = width - c.length;
+            if (need > 0) {
+              var z = new Array(need + 1).join('0');
+              if (i < 0)
+                c = '-' + z + c.slice(1);
+              else
+                c = z + c;
+            }
           }
         }
+        N.push(c);
+      }
+    } else {
+      N = [];
+
+      for (var j = 0; j < n.length; j++) {
+        N.push.apply(N, expand(n[j], false));
       }
-      N.push(c);
     }
-  } else {
-    N = concatMap(n, function(el) { return expand(el, false) });
-  }
 
-  for (var j = 0; j < N.length; j++) {
-    for (var k = 0; k < post.length; k++) {
-      var expansion = pre + N[j] + post[k];
-      if (!isTop || isSequence || expansion)
-        expansions.push(expansion);
+    for (var j = 0; j < N.length; j++) {
+      for (var k = 0; k < post.length; k++) {
+        var expansion = pre + N[j] + post[k];
+        if (!isTop || isSequence || expansion)
+          expansions.push(expansion);
+      }
     }
   }
 
@@ -21534,22957 +20743,23986 @@ function expand(str, isTop) {
 
 /***/ }),
 
-/***/ 40233:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 97087:
+/***/ ((module) => {
 
-"use strict";
+module.exports = function (xs, fn) {
+    var res = [];
+    for (var i = 0; i < xs.length; i++) {
+        var x = fn(xs[i], i);
+        if (isArray(x)) res.push.apply(res, x);
+        else res.push(x);
+    }
+    return res;
+};
 
+var isArray = Array.isArray || function (xs) {
+    return Object.prototype.toString.call(xs) === '[object Array]';
+};
 
-const contentVer = (__nccwpck_require__(4038)/* ["cache-version"].content */ .MH.Q)
-const hashToSegments = __nccwpck_require__(99704)
-const path = __nccwpck_require__(16928)
-const ssri = __nccwpck_require__(68951)
 
-// Current format of content file path:
-//
-// sha512-BaSE64Hex= ->
-// ~/.my-cache/content-v2/sha512/ba/da/55deadbeefc0ffee
-//
-module.exports = contentPath
+/***/ }),
 
-function contentPath (cache, integrity) {
-  const sri = ssri.parse(integrity, { single: true })
-  // contentPath is the *strongest* algo given
-  return path.join(
-    contentDir(cache),
-    sri.algorithm,
-    ...hashToSegments(sri.hexDigest())
-  )
+/***/ 6110:
+/***/ ((module, exports, __nccwpck_require__) => {
+
+/* eslint-env browser */
+
+/**
+ * This is the web browser implementation of `debug()`.
+ */
+
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.storage = localstorage();
+exports.destroy = (() => {
+	let warned = false;
+
+	return () => {
+		if (!warned) {
+			warned = true;
+			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+		}
+	};
+})();
+
+/**
+ * Colors.
+ */
+
+exports.colors = [
+	'#0000CC',
+	'#0000FF',
+	'#0033CC',
+	'#0033FF',
+	'#0066CC',
+	'#0066FF',
+	'#0099CC',
+	'#0099FF',
+	'#00CC00',
+	'#00CC33',
+	'#00CC66',
+	'#00CC99',
+	'#00CCCC',
+	'#00CCFF',
+	'#3300CC',
+	'#3300FF',
+	'#3333CC',
+	'#3333FF',
+	'#3366CC',
+	'#3366FF',
+	'#3399CC',
+	'#3399FF',
+	'#33CC00',
+	'#33CC33',
+	'#33CC66',
+	'#33CC99',
+	'#33CCCC',
+	'#33CCFF',
+	'#6600CC',
+	'#6600FF',
+	'#6633CC',
+	'#6633FF',
+	'#66CC00',
+	'#66CC33',
+	'#9900CC',
+	'#9900FF',
+	'#9933CC',
+	'#9933FF',
+	'#99CC00',
+	'#99CC33',
+	'#CC0000',
+	'#CC0033',
+	'#CC0066',
+	'#CC0099',
+	'#CC00CC',
+	'#CC00FF',
+	'#CC3300',
+	'#CC3333',
+	'#CC3366',
+	'#CC3399',
+	'#CC33CC',
+	'#CC33FF',
+	'#CC6600',
+	'#CC6633',
+	'#CC9900',
+	'#CC9933',
+	'#CCCC00',
+	'#CCCC33',
+	'#FF0000',
+	'#FF0033',
+	'#FF0066',
+	'#FF0099',
+	'#FF00CC',
+	'#FF00FF',
+	'#FF3300',
+	'#FF3333',
+	'#FF3366',
+	'#FF3399',
+	'#FF33CC',
+	'#FF33FF',
+	'#FF6600',
+	'#FF6633',
+	'#FF9900',
+	'#FF9933',
+	'#FFCC00',
+	'#FFCC33'
+];
+
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+
+// eslint-disable-next-line complexity
+function useColors() {
+	// NB: In an Electron preload script, document will be defined but not fully
+	// initialized. Since we know we're in Chrome, we'll just detect this case
+	// explicitly
+	if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
+		return true;
+	}
+
+	// Internet Explorer and Edge do not support colors.
+	if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+		return false;
+	}
+
+	// Is webkit? http://stackoverflow.com/a/16459606/376773
+	// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+	return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
+		// Is firebug? http://stackoverflow.com/a/398120/376773
+		(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
+		// Is firefox >= v31?
+		// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
+		// Double check webkit in userAgent just in case we are in a worker
+		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
 }
 
-module.exports.contentDir = contentDir
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
 
-function contentDir (cache) {
-  return path.join(cache, `content-v${contentVer}`)
-}
+function formatArgs(args) {
+	args[0] = (this.useColors ? '%c' : '') +
+		this.namespace +
+		(this.useColors ? ' %c' : ' ') +
+		args[0] +
+		(this.useColors ? '%c ' : ' ') +
+		'+' + module.exports.humanize(this.diff);
 
+	if (!this.useColors) {
+		return;
+	}
 
-/***/ }),
+	const c = 'color: ' + this.color;
+	args.splice(1, 0, c, 'color: inherit');
 
-/***/ 39398:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+	// The final "%c" is somewhat tricky, because there could be other
+	// arguments passed either before or after the %c, so we need to
+	// figure out the correct index to insert the CSS into
+	let index = 0;
+	let lastC = 0;
+	args[0].replace(/%[a-zA-Z%]/g, match => {
+		if (match === '%%') {
+			return;
+		}
+		index++;
+		if (match === '%c') {
+			// We only are interested in the *last* %c
+			// (the user may have provided their own)
+			lastC = index;
+		}
+	});
 
-"use strict";
+	args.splice(lastC, 0, c);
+}
 
+/**
+ * Invokes `console.debug()` when available.
+ * No-op when `console.debug` is not a "function".
+ * If `console.debug` is not available, falls back
+ * to `console.log`.
+ *
+ * @api public
+ */
+exports.log = console.debug || console.log || (() => {});
 
-const fs = __nccwpck_require__(91943)
-const fsm = __nccwpck_require__(25032)
-const ssri = __nccwpck_require__(68951)
-const contentPath = __nccwpck_require__(40233)
-const Pipeline = __nccwpck_require__(52899)
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+	try {
+		if (namespaces) {
+			exports.storage.setItem('debug', namespaces);
+		} else {
+			exports.storage.removeItem('debug');
+		}
+	} catch (error) {
+		// Swallow
+		// XXX (@Qix-) should we be logging these?
+	}
+}
 
-module.exports = read
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+function load() {
+	let r;
+	try {
+		r = exports.storage.getItem('debug');
+	} catch (error) {
+		// Swallow
+		// XXX (@Qix-) should we be logging these?
+	}
 
-const MAX_SINGLE_READ_SIZE = 64 * 1024 * 1024
-async function read (cache, integrity, opts = {}) {
-  const { size } = opts
-  const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
-    // get size
-    const stat = size ? { size } : await fs.stat(cpath)
-    return { stat, cpath, sri }
-  })
+	// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+	if (!r && typeof process !== 'undefined' && 'env' in process) {
+		r = process.env.DEBUG;
+	}
 
-  if (stat.size > MAX_SINGLE_READ_SIZE) {
-    return readPipeline(cpath, stat.size, sri, new Pipeline()).concat()
-  }
+	return r;
+}
 
-  const data = await fs.readFile(cpath, { encoding: null })
+/**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
 
-  if (stat.size !== data.length) {
-    throw sizeError(stat.size, data.length)
-  }
+function localstorage() {
+	try {
+		// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
+		// The Browser also has localStorage in the global context.
+		return localStorage;
+	} catch (error) {
+		// Swallow
+		// XXX (@Qix-) should we be logging these?
+	}
+}
 
-  if (!ssri.checkData(data, sri)) {
-    throw integrityError(sri, cpath)
-  }
+module.exports = __nccwpck_require__(40897)(exports);
 
-  return data
-}
+const {formatters} = module.exports;
 
-const readPipeline = (cpath, size, sri, stream) => {
-  stream.push(
-    new fsm.ReadStream(cpath, {
-      size,
-      readSize: MAX_SINGLE_READ_SIZE,
-    }),
-    ssri.integrityStream({
-      integrity: sri,
-      size,
-    })
-  )
-  return stream
-}
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
 
-module.exports.stream = readStream
-module.exports.readStream = readStream
+formatters.j = function (v) {
+	try {
+		return JSON.stringify(v);
+	} catch (error) {
+		return '[UnexpectedJSONParseError]: ' + error.message;
+	}
+};
 
-function readStream (cache, integrity, opts = {}) {
-  const { size } = opts
-  const stream = new Pipeline()
-  // Set all this up to run on the stream and then just return the stream
-  Promise.resolve().then(async () => {
-    const { stat, cpath, sri } = await withContentSri(cache, integrity, async (cpath, sri) => {
-      // get size
-      const stat = size ? { size } : await fs.stat(cpath)
-      return { stat, cpath, sri }
-    })
 
-    return readPipeline(cpath, stat.size, sri, stream)
-  }).catch(err => stream.emit('error', err))
+/***/ }),
 
-  return stream
-}
+/***/ 40897:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-module.exports.copy = copy
 
-function copy (cache, integrity, dest) {
-  return withContentSri(cache, integrity, (cpath) => {
-    return fs.copyFile(cpath, dest)
-  })
-}
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ */
 
-module.exports.hasContent = hasContent
+function setup(env) {
+	createDebug.debug = createDebug;
+	createDebug.default = createDebug;
+	createDebug.coerce = coerce;
+	createDebug.disable = disable;
+	createDebug.enable = enable;
+	createDebug.enabled = enabled;
+	createDebug.humanize = __nccwpck_require__(70744);
+	createDebug.destroy = destroy;
 
-async function hasContent (cache, integrity) {
-  if (!integrity) {
-    return false
-  }
+	Object.keys(env).forEach(key => {
+		createDebug[key] = env[key];
+	});
 
-  try {
-    return await withContentSri(cache, integrity, async (cpath, sri) => {
-      const stat = await fs.stat(cpath)
-      return { size: stat.size, sri, stat }
-    })
-  } catch (err) {
-    if (err.code === 'ENOENT') {
-      return false
-    }
+	/**
+	* The currently active debug mode names, and names to skip.
+	*/
 
-    if (err.code === 'EPERM') {
-      /* istanbul ignore else */
-      if (process.platform !== 'win32') {
-        throw err
-      } else {
-        return false
-      }
-    }
-  }
-}
+	createDebug.names = [];
+	createDebug.skips = [];
 
-async function withContentSri (cache, integrity, fn) {
-  const sri = ssri.parse(integrity)
-  // If `integrity` has multiple entries, pick the first digest
-  // with available local data.
-  const algo = sri.pickAlgorithm()
-  const digests = sri[algo]
+	/**
+	* Map of special "%n" handling functions, for the debug "format" argument.
+	*
+	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+	*/
+	createDebug.formatters = {};
 
-  if (digests.length <= 1) {
-    const cpath = contentPath(cache, digests[0])
-    return fn(cpath, digests[0])
-  } else {
-    // Can't use race here because a generic error can happen before
-    // a ENOENT error, and can happen before a valid result
-    const results = await Promise.all(digests.map(async (meta) => {
-      try {
-        return await withContentSri(cache, meta, fn)
-      } catch (err) {
-        if (err.code === 'ENOENT') {
-          return Object.assign(
-            new Error('No matching content found for ' + sri.toString()),
-            { code: 'ENOENT' }
-          )
-        }
-        return err
-      }
-    }))
-    // Return the first non error if it is found
-    const result = results.find((r) => !(r instanceof Error))
-    if (result) {
-      return result
-    }
+	/**
+	* Selects a color for a debug namespace
+	* @param {String} namespace The namespace string for the debug instance to be colored
+	* @return {Number|String} An ANSI color code for the given namespace
+	* @api private
+	*/
+	function selectColor(namespace) {
+		let hash = 0;
 
-    // Throw the No matching content found error
-    const enoentError = results.find((r) => r.code === 'ENOENT')
-    if (enoentError) {
-      throw enoentError
-    }
+		for (let i = 0; i < namespace.length; i++) {
+			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
+			hash |= 0; // Convert to 32bit integer
+		}
 
-    // Throw generic error
-    throw results.find((r) => r instanceof Error)
-  }
-}
+		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
+	}
+	createDebug.selectColor = selectColor;
 
-function sizeError (expected, found) {
-  /* eslint-disable-next-line max-len */
-  const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
-  err.expected = expected
-  err.found = found
-  err.code = 'EBADSIZE'
-  return err
-}
+	/**
+	* Create a debugger with the given `namespace`.
+	*
+	* @param {String} namespace
+	* @return {Function}
+	* @api public
+	*/
+	function createDebug(namespace) {
+		let prevTime;
+		let enableOverride = null;
+		let namespacesCache;
+		let enabledCache;
 
-function integrityError (sri, path) {
-  const err = new Error(`Integrity verification failed for ${sri} (${path})`)
-  err.code = 'EINTEGRITY'
-  err.sri = sri
-  err.path = path
-  return err
-}
+		function debug(...args) {
+			// Disabled?
+			if (!debug.enabled) {
+				return;
+			}
 
+			const self = debug;
 
-/***/ }),
+			// Set `diff` timestamp
+			const curr = Number(new Date());
+			const ms = curr - (prevTime || curr);
+			self.diff = ms;
+			self.prev = prevTime;
+			self.curr = curr;
+			prevTime = curr;
 
-/***/ 92447:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+			args[0] = createDebug.coerce(args[0]);
 
-"use strict";
+			if (typeof args[0] !== 'string') {
+				// Anything else let's inspect with %O
+				args.unshift('%O');
+			}
 
+			// Apply any `formatters` transformations
+			let index = 0;
+			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
+				// If we encounter an escaped % then don't increase the array index
+				if (match === '%%') {
+					return '%';
+				}
+				index++;
+				const formatter = createDebug.formatters[format];
+				if (typeof formatter === 'function') {
+					const val = args[index];
+					match = formatter.call(self, val);
 
-const fs = __nccwpck_require__(91943)
-const contentPath = __nccwpck_require__(40233)
-const { hasContent } = __nccwpck_require__(39398)
+					// Now we need to remove `args[index]` since it's inlined in the `format`
+					args.splice(index, 1);
+					index--;
+				}
+				return match;
+			});
 
-module.exports = rm
+			// Apply env-specific formatting (colors, etc.)
+			createDebug.formatArgs.call(self, args);
 
-async function rm (cache, integrity) {
-  const content = await hasContent(cache, integrity)
-  // ~pretty~ sure we can't end up with a content lacking sri, but be safe
-  if (content && content.sri) {
-    await fs.rm(contentPath(cache, content.sri), { recursive: true, force: true })
-    return true
-  } else {
-    return false
-  }
-}
+			const logFn = self.log || createDebug.log;
+			logFn.apply(self, args);
+		}
 
+		debug.namespace = namespace;
+		debug.useColors = createDebug.useColors();
+		debug.color = createDebug.selectColor(namespace);
+		debug.extend = extend;
+		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
 
-/***/ }),
+		Object.defineProperty(debug, 'enabled', {
+			enumerable: true,
+			configurable: false,
+			get: () => {
+				if (enableOverride !== null) {
+					return enableOverride;
+				}
+				if (namespacesCache !== createDebug.namespaces) {
+					namespacesCache = createDebug.namespaces;
+					enabledCache = createDebug.enabled(namespace);
+				}
 
-/***/ 93699:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+				return enabledCache;
+			},
+			set: v => {
+				enableOverride = v;
+			}
+		});
 
-"use strict";
+		// Env-specific initialization logic for debug instances
+		if (typeof createDebug.init === 'function') {
+			createDebug.init(debug);
+		}
 
+		return debug;
+	}
 
-const events = __nccwpck_require__(24434)
+	function extend(namespace, delimiter) {
+		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
+		newDebug.log = this.log;
+		return newDebug;
+	}
 
-const contentPath = __nccwpck_require__(40233)
-const fs = __nccwpck_require__(91943)
-const { moveFile } = __nccwpck_require__(88437)
-const { Minipass } = __nccwpck_require__(78275)
-const Pipeline = __nccwpck_require__(52899)
-const Flush = __nccwpck_require__(37633)
-const path = __nccwpck_require__(16928)
-const ssri = __nccwpck_require__(68951)
-const uniqueFilename = __nccwpck_require__(46019)
-const fsm = __nccwpck_require__(25032)
+	/**
+	* Enables a debug mode by namespaces. This can include modes
+	* separated by a colon and wildcards.
+	*
+	* @param {String} namespaces
+	* @api public
+	*/
+	function enable(namespaces) {
+		createDebug.save(namespaces);
+		createDebug.namespaces = namespaces;
 
-module.exports = write
+		createDebug.names = [];
+		createDebug.skips = [];
 
-// Cache of move operations in process so we don't duplicate
-const moveOperations = new Map()
+		let i;
+		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+		const len = split.length;
 
-async function write (cache, data, opts = {}) {
-  const { algorithms, size, integrity } = opts
+		for (i = 0; i < len; i++) {
+			if (!split[i]) {
+				// ignore empty strings
+				continue;
+			}
 
-  if (typeof size === 'number' && data.length !== size) {
-    throw sizeError(size, data.length)
-  }
+			namespaces = split[i].replace(/\*/g, '.*?');
 
-  const sri = ssri.fromData(data, algorithms ? { algorithms } : {})
-  if (integrity && !ssri.checkData(data, integrity, opts)) {
-    throw checksumError(integrity, sri)
-  }
+			if (namespaces[0] === '-') {
+				createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
+			} else {
+				createDebug.names.push(new RegExp('^' + namespaces + '$'));
+			}
+		}
+	}
 
-  for (const algo in sri) {
-    const tmp = await makeTmp(cache, opts)
-    const hash = sri[algo].toString()
-    try {
-      await fs.writeFile(tmp.target, data, { flag: 'wx' })
-      await moveToDestination(tmp, cache, hash, opts)
-    } finally {
-      if (!tmp.moved) {
-        await fs.rm(tmp.target, { recursive: true, force: true })
-      }
-    }
-  }
-  return { integrity: sri, size: data.length }
-}
+	/**
+	* Disable debug output.
+	*
+	* @return {String} namespaces
+	* @api public
+	*/
+	function disable() {
+		const namespaces = [
+			...createDebug.names.map(toNamespace),
+			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
+		].join(',');
+		createDebug.enable('');
+		return namespaces;
+	}
 
-module.exports.stream = writeStream
+	/**
+	* Returns true if the given mode name is enabled, false otherwise.
+	*
+	* @param {String} name
+	* @return {Boolean}
+	* @api public
+	*/
+	function enabled(name) {
+		if (name[name.length - 1] === '*') {
+			return true;
+		}
 
-// writes proxied to the 'inputStream' that is passed to the Promise
-// 'end' is deferred until content is handled.
-class CacacheWriteStream extends Flush {
-  constructor (cache, opts) {
-    super()
-    this.opts = opts
-    this.cache = cache
-    this.inputStream = new Minipass()
-    this.inputStream.on('error', er => this.emit('error', er))
-    this.inputStream.on('drain', () => this.emit('drain'))
-    this.handleContentP = null
-  }
+		let i;
+		let len;
 
-  write (chunk, encoding, cb) {
-    if (!this.handleContentP) {
-      this.handleContentP = handleContent(
-        this.inputStream,
-        this.cache,
-        this.opts
-      )
-      this.handleContentP.catch(error => this.emit('error', error))
-    }
-    return this.inputStream.write(chunk, encoding, cb)
-  }
+		for (i = 0, len = createDebug.skips.length; i < len; i++) {
+			if (createDebug.skips[i].test(name)) {
+				return false;
+			}
+		}
 
-  flush (cb) {
-    this.inputStream.end(() => {
-      if (!this.handleContentP) {
-        const e = new Error('Cache input stream was empty')
-        e.code = 'ENODATA'
-        // empty streams are probably emitting end right away.
-        // defer this one tick by rejecting a promise on it.
-        return Promise.reject(e).catch(cb)
-      }
-      // eslint-disable-next-line promise/catch-or-return
-      this.handleContentP.then(
-        (res) => {
-          res.integrity && this.emit('integrity', res.integrity)
-          // eslint-disable-next-line promise/always-return
-          res.size !== null && this.emit('size', res.size)
-          cb()
-        },
-        (er) => cb(er)
-      )
-    })
-  }
-}
+		for (i = 0, len = createDebug.names.length; i < len; i++) {
+			if (createDebug.names[i].test(name)) {
+				return true;
+			}
+		}
 
-function writeStream (cache, opts = {}) {
-  return new CacacheWriteStream(cache, opts)
-}
+		return false;
+	}
 
-async function handleContent (inputStream, cache, opts) {
-  const tmp = await makeTmp(cache, opts)
-  try {
-    const res = await pipeToTmp(inputStream, cache, tmp.target, opts)
-    await moveToDestination(
-      tmp,
-      cache,
-      res.integrity,
-      opts
-    )
-    return res
-  } finally {
-    if (!tmp.moved) {
-      await fs.rm(tmp.target, { recursive: true, force: true })
-    }
-  }
-}
+	/**
+	* Convert regexp to namespace
+	*
+	* @param {RegExp} regxep
+	* @return {String} namespace
+	* @api private
+	*/
+	function toNamespace(regexp) {
+		return regexp.toString()
+			.substring(2, regexp.toString().length - 2)
+			.replace(/\.\*\?$/, '*');
+	}
 
-async function pipeToTmp (inputStream, cache, tmpTarget, opts) {
-  const outStream = new fsm.WriteStream(tmpTarget, {
-    flags: 'wx',
-  })
+	/**
+	* Coerce `val`.
+	*
+	* @param {Mixed} val
+	* @return {Mixed}
+	* @api private
+	*/
+	function coerce(val) {
+		if (val instanceof Error) {
+			return val.stack || val.message;
+		}
+		return val;
+	}
 
-  if (opts.integrityEmitter) {
-    // we need to create these all simultaneously since they can fire in any order
-    const [integrity, size] = await Promise.all([
-      events.once(opts.integrityEmitter, 'integrity').then(res => res[0]),
-      events.once(opts.integrityEmitter, 'size').then(res => res[0]),
-      new Pipeline(inputStream, outStream).promise(),
-    ])
-    return { integrity, size }
-  }
+	/**
+	* XXX DO NOT USE. This is a temporary stub function.
+	* XXX It WILL be removed in the next major release.
+	*/
+	function destroy() {
+		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+	}
 
-  let integrity
-  let size
-  const hashStream = ssri.integrityStream({
-    integrity: opts.integrity,
-    algorithms: opts.algorithms,
-    size: opts.size,
-  })
-  hashStream.on('integrity', i => {
-    integrity = i
-  })
-  hashStream.on('size', s => {
-    size = s
-  })
+	createDebug.enable(createDebug.load());
 
-  const pipeline = new Pipeline(inputStream, hashStream, outStream)
-  await pipeline.promise()
-  return { integrity, size }
+	return createDebug;
 }
 
-async function makeTmp (cache, opts) {
-  const tmpTarget = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix)
-  await fs.mkdir(path.dirname(tmpTarget), { recursive: true })
-  return {
-    target: tmpTarget,
-    moved: false,
-  }
-}
+module.exports = setup;
 
-async function moveToDestination (tmp, cache, sri) {
-  const destination = contentPath(cache, sri)
-  const destDir = path.dirname(destination)
-  if (moveOperations.has(destination)) {
-    return moveOperations.get(destination)
-  }
-  moveOperations.set(
-    destination,
-    fs.mkdir(destDir, { recursive: true })
-      .then(async () => {
-        await moveFile(tmp.target, destination, { overwrite: false })
-        tmp.moved = true
-        return tmp.moved
-      })
-      .catch(err => {
-        if (!err.message.startsWith('The destination file exists')) {
-          throw Object.assign(err, { code: 'EEXIST' })
-        }
-      }).finally(() => {
-        moveOperations.delete(destination)
-      })
 
-  )
-  return moveOperations.get(destination)
-}
+/***/ }),
 
-function sizeError (expected, found) {
-  /* eslint-disable-next-line max-len */
-  const err = new Error(`Bad data size: expected inserted data to be ${expected} bytes, but got ${found} instead`)
-  err.expected = expected
-  err.found = found
-  err.code = 'EBADSIZE'
-  return err
-}
+/***/ 2830:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function checksumError (expected, found) {
-  const err = new Error(`Integrity check failed:
-  Wanted: ${expected}
-   Found: ${found}`)
-  err.code = 'EINTEGRITY'
-  err.expected = expected
-  err.found = found
-  return err
+/**
+ * Detect Electron renderer / nwjs process, which is node, but we should
+ * treat as a browser.
+ */
+
+if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
+	module.exports = __nccwpck_require__(6110);
+} else {
+	module.exports = __nccwpck_require__(95108);
 }
 
 
 /***/ }),
 
-/***/ 26575:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+/***/ 95108:
+/***/ ((module, exports, __nccwpck_require__) => {
 
+/**
+ * Module dependencies.
+ */
 
-const crypto = __nccwpck_require__(76982)
-const {
-  appendFile,
-  mkdir,
-  readFile,
-  readdir,
-  rm,
-  writeFile,
-} = __nccwpck_require__(91943)
-const { Minipass } = __nccwpck_require__(78275)
-const path = __nccwpck_require__(16928)
-const ssri = __nccwpck_require__(68951)
-const uniqueFilename = __nccwpck_require__(46019)
+const tty = __nccwpck_require__(52018);
+const util = __nccwpck_require__(39023);
 
-const contentPath = __nccwpck_require__(40233)
-const hashToSegments = __nccwpck_require__(99704)
-const indexV = (__nccwpck_require__(4038)/* ["cache-version"].index */ .MH.P)
-const { moveFile } = __nccwpck_require__(88437)
+/**
+ * This is the Node.js implementation of `debug()`.
+ */
 
-const lsStreamConcurrency = 5
+exports.init = init;
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.destroy = util.deprecate(
+	() => {},
+	'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
+);
 
-module.exports.NotFoundError = class NotFoundError extends Error {
-  constructor (cache, key) {
-    super(`No cache entry for ${key} found in ${cache}`)
-    this.code = 'ENOENT'
-    this.cache = cache
-    this.key = key
-  }
-}
+/**
+ * Colors.
+ */
 
-module.exports.compact = compact
+exports.colors = [6, 2, 3, 4, 5, 1];
 
-async function compact (cache, key, matchFn, opts = {}) {
-  const bucket = bucketPath(cache, key)
-  const entries = await bucketEntries(bucket)
-  const newEntries = []
-  // we loop backwards because the bottom-most result is the newest
-  // since we add new entries with appendFile
-  for (let i = entries.length - 1; i >= 0; --i) {
-    const entry = entries[i]
-    // a null integrity could mean either a delete was appended
-    // or the user has simply stored an index that does not map
-    // to any content. we determine if the user wants to keep the
-    // null integrity based on the validateEntry function passed in options.
-    // if the integrity is null and no validateEntry is provided, we break
-    // as we consider the null integrity to be a deletion of everything
-    // that came before it.
-    if (entry.integrity === null && !opts.validateEntry) {
-      break
-    }
+try {
+	// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
+	// eslint-disable-next-line import/no-extraneous-dependencies
+	const supportsColor = __nccwpck_require__(21450);
 
-    // if this entry is valid, and it is either the first entry or
-    // the newEntries array doesn't already include an entry that
-    // matches this one based on the provided matchFn, then we add
-    // it to the beginning of our list
-    if ((!opts.validateEntry || opts.validateEntry(entry) === true) &&
-      (newEntries.length === 0 ||
-        !newEntries.find((oldEntry) => matchFn(oldEntry, entry)))) {
-      newEntries.unshift(entry)
-    }
-  }
+	if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
+		exports.colors = [
+			20,
+			21,
+			26,
+			27,
+			32,
+			33,
+			38,
+			39,
+			40,
+			41,
+			42,
+			43,
+			44,
+			45,
+			56,
+			57,
+			62,
+			63,
+			68,
+			69,
+			74,
+			75,
+			76,
+			77,
+			78,
+			79,
+			80,
+			81,
+			92,
+			93,
+			98,
+			99,
+			112,
+			113,
+			128,
+			129,
+			134,
+			135,
+			148,
+			149,
+			160,
+			161,
+			162,
+			163,
+			164,
+			165,
+			166,
+			167,
+			168,
+			169,
+			170,
+			171,
+			172,
+			173,
+			178,
+			179,
+			184,
+			185,
+			196,
+			197,
+			198,
+			199,
+			200,
+			201,
+			202,
+			203,
+			204,
+			205,
+			206,
+			207,
+			208,
+			209,
+			214,
+			215,
+			220,
+			221
+		];
+	}
+} catch (error) {
+	// Swallow - we only care if `supports-color` is available; it doesn't have to be.
+}
 
-  const newIndex = '\n' + newEntries.map((entry) => {
-    const stringified = JSON.stringify(entry)
-    const hash = hashEntry(stringified)
-    return `${hash}\t${stringified}`
-  }).join('\n')
+/**
+ * Build up the default `inspectOpts` object from the environment variables.
+ *
+ *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
+ */
 
-  const setup = async () => {
-    const target = uniqueFilename(path.join(cache, 'tmp'), opts.tmpPrefix)
-    await mkdir(path.dirname(target), { recursive: true })
-    return {
-      target,
-      moved: false,
-    }
-  }
+exports.inspectOpts = Object.keys(process.env).filter(key => {
+	return /^debug_/i.test(key);
+}).reduce((obj, key) => {
+	// Camel-case
+	const prop = key
+		.substring(6)
+		.toLowerCase()
+		.replace(/_([a-z])/g, (_, k) => {
+			return k.toUpperCase();
+		});
 
-  const teardown = async (tmp) => {
-    if (!tmp.moved) {
-      return rm(tmp.target, { recursive: true, force: true })
-    }
-  }
+	// Coerce string value into JS value
+	let val = process.env[key];
+	if (/^(yes|on|true|enabled)$/i.test(val)) {
+		val = true;
+	} else if (/^(no|off|false|disabled)$/i.test(val)) {
+		val = false;
+	} else if (val === 'null') {
+		val = null;
+	} else {
+		val = Number(val);
+	}
 
-  const write = async (tmp) => {
-    await writeFile(tmp.target, newIndex, { flag: 'wx' })
-    await mkdir(path.dirname(bucket), { recursive: true })
-    // we use @npmcli/move-file directly here because we
-    // want to overwrite the existing file
-    await moveFile(tmp.target, bucket)
-    tmp.moved = true
-  }
+	obj[prop] = val;
+	return obj;
+}, {});
 
-  // write the file atomically
-  const tmp = await setup()
-  try {
-    await write(tmp)
-  } finally {
-    await teardown(tmp)
-  }
+/**
+ * Is stdout a TTY? Colored output is enabled when `true`.
+ */
 
-  // we reverse the list we generated such that the newest
-  // entries come first in order to make looping through them easier
-  // the true passed to formatEntry tells it to keep null
-  // integrity values, if they made it this far it's because
-  // validateEntry returned true, and as such we should return it
-  return newEntries.reverse().map((entry) => formatEntry(cache, entry, true))
+function useColors() {
+	return 'colors' in exports.inspectOpts ?
+		Boolean(exports.inspectOpts.colors) :
+		tty.isatty(process.stderr.fd);
 }
 
-module.exports.insert = insert
-
-async function insert (cache, key, integrity, opts = {}) {
-  const { metadata, size, time } = opts
-  const bucket = bucketPath(cache, key)
-  const entry = {
-    key,
-    integrity: integrity && ssri.stringify(integrity),
-    time: time || Date.now(),
-    size,
-    metadata,
-  }
-  try {
-    await mkdir(path.dirname(bucket), { recursive: true })
-    const stringified = JSON.stringify(entry)
-    // NOTE - Cleverness ahoy!
-    //
-    // This works because it's tremendously unlikely for an entry to corrupt
-    // another while still preserving the string length of the JSON in
-    // question. So, we just slap the length in there and verify it on read.
-    //
-    // Thanks to @isaacs for the whiteboarding session that ended up with
-    // this.
-    await appendFile(bucket, `\n${hashEntry(stringified)}\t${stringified}`)
-  } catch (err) {
-    if (err.code === 'ENOENT') {
-      return undefined
-    }
+/**
+ * Adds ANSI color escape codes if enabled.
+ *
+ * @api public
+ */
 
-    throw err
-  }
-  return formatEntry(cache, entry)
-}
+function formatArgs(args) {
+	const {namespace: name, useColors} = this;
 
-module.exports.find = find
+	if (useColors) {
+		const c = this.color;
+		const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
+		const prefix = `  ${colorCode};1m${name} \u001B[0m`;
 
-async function find (cache, key) {
-  const bucket = bucketPath(cache, key)
-  try {
-    const entries = await bucketEntries(bucket)
-    return entries.reduce((latest, next) => {
-      if (next && next.key === key) {
-        return formatEntry(cache, next)
-      } else {
-        return latest
-      }
-    }, null)
-  } catch (err) {
-    if (err.code === 'ENOENT') {
-      return null
-    } else {
-      throw err
-    }
-  }
+		args[0] = prefix + args[0].split('\n').join('\n' + prefix);
+		args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
+	} else {
+		args[0] = getDate() + name + ' ' + args[0];
+	}
 }
 
-module.exports["delete"] = del
+function getDate() {
+	if (exports.inspectOpts.hideDate) {
+		return '';
+	}
+	return new Date().toISOString() + ' ';
+}
 
-function del (cache, key, opts = {}) {
-  if (!opts.removeFully) {
-    return insert(cache, key, null, opts)
-  }
+/**
+ * Invokes `util.format()` with the specified arguments and writes to stderr.
+ */
 
-  const bucket = bucketPath(cache, key)
-  return rm(bucket, { recursive: true, force: true })
+function log(...args) {
+	return process.stderr.write(util.format(...args) + '\n');
 }
 
-module.exports.lsStream = lsStream
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+	if (namespaces) {
+		process.env.DEBUG = namespaces;
+	} else {
+		// If you set a process.env field to null or undefined, it gets cast to the
+		// string 'null' or 'undefined'. Just delete instead.
+		delete process.env.DEBUG;
+	}
+}
 
-function lsStream (cache) {
-  const indexDir = bucketDir(cache)
-  const stream = new Minipass({ objectMode: true })
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
 
-  // Set all this up to run on the stream and then just return the stream
-  Promise.resolve().then(async () => {
-    const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606))
-    const buckets = await readdirOrEmpty(indexDir)
-    await pMap(buckets, async (bucket) => {
-      const bucketPath = path.join(indexDir, bucket)
-      const subbuckets = await readdirOrEmpty(bucketPath)
-      await pMap(subbuckets, async (subbucket) => {
-        const subbucketPath = path.join(bucketPath, subbucket)
+function load() {
+	return process.env.DEBUG;
+}
 
-        // "/cachename//./*"
-        const subbucketEntries = await readdirOrEmpty(subbucketPath)
-        await pMap(subbucketEntries, async (entry) => {
-          const entryPath = path.join(subbucketPath, entry)
-          try {
-            const entries = await bucketEntries(entryPath)
-            // using a Map here prevents duplicate keys from showing up
-            // twice, I guess?
-            const reduced = entries.reduce((acc, entry) => {
-              acc.set(entry.key, entry)
-              return acc
-            }, new Map())
-            // reduced is a map of key => entry
-            for (const entry of reduced.values()) {
-              const formatted = formatEntry(cache, entry)
-              if (formatted) {
-                stream.write(formatted)
-              }
-            }
-          } catch (err) {
-            if (err.code === 'ENOENT') {
-              return undefined
-            }
-            throw err
-          }
-        },
-        { concurrency: lsStreamConcurrency })
-      },
-      { concurrency: lsStreamConcurrency })
-    },
-    { concurrency: lsStreamConcurrency })
-    stream.end()
-    return stream
-  }).catch(err => stream.emit('error', err))
+/**
+ * Init logic for `debug` instances.
+ *
+ * Create a new `inspectOpts` object in case `useColors` is set
+ * differently for a particular `debug` instance.
+ */
 
-  return stream
+function init(debug) {
+	debug.inspectOpts = {};
+
+	const keys = Object.keys(exports.inspectOpts);
+	for (let i = 0; i < keys.length; i++) {
+		debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
+	}
 }
 
-module.exports.ls = ls
+module.exports = __nccwpck_require__(40897)(exports);
 
-async function ls (cache) {
-  const entries = await lsStream(cache).collect()
-  return entries.reduce((acc, xs) => {
-    acc[xs.key] = xs
-    return acc
-  }, {})
-}
+const {formatters} = module.exports;
 
-module.exports.bucketEntries = bucketEntries
+/**
+ * Map %o to `util.inspect()`, all on a single line.
+ */
 
-async function bucketEntries (bucket, filter) {
-  const data = await readFile(bucket, 'utf8')
-  return _bucketEntries(data, filter)
-}
+formatters.o = function (v) {
+	this.inspectOpts.colors = this.useColors;
+	return util.inspect(v, this.inspectOpts)
+		.split('\n')
+		.map(str => str.trim())
+		.join(' ');
+};
 
-function _bucketEntries (data) {
-  const entries = []
-  data.split('\n').forEach((entry) => {
-    if (!entry) {
-      return
-    }
+/**
+ * Map %O to `util.inspect()`, allowing multiple lines if needed.
+ */
 
-    const pieces = entry.split('\t')
-    if (!pieces[1] || hashEntry(pieces[1]) !== pieces[0]) {
-      // Hash is no good! Corruption or malice? Doesn't matter!
-      // EJECT EJECT
-      return
-    }
-    let obj
-    try {
-      obj = JSON.parse(pieces[1])
-    } catch (_) {
-      // eslint-ignore-next-line no-empty-block
-    }
-    // coverage disabled here, no need to test with an entry that parses to something falsey
-    // istanbul ignore else
-    if (obj) {
-      entries.push(obj)
-    }
-  })
-  return entries
-}
+formatters.O = function (v) {
+	this.inspectOpts.colors = this.useColors;
+	return util.inspect(v, this.inspectOpts);
+};
 
-module.exports.bucketDir = bucketDir
 
-function bucketDir (cache) {
-  return path.join(cache, `index-v${indexV}`)
-}
+/***/ }),
 
-module.exports.bucketPath = bucketPath
+/***/ 14150:
+/***/ ((__unused_webpack_module, exports) => {
 
-function bucketPath (cache, key) {
-  const hashed = hashKey(key)
-  return path.join.apply(
-    path,
-    [bucketDir(cache)].concat(hashToSegments(hashed))
-  )
-}
+"use strict";
 
-module.exports.hashKey = hashKey
 
-function hashKey (key) {
-  return hash(key, 'sha256')
-}
+Object.defineProperty(exports, "__esModule", ({ value: true }));
 
-module.exports.hashEntry = hashEntry
+class Deprecation extends Error {
+  constructor(message) {
+    super(message); // Maintains proper stack trace (only available on V8)
 
-function hashEntry (str) {
-  return hash(str, 'sha1')
-}
+    /* istanbul ignore next */
 
-function hash (str, digest) {
-  return crypto
-    .createHash(digest)
-    .update(str)
-    .digest('hex')
-}
+    if (Error.captureStackTrace) {
+      Error.captureStackTrace(this, this.constructor);
+    }
 
-function formatEntry (cache, entry, keepAll) {
-  // Treat null digests as deletions. They'll shadow any previous entries.
-  if (!entry.integrity && !keepAll) {
-    return null
+    this.name = 'Deprecation';
   }
 
-  return {
-    key: entry.key,
-    integrity: entry.integrity,
-    path: entry.integrity ? contentPath(cache, entry.integrity) : undefined,
-    size: entry.size,
-    time: entry.time,
-    metadata: entry.metadata,
-  }
 }
 
-function readdirOrEmpty (dir) {
-  return readdir(dir).catch((err) => {
-    if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
-      return []
-    }
-
-    throw err
-  })
-}
+exports.Deprecation = Deprecation;
 
 
 /***/ }),
 
-/***/ 19690:
+/***/ 24056:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
 
-const Collect = __nccwpck_require__(11757)
-const { Minipass } = __nccwpck_require__(78275)
-const Pipeline = __nccwpck_require__(52899)
+var iconvLite = __nccwpck_require__(31748);
 
-const index = __nccwpck_require__(26575)
-const memo = __nccwpck_require__(56068)
-const read = __nccwpck_require__(39398)
+// Expose to the world
+module.exports.C = convert;
 
-async function getData (cache, key, opts = {}) {
-  const { integrity, memoize, size } = opts
-  const memoized = memo.get(cache, key, opts)
-  if (memoized && memoize !== false) {
-    return {
-      metadata: memoized.entry.metadata,
-      data: memoized.data,
-      integrity: memoized.entry.integrity,
-      size: memoized.entry.size,
+/**
+ * Convert encoding of an UTF-8 string or a buffer
+ *
+ * @param {String|Buffer} str String to be converted
+ * @param {String} to Encoding to be converted to
+ * @param {String} [from='UTF-8'] Encoding to be converted from
+ * @return {Buffer} Encoded string
+ */
+function convert(str, to, from) {
+    from = checkEncoding(from || 'UTF-8');
+    to = checkEncoding(to || 'UTF-8');
+    str = str || '';
+
+    var result;
+
+    if (from !== 'UTF-8' && typeof str === 'string') {
+        str = Buffer.from(str, 'binary');
     }
-  }
 
-  const entry = await index.find(cache, key, opts)
-  if (!entry) {
-    throw new index.NotFoundError(cache, key)
-  }
-  const data = await read(cache, entry.integrity, { integrity, size })
-  if (memoize) {
-    memo.put(cache, entry, data, opts)
-  }
+    if (from === to) {
+        if (typeof str === 'string') {
+            result = Buffer.from(str);
+        } else {
+            result = str;
+        }
+    } else {
+        try {
+            result = convertIconvLite(str, to, from);
+        } catch (E) {
+            console.error(E);
+            result = str;
+        }
+    }
 
-  return {
-    data,
-    metadata: entry.metadata,
-    size: entry.size,
-    integrity: entry.integrity,
-  }
-}
-module.exports = getData
+    if (typeof result === 'string') {
+        result = Buffer.from(result, 'utf-8');
+    }
 
-async function getDataByDigest (cache, key, opts = {}) {
-  const { integrity, memoize, size } = opts
-  const memoized = memo.get.byDigest(cache, key, opts)
-  if (memoized && memoize !== false) {
-    return memoized
-  }
+    return result;
+}
 
-  const res = await read(cache, key, { integrity, size })
-  if (memoize) {
-    memo.put.byDigest(cache, key, res, opts)
-  }
-  return res
+/**
+ * Convert encoding of astring with iconv-lite
+ *
+ * @param {String|Buffer} str String to be converted
+ * @param {String} to Encoding to be converted to
+ * @param {String} [from='UTF-8'] Encoding to be converted from
+ * @return {Buffer} Encoded string
+ */
+function convertIconvLite(str, to, from) {
+    if (to === 'UTF-8') {
+        return iconvLite.decode(str, from);
+    } else if (from === 'UTF-8') {
+        return iconvLite.encode(str, to);
+    } else {
+        return iconvLite.encode(iconvLite.decode(str, from), to);
+    }
 }
-module.exports.byDigest = getDataByDigest
 
-const getMemoizedStream = (memoized) => {
-  const stream = new Minipass()
-  stream.on('newListener', function (ev, cb) {
-    ev === 'metadata' && cb(memoized.entry.metadata)
-    ev === 'integrity' && cb(memoized.entry.integrity)
-    ev === 'size' && cb(memoized.entry.size)
-  })
-  stream.end(memoized.data)
-  return stream
+/**
+ * Converts charset name if needed
+ *
+ * @param {String} name Character set
+ * @return {String} Character set name
+ */
+function checkEncoding(name) {
+    return (name || '')
+        .toString()
+        .trim()
+        .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1')
+        .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1')
+        .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1')
+        .replace(/^ks_c_5601\-1987$/i, 'CP949')
+        .replace(/^us[\-_]?ascii$/i, 'ASCII')
+        .toUpperCase();
 }
 
-function getStream (cache, key, opts = {}) {
-  const { memoize, size } = opts
-  const memoized = memo.get(cache, key, opts)
-  if (memoized && memoize !== false) {
-    return getMemoizedStream(memoized)
-  }
 
-  const stream = new Pipeline()
-  // Set all this up to run on the stream and then just return the stream
-  Promise.resolve().then(async () => {
-    const entry = await index.find(cache, key)
-    if (!entry) {
-      throw new index.NotFoundError(cache, key)
-    }
+/***/ }),
 
-    stream.emit('metadata', entry.metadata)
-    stream.emit('integrity', entry.integrity)
-    stream.emit('size', entry.size)
-    stream.on('newListener', function (ev, cb) {
-      ev === 'metadata' && cb(entry.metadata)
-      ev === 'integrity' && cb(entry.integrity)
-      ev === 'size' && cb(entry.size)
-    })
+/***/ 14339:
+/***/ ((module) => {
 
-    const src = read.readStream(
-      cache,
-      entry.integrity,
-      { ...opts, size: typeof size !== 'number' ? entry.size : size }
-    )
+"use strict";
 
-    if (memoize) {
-      const memoStream = new Collect.PassThrough()
-      memoStream.on('collect', data => memo.put(cache, entry, data, opts))
-      stream.unshift(memoStream)
+
+function assign(obj, props) {
+    for (const key in props) {
+        Object.defineProperty(obj, key, {
+            value: props[key],
+            enumerable: true,
+            configurable: true,
+        });
     }
-    stream.unshift(src)
-    return stream
-  }).catch((err) => stream.emit('error', err))
 
-  return stream
+    return obj;
 }
 
-module.exports.stream = getStream
+function createError(err, code, props) {
+    if (!err || typeof err === 'string') {
+        throw new TypeError('Please pass an Error to err-code');
+    }
 
-function getStreamDigest (cache, integrity, opts = {}) {
-  const { memoize } = opts
-  const memoized = memo.get.byDigest(cache, integrity, opts)
-  if (memoized && memoize !== false) {
-    const stream = new Minipass()
-    stream.end(memoized)
-    return stream
-  } else {
-    const stream = read.readStream(cache, integrity, opts)
-    if (!memoize) {
-      return stream
+    if (!props) {
+        props = {};
     }
 
-    const memoStream = new Collect.PassThrough()
-    memoStream.on('collect', data => memo.put.byDigest(
-      cache,
-      integrity,
-      data,
-      opts
-    ))
-    return new Pipeline(stream, memoStream)
-  }
-}
+    if (typeof code === 'object') {
+        props = code;
+        code = undefined;
+    }
 
-module.exports.stream.byDigest = getStreamDigest
+    if (code != null) {
+        props.code = code;
+    }
 
-function info (cache, key, opts = {}) {
-  const { memoize } = opts
-  const memoized = memo.get(cache, key, opts)
-  if (memoized && memoize !== false) {
-    return Promise.resolve(memoized.entry)
-  } else {
-    return index.find(cache, key)
-  }
-}
-module.exports.info = info
+    try {
+        return assign(err, props);
+    } catch (_) {
+        props.message = err.message;
+        props.stack = err.stack;
 
-async function copy (cache, key, dest, opts = {}) {
-  const entry = await index.find(cache, key, opts)
-  if (!entry) {
-    throw new index.NotFoundError(cache, key)
-  }
-  await read.copy(cache, entry.integrity, dest, opts)
-  return {
-    metadata: entry.metadata,
-    size: entry.size,
-    integrity: entry.integrity,
-  }
-}
+        const ErrClass = function () {};
 
-module.exports.copy = copy
+        ErrClass.prototype = Object.create(Object.getPrototypeOf(err));
 
-async function copyByDigest (cache, key, dest, opts = {}) {
-  await read.copy(cache, key, dest, opts)
-  return key
+        return assign(new ErrClass(), props);
+    }
 }
 
-module.exports.copy.byDigest = copyByDigest
-
-module.exports.hasContent = read.hasContent
+module.exports = createError;
 
 
 /***/ }),
 
-/***/ 85742:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 25032:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+const { Minipass } = __nccwpck_require__(78275)
+const EE = (__nccwpck_require__(24434).EventEmitter)
+const fs = __nccwpck_require__(79896)
+
+const writev = fs.writev
+
+const _autoClose = Symbol('_autoClose')
+const _close = Symbol('_close')
+const _ended = Symbol('_ended')
+const _fd = Symbol('_fd')
+const _finished = Symbol('_finished')
+const _flags = Symbol('_flags')
+const _flush = Symbol('_flush')
+const _handleChunk = Symbol('_handleChunk')
+const _makeBuf = Symbol('_makeBuf')
+const _mode = Symbol('_mode')
+const _needDrain = Symbol('_needDrain')
+const _onerror = Symbol('_onerror')
+const _onopen = Symbol('_onopen')
+const _onread = Symbol('_onread')
+const _onwrite = Symbol('_onwrite')
+const _open = Symbol('_open')
+const _path = Symbol('_path')
+const _pos = Symbol('_pos')
+const _queue = Symbol('_queue')
+const _read = Symbol('_read')
+const _readSize = Symbol('_readSize')
+const _reading = Symbol('_reading')
+const _remain = Symbol('_remain')
+const _size = Symbol('_size')
+const _write = Symbol('_write')
+const _writing = Symbol('_writing')
+const _defaultFlag = Symbol('_defaultFlag')
+const _errored = Symbol('_errored')
+
+class ReadStream extends Minipass {
+  constructor (path, opt) {
+    opt = opt || {}
+    super(opt)
 
-"use strict";
+    this.readable = true
+    this.writable = false
 
+    if (typeof path !== 'string') {
+      throw new TypeError('path must be a string')
+    }
 
-const get = __nccwpck_require__(19690)
-const put = __nccwpck_require__(94283)
-const rm = __nccwpck_require__(30793)
-const verify = __nccwpck_require__(37621)
-const { clearMemoized } = __nccwpck_require__(56068)
-const tmp = __nccwpck_require__(63990)
-const index = __nccwpck_require__(26575)
+    this[_errored] = false
+    this[_fd] = typeof opt.fd === 'number' ? opt.fd : null
+    this[_path] = path
+    this[_readSize] = opt.readSize || 16 * 1024 * 1024
+    this[_reading] = false
+    this[_size] = typeof opt.size === 'number' ? opt.size : Infinity
+    this[_remain] = this[_size]
+    this[_autoClose] = typeof opt.autoClose === 'boolean' ?
+      opt.autoClose : true
 
-module.exports.index = {}
-module.exports.index.compact = index.compact
-module.exports.index.insert = index.insert
+    if (typeof this[_fd] === 'number') {
+      this[_read]()
+    } else {
+      this[_open]()
+    }
+  }
 
-module.exports.ls = index.ls
-module.exports.ls.stream = index.lsStream
+  get fd () {
+    return this[_fd]
+  }
 
-module.exports.get = get
-module.exports.get.byDigest = get.byDigest
-module.exports.get.stream = get.stream
-module.exports.get.stream.byDigest = get.stream.byDigest
-module.exports.get.copy = get.copy
-module.exports.get.copy.byDigest = get.copy.byDigest
-module.exports.get.info = get.info
-module.exports.get.hasContent = get.hasContent
+  get path () {
+    return this[_path]
+  }
 
-module.exports.put = put
-module.exports.put.stream = put.stream
+  write () {
+    throw new TypeError('this is a readable stream')
+  }
 
-module.exports.rm = rm.entry
-module.exports.rm.all = rm.all
-module.exports.rm.entry = module.exports.rm
-module.exports.rm.content = rm.content
+  end () {
+    throw new TypeError('this is a readable stream')
+  }
 
-module.exports.clearMemoized = clearMemoized
+  [_open] () {
+    fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd))
+  }
 
-module.exports.tmp = {}
-module.exports.tmp.mkdir = tmp.mkdir
-module.exports.tmp.withTmp = tmp.withTmp
+  [_onopen] (er, fd) {
+    if (er) {
+      this[_onerror](er)
+    } else {
+      this[_fd] = fd
+      this.emit('open', fd)
+      this[_read]()
+    }
+  }
 
-module.exports.verify = verify
-module.exports.verify.lastRun = verify.lastRun
+  [_makeBuf] () {
+    return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]))
+  }
 
+  [_read] () {
+    if (!this[_reading]) {
+      this[_reading] = true
+      const buf = this[_makeBuf]()
+      /* istanbul ignore if */
+      if (buf.length === 0) {
+        return process.nextTick(() => this[_onread](null, 0, buf))
+      }
+      fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) =>
+        this[_onread](er, br, b))
+    }
+  }
 
-/***/ }),
+  [_onread] (er, br, buf) {
+    this[_reading] = false
+    if (er) {
+      this[_onerror](er)
+    } else if (this[_handleChunk](br, buf)) {
+      this[_read]()
+    }
+  }
 
-/***/ 56068:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+  [_close] () {
+    if (this[_autoClose] && typeof this[_fd] === 'number') {
+      const fd = this[_fd]
+      this[_fd] = null
+      fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'))
+    }
+  }
 
-"use strict";
+  [_onerror] (er) {
+    this[_reading] = true
+    this[_close]()
+    this.emit('error', er)
+  }
 
+  [_handleChunk] (br, buf) {
+    let ret = false
+    // no effect if infinite
+    this[_remain] -= br
+    if (br > 0) {
+      ret = super.write(br < buf.length ? buf.slice(0, br) : buf)
+    }
 
-const { LRUCache } = __nccwpck_require__(83193)
+    if (br === 0 || this[_remain] <= 0) {
+      ret = false
+      this[_close]()
+      super.end()
+    }
 
-const MEMOIZED = new LRUCache({
-  max: 500,
-  maxSize: 50 * 1024 * 1024, // 50MB
-  ttl: 3 * 60 * 1000, // 3 minutes
-  sizeCalculation: (entry, key) => key.startsWith('key:') ? entry.data.length : entry.length,
-})
+    return ret
+  }
 
-module.exports.clearMemoized = clearMemoized
+  emit (ev, data) {
+    switch (ev) {
+      case 'prefinish':
+      case 'finish':
+        break
 
-function clearMemoized () {
-  const old = {}
-  MEMOIZED.forEach((v, k) => {
-    old[k] = v
-  })
-  MEMOIZED.clear()
-  return old
-}
+      case 'drain':
+        if (typeof this[_fd] === 'number') {
+          this[_read]()
+        }
+        break
 
-module.exports.put = put
+      case 'error':
+        if (this[_errored]) {
+          return
+        }
+        this[_errored] = true
+        return super.emit(ev, data)
 
-function put (cache, entry, data, opts) {
-  pickMem(opts).set(`key:${cache}:${entry.key}`, { entry, data })
-  putDigest(cache, entry.integrity, data, opts)
+      default:
+        return super.emit(ev, data)
+    }
+  }
 }
 
-module.exports.put.byDigest = putDigest
-
-function putDigest (cache, integrity, data, opts) {
-  pickMem(opts).set(`digest:${cache}:${integrity}`, data)
-}
+class ReadStreamSync extends ReadStream {
+  [_open] () {
+    let threw = true
+    try {
+      this[_onopen](null, fs.openSync(this[_path], 'r'))
+      threw = false
+    } finally {
+      if (threw) {
+        this[_close]()
+      }
+    }
+  }
 
-module.exports.get = get
+  [_read] () {
+    let threw = true
+    try {
+      if (!this[_reading]) {
+        this[_reading] = true
+        do {
+          const buf = this[_makeBuf]()
+          /* istanbul ignore next */
+          const br = buf.length === 0 ? 0
+            : fs.readSync(this[_fd], buf, 0, buf.length, null)
+          if (!this[_handleChunk](br, buf)) {
+            break
+          }
+        } while (true)
+        this[_reading] = false
+      }
+      threw = false
+    } finally {
+      if (threw) {
+        this[_close]()
+      }
+    }
+  }
 
-function get (cache, key, opts) {
-  return pickMem(opts).get(`key:${cache}:${key}`)
+  [_close] () {
+    if (this[_autoClose] && typeof this[_fd] === 'number') {
+      const fd = this[_fd]
+      this[_fd] = null
+      fs.closeSync(fd)
+      this.emit('close')
+    }
+  }
 }
 
-module.exports.get.byDigest = getDigest
+class WriteStream extends EE {
+  constructor (path, opt) {
+    opt = opt || {}
+    super(opt)
+    this.readable = false
+    this.writable = true
+    this[_errored] = false
+    this[_writing] = false
+    this[_ended] = false
+    this[_needDrain] = false
+    this[_queue] = []
+    this[_path] = path
+    this[_fd] = typeof opt.fd === 'number' ? opt.fd : null
+    this[_mode] = opt.mode === undefined ? 0o666 : opt.mode
+    this[_pos] = typeof opt.start === 'number' ? opt.start : null
+    this[_autoClose] = typeof opt.autoClose === 'boolean' ?
+      opt.autoClose : true
 
-function getDigest (cache, integrity, opts) {
-  return pickMem(opts).get(`digest:${cache}:${integrity}`)
-}
+    // truncating makes no sense when writing into the middle
+    const defaultFlag = this[_pos] !== null ? 'r+' : 'w'
+    this[_defaultFlag] = opt.flags === undefined
+    this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags
 
-class ObjProxy {
-  constructor (obj) {
-    this.obj = obj
+    if (this[_fd] === null) {
+      this[_open]()
+    }
   }
 
-  get (key) {
-    return this.obj[key]
+  emit (ev, data) {
+    if (ev === 'error') {
+      if (this[_errored]) {
+        return
+      }
+      this[_errored] = true
+    }
+    return super.emit(ev, data)
   }
 
-  set (key, val) {
-    this.obj[key] = val
+  get fd () {
+    return this[_fd]
   }
-}
 
-function pickMem (opts) {
-  if (!opts || !opts.memoize) {
-    return MEMOIZED
-  } else if (opts.memoize.get && opts.memoize.set) {
-    return opts.memoize
-  } else if (typeof opts.memoize === 'object') {
-    return new ObjProxy(opts.memoize)
-  } else {
-    return MEMOIZED
+  get path () {
+    return this[_path]
   }
-}
-
-
-/***/ }),
-
-/***/ 94283:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+  [_onerror] (er) {
+    this[_close]()
+    this[_writing] = true
+    this.emit('error', er)
+  }
 
+  [_open] () {
+    fs.open(this[_path], this[_flags], this[_mode],
+      (er, fd) => this[_onopen](er, fd))
+  }
 
-const index = __nccwpck_require__(26575)
-const memo = __nccwpck_require__(56068)
-const write = __nccwpck_require__(93699)
-const Flush = __nccwpck_require__(37633)
-const { PassThrough } = __nccwpck_require__(11757)
-const Pipeline = __nccwpck_require__(52899)
+  [_onopen] (er, fd) {
+    if (this[_defaultFlag] &&
+        this[_flags] === 'r+' &&
+        er && er.code === 'ENOENT') {
+      this[_flags] = 'w'
+      this[_open]()
+    } else if (er) {
+      this[_onerror](er)
+    } else {
+      this[_fd] = fd
+      this.emit('open', fd)
+      if (!this[_writing]) {
+        this[_flush]()
+      }
+    }
+  }
 
-const putOpts = (opts) => ({
-  algorithms: ['sha512'],
-  ...opts,
-})
+  end (buf, enc) {
+    if (buf) {
+      this.write(buf, enc)
+    }
 
-module.exports = putData
+    this[_ended] = true
 
-async function putData (cache, key, data, opts = {}) {
-  const { memoize } = opts
-  opts = putOpts(opts)
-  const res = await write(cache, data, opts)
-  const entry = await index.insert(cache, key, res.integrity, { ...opts, size: res.size })
-  if (memoize) {
-    memo.put(cache, entry, data, opts)
+    // synthetic after-write logic, where drain/finish live
+    if (!this[_writing] && !this[_queue].length &&
+        typeof this[_fd] === 'number') {
+      this[_onwrite](null, 0)
+    }
+    return this
   }
 
-  return res.integrity
-}
+  write (buf, enc) {
+    if (typeof buf === 'string') {
+      buf = Buffer.from(buf, enc)
+    }
 
-module.exports.stream = putStream
+    if (this[_ended]) {
+      this.emit('error', new Error('write() after end()'))
+      return false
+    }
 
-function putStream (cache, key, opts = {}) {
-  const { memoize } = opts
-  opts = putOpts(opts)
-  let integrity
-  let size
-  let error
+    if (this[_fd] === null || this[_writing] || this[_queue].length) {
+      this[_queue].push(buf)
+      this[_needDrain] = true
+      return false
+    }
 
-  let memoData
-  const pipeline = new Pipeline()
-  // first item in the pipeline is the memoizer, because we need
-  // that to end first and get the collected data.
-  if (memoize) {
-    const memoizer = new PassThrough().on('collect', data => {
-      memoData = data
-    })
-    pipeline.push(memoizer)
+    this[_writing] = true
+    this[_write](buf)
+    return true
   }
 
-  // contentStream is a write-only, not a passthrough
-  // no data comes out of it.
-  const contentStream = write.stream(cache, opts)
-    .on('integrity', (int) => {
-      integrity = int
-    })
-    .on('size', (s) => {
-      size = s
-    })
-    .on('error', (err) => {
-      error = err
-    })
+  [_write] (buf) {
+    fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) =>
+      this[_onwrite](er, bw))
+  }
 
-  pipeline.push(contentStream)
+  [_onwrite] (er, bw) {
+    if (er) {
+      this[_onerror](er)
+    } else {
+      if (this[_pos] !== null) {
+        this[_pos] += bw
+      }
+      if (this[_queue].length) {
+        this[_flush]()
+      } else {
+        this[_writing] = false
 
-  // last but not least, we write the index and emit hash and size,
-  // and memoize if we're doing that
-  pipeline.push(new Flush({
-    async flush () {
-      if (!error) {
-        const entry = await index.insert(cache, key, integrity, { ...opts, size })
-        if (memoize && memoData) {
-          memo.put(cache, entry, memoData, opts)
+        if (this[_ended] && !this[_finished]) {
+          this[_finished] = true
+          this[_close]()
+          this.emit('finish')
+        } else if (this[_needDrain]) {
+          this[_needDrain] = false
+          this.emit('drain')
         }
-        pipeline.emit('integrity', integrity)
-        pipeline.emit('size', size)
       }
-    },
-  }))
-
-  return pipeline
-}
-
-
-/***/ }),
-
-/***/ 30793:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
+    }
+  }
 
+  [_flush] () {
+    if (this[_queue].length === 0) {
+      if (this[_ended]) {
+        this[_onwrite](null, 0)
+      }
+    } else if (this[_queue].length === 1) {
+      this[_write](this[_queue].pop())
+    } else {
+      const iovec = this[_queue]
+      this[_queue] = []
+      writev(this[_fd], iovec, this[_pos],
+        (er, bw) => this[_onwrite](er, bw))
+    }
+  }
 
-const { rm } = __nccwpck_require__(91943)
-const glob = __nccwpck_require__(6337)
-const index = __nccwpck_require__(26575)
-const memo = __nccwpck_require__(56068)
-const path = __nccwpck_require__(16928)
-const rmContent = __nccwpck_require__(92447)
+  [_close] () {
+    if (this[_autoClose] && typeof this[_fd] === 'number') {
+      const fd = this[_fd]
+      this[_fd] = null
+      fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'))
+    }
+  }
+}
 
-module.exports = entry
-module.exports.entry = entry
+class WriteStreamSync extends WriteStream {
+  [_open] () {
+    let fd
+    // only wrap in a try{} block if we know we'll retry, to avoid
+    // the rethrow obscuring the error's source frame in most cases.
+    if (this[_defaultFlag] && this[_flags] === 'r+') {
+      try {
+        fd = fs.openSync(this[_path], this[_flags], this[_mode])
+      } catch (er) {
+        if (er.code === 'ENOENT') {
+          this[_flags] = 'w'
+          return this[_open]()
+        } else {
+          throw er
+        }
+      }
+    } else {
+      fd = fs.openSync(this[_path], this[_flags], this[_mode])
+    }
 
-function entry (cache, key, opts) {
-  memo.clearMemoized()
-  return index.delete(cache, key, opts)
-}
+    this[_onopen](null, fd)
+  }
 
-module.exports.content = content
+  [_close] () {
+    if (this[_autoClose] && typeof this[_fd] === 'number') {
+      const fd = this[_fd]
+      this[_fd] = null
+      fs.closeSync(fd)
+      this.emit('close')
+    }
+  }
 
-function content (cache, integrity) {
-  memo.clearMemoized()
-  return rmContent(cache, integrity)
+  [_write] (buf) {
+    // throw the original, but try to close if it fails
+    let threw = true
+    try {
+      this[_onwrite](null,
+        fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos]))
+      threw = false
+    } finally {
+      if (threw) {
+        try {
+          this[_close]()
+        } catch {
+          // ok error
+        }
+      }
+    }
+  }
 }
 
-module.exports.all = all
+exports.ReadStream = ReadStream
+exports.ReadStreamSync = ReadStreamSync
 
-async function all (cache) {
-  memo.clearMemoized()
-  const paths = await glob(path.join(cache, '*(content-*|index-*)'), { silent: true, nosort: true })
-  return Promise.all(paths.map((p) => rm(p, { recursive: true, force: true })))
-}
+exports.WriteStream = WriteStream
+exports.WriteStreamSync = WriteStreamSync
 
 
 /***/ }),
 
-/***/ 6337:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 83813:
+/***/ ((module) => {
 
 "use strict";
 
 
-const { glob } = __nccwpck_require__(67471)
-const path = __nccwpck_require__(16928)
-
-const globify = (pattern) => pattern.split(path.win32.sep).join(path.posix.sep)
-module.exports = (path, options) => glob(globify(path), options)
+module.exports = (flag, argv = process.argv) => {
+	const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
+	const position = argv.indexOf(prefix + flag);
+	const terminatorPosition = argv.indexOf('--');
+	return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+};
 
 
 /***/ }),
 
-/***/ 99704:
+/***/ 12203:
 /***/ ((module) => {
 
 "use strict";
 
+// rfc7231 6.1
+const statusCodeCacheableByDefault = new Set([
+    200,
+    203,
+    204,
+    206,
+    300,
+    301,
+    308,
+    404,
+    405,
+    410,
+    414,
+    501,
+]);
 
-module.exports = hashToSegments
-
-function hashToSegments (hash) {
-  return [hash.slice(0, 2), hash.slice(2, 4), hash.slice(4)]
-}
+// This implementation does not understand partial responses (206)
+const understoodStatuses = new Set([
+    200,
+    203,
+    204,
+    300,
+    301,
+    302,
+    303,
+    307,
+    308,
+    404,
+    405,
+    410,
+    414,
+    501,
+]);
 
+const errorStatusCodes = new Set([
+    500,
+    502,
+    503, 
+    504,
+]);
 
-/***/ }),
+const hopByHopHeaders = {
+    date: true, // included, because we add Age update Date
+    connection: true,
+    'keep-alive': true,
+    'proxy-authenticate': true,
+    'proxy-authorization': true,
+    te: true,
+    trailer: true,
+    'transfer-encoding': true,
+    upgrade: true,
+};
 
-/***/ 63990:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const excludedFromRevalidationUpdate = {
+    // Since the old body is reused, it doesn't make sense to change properties of the body
+    'content-length': true,
+    'content-encoding': true,
+    'transfer-encoding': true,
+    'content-range': true,
+};
 
-"use strict";
+function toNumberOrZero(s) {
+    const n = parseInt(s, 10);
+    return isFinite(n) ? n : 0;
+}
 
+// RFC 5861
+function isErrorResponse(response) {
+    // consider undefined response as faulty
+    if(!response) {
+        return true
+    }
+    return errorStatusCodes.has(response.status);
+}
 
-const { withTempDir } = __nccwpck_require__(88437)
-const fs = __nccwpck_require__(91943)
-const path = __nccwpck_require__(16928)
+function parseCacheControl(header) {
+    const cc = {};
+    if (!header) return cc;
 
-module.exports.mkdir = mktmpdir
+    // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),
+    // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale
+    const parts = header.trim().split(/,/);
+    for (const part of parts) {
+        const [k, v] = part.split(/=/, 2);
+        cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, '');
+    }
 
-async function mktmpdir (cache, opts = {}) {
-  const { tmpPrefix } = opts
-  const tmpDir = path.join(cache, 'tmp')
-  await fs.mkdir(tmpDir, { recursive: true, owner: 'inherit' })
-  // do not use path.join(), it drops the trailing / if tmpPrefix is unset
-  const target = `${tmpDir}${path.sep}${tmpPrefix || ''}`
-  return fs.mkdtemp(target, { owner: 'inherit' })
+    return cc;
 }
 
-module.exports.withTmp = withTmp
-
-function withTmp (cache, opts, cb) {
-  if (!cb) {
-    cb = opts
-    opts = {}
-  }
-  return withTempDir(path.join(cache, 'tmp'), cb, opts)
+function formatCacheControl(cc) {
+    let parts = [];
+    for (const k in cc) {
+        const v = cc[k];
+        parts.push(v === true ? k : k + '=' + v);
+    }
+    if (!parts.length) {
+        return undefined;
+    }
+    return parts.join(', ');
 }
 
+module.exports = class CachePolicy {
+    constructor(
+        req,
+        res,
+        {
+            shared,
+            cacheHeuristic,
+            immutableMinTimeToLive,
+            ignoreCargoCult,
+            _fromObject,
+        } = {}
+    ) {
+        if (_fromObject) {
+            this._fromObject(_fromObject);
+            return;
+        }
 
-/***/ }),
-
-/***/ 37621:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-
+        if (!res || !res.headers) {
+            throw Error('Response headers missing');
+        }
+        this._assertRequestHasHeaders(req);
 
-const {
-  mkdir,
-  readFile,
-  rm,
-  stat,
-  truncate,
-  writeFile,
-} = __nccwpck_require__(91943)
-const contentPath = __nccwpck_require__(40233)
-const fsm = __nccwpck_require__(25032)
-const glob = __nccwpck_require__(6337)
-const index = __nccwpck_require__(26575)
-const path = __nccwpck_require__(16928)
-const ssri = __nccwpck_require__(68951)
+        this._responseTime = this.now();
+        this._isShared = shared !== false;
+        this._cacheHeuristic =
+            undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
+        this._immutableMinTtl =
+            undefined !== immutableMinTimeToLive
+                ? immutableMinTimeToLive
+                : 24 * 3600 * 1000;
 
-const hasOwnProperty = (obj, key) =>
-  Object.prototype.hasOwnProperty.call(obj, key)
+        this._status = 'status' in res ? res.status : 200;
+        this._resHeaders = res.headers;
+        this._rescc = parseCacheControl(res.headers['cache-control']);
+        this._method = 'method' in req ? req.method : 'GET';
+        this._url = req.url;
+        this._host = req.headers.host;
+        this._noAuthorization = !req.headers.authorization;
+        this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used
+        this._reqcc = parseCacheControl(req.headers['cache-control']);
 
-const verifyOpts = (opts) => ({
-  concurrency: 20,
-  log: { silly () {} },
-  ...opts,
-})
+        // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,
+        // so there's no point stricly adhering to the blindly copy&pasted directives.
+        if (
+            ignoreCargoCult &&
+            'pre-check' in this._rescc &&
+            'post-check' in this._rescc
+        ) {
+            delete this._rescc['pre-check'];
+            delete this._rescc['post-check'];
+            delete this._rescc['no-cache'];
+            delete this._rescc['no-store'];
+            delete this._rescc['must-revalidate'];
+            this._resHeaders = Object.assign({}, this._resHeaders, {
+                'cache-control': formatCacheControl(this._rescc),
+            });
+            delete this._resHeaders.expires;
+            delete this._resHeaders.pragma;
+        }
 
-module.exports = verify
+        // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive
+        // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1).
+        if (
+            res.headers['cache-control'] == null &&
+            /no-cache/.test(res.headers.pragma)
+        ) {
+            this._rescc['no-cache'] = true;
+        }
+    }
 
-async function verify (cache, opts) {
-  opts = verifyOpts(opts)
-  opts.log.silly('verify', 'verifying cache at', cache)
+    now() {
+        return Date.now();
+    }
 
-  const steps = [
-    markStartTime,
-    fixPerms,
-    garbageCollect,
-    rebuildIndex,
-    cleanTmp,
-    writeVerifile,
-    markEndTime,
-  ]
+    storable() {
+        // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.
+        return !!(
+            !this._reqcc['no-store'] &&
+            // A cache MUST NOT store a response to any request, unless:
+            // The request method is understood by the cache and defined as being cacheable, and
+            ('GET' === this._method ||
+                'HEAD' === this._method ||
+                ('POST' === this._method && this._hasExplicitExpiration())) &&
+            // the response status code is understood by the cache, and
+            understoodStatuses.has(this._status) &&
+            // the "no-store" cache directive does not appear in request or response header fields, and
+            !this._rescc['no-store'] &&
+            // the "private" response directive does not appear in the response, if the cache is shared, and
+            (!this._isShared || !this._rescc.private) &&
+            // the Authorization header field does not appear in the request, if the cache is shared,
+            (!this._isShared ||
+                this._noAuthorization ||
+                this._allowsStoringAuthenticated()) &&
+            // the response either:
+            // contains an Expires header field, or
+            (this._resHeaders.expires ||
+                // contains a max-age response directive, or
+                // contains a s-maxage response directive and the cache is shared, or
+                // contains a public response directive.
+                this._rescc['max-age'] ||
+                (this._isShared && this._rescc['s-maxage']) ||
+                this._rescc.public ||
+                // has a status code that is defined as cacheable by default
+                statusCodeCacheableByDefault.has(this._status))
+        );
+    }
 
-  const stats = {}
-  for (const step of steps) {
-    const label = step.name
-    const start = new Date()
-    const s = await step(cache, opts)
-    if (s) {
-      Object.keys(s).forEach((k) => {
-        stats[k] = s[k]
-      })
+    _hasExplicitExpiration() {
+        // 4.2.1 Calculating Freshness Lifetime
+        return (
+            (this._isShared && this._rescc['s-maxage']) ||
+            this._rescc['max-age'] ||
+            this._resHeaders.expires
+        );
     }
-    const end = new Date()
-    if (!stats.runTime) {
-      stats.runTime = {}
+
+    _assertRequestHasHeaders(req) {
+        if (!req || !req.headers) {
+            throw Error('Request headers missing');
+        }
     }
-    stats.runTime[label] = end - start
-  }
-  stats.runTime.total = stats.endTime - stats.startTime
-  opts.log.silly(
-    'verify',
-    'verification finished for',
-    cache,
-    'in',
-    `${stats.runTime.total}ms`
-  )
-  return stats
-}
 
-async function markStartTime () {
-  return { startTime: new Date() }
-}
+    satisfiesWithoutRevalidation(req) {
+        this._assertRequestHasHeaders(req);
 
-async function markEndTime () {
-  return { endTime: new Date() }
-}
+        // When presented with a request, a cache MUST NOT reuse a stored response, unless:
+        // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,
+        // unless the stored response is successfully validated (Section 4.3), and
+        const requestCC = parseCacheControl(req.headers['cache-control']);
+        if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {
+            return false;
+        }
 
-async function fixPerms (cache, opts) {
-  opts.log.silly('verify', 'fixing cache permissions')
-  await mkdir(cache, { recursive: true })
-  return null
-}
+        if (requestCC['max-age'] && this.age() > requestCC['max-age']) {
+            return false;
+        }
 
-// Implements a naive mark-and-sweep tracing garbage collector.
-//
-// The algorithm is basically as follows:
-// 1. Read (and filter) all index entries ("pointers")
-// 2. Mark each integrity value as "live"
-// 3. Read entire filesystem tree in `content-vX/` dir
-// 4. If content is live, verify its checksum and delete it if it fails
-// 5. If content is not marked as live, rm it.
-//
-async function garbageCollect (cache, opts) {
-  opts.log.silly('verify', 'garbage collecting content')
-  const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606))
-  const indexStream = index.lsStream(cache)
-  const liveContent = new Set()
-  indexStream.on('data', (entry) => {
-    if (opts.filter && !opts.filter(entry)) {
-      return
-    }
+        if (
+            requestCC['min-fresh'] &&
+            this.timeToLive() < 1000 * requestCC['min-fresh']
+        ) {
+            return false;
+        }
 
-    // integrity is stringified, re-parse it so we can get each hash
-    const integrity = ssri.parse(entry.integrity)
-    for (const algo in integrity) {
-      liveContent.add(integrity[algo].toString())
-    }
-  })
-  await new Promise((resolve, reject) => {
-    indexStream.on('end', resolve).on('error', reject)
-  })
-  const contentDir = contentPath.contentDir(cache)
-  const files = await glob(path.join(contentDir, '**'), {
-    follow: false,
-    nodir: true,
-    nosort: true,
-  })
-  const stats = {
-    verifiedContent: 0,
-    reclaimedCount: 0,
-    reclaimedSize: 0,
-    badContentCount: 0,
-    keptSize: 0,
-  }
-  await pMap(
-    files,
-    async (f) => {
-      const split = f.split(/[/\\]/)
-      const digest = split.slice(split.length - 3).join('')
-      const algo = split[split.length - 4]
-      const integrity = ssri.fromHex(digest, algo)
-      if (liveContent.has(integrity.toString())) {
-        const info = await verifyContent(f, integrity)
-        if (!info.valid) {
-          stats.reclaimedCount++
-          stats.badContentCount++
-          stats.reclaimedSize += info.size
-        } else {
-          stats.verifiedContent++
-          stats.keptSize += info.size
+        // the stored response is either:
+        // fresh, or allowed to be served stale
+        if (this.stale()) {
+            const allowsStale =
+                requestCC['max-stale'] &&
+                !this._rescc['must-revalidate'] &&
+                (true === requestCC['max-stale'] ||
+                    requestCC['max-stale'] > this.age() - this.maxAge());
+            if (!allowsStale) {
+                return false;
+            }
         }
-      } else {
-        // No entries refer to this content. We can delete.
-        stats.reclaimedCount++
-        const s = await stat(f)
-        await rm(f, { recursive: true, force: true })
-        stats.reclaimedSize += s.size
-      }
-      return stats
-    },
-    { concurrency: opts.concurrency }
-  )
-  return stats
-}
 
-async function verifyContent (filepath, sri) {
-  const contentInfo = {}
-  try {
-    const { size } = await stat(filepath)
-    contentInfo.size = size
-    contentInfo.valid = true
-    await ssri.checkStream(new fsm.ReadStream(filepath), sri)
-  } catch (err) {
-    if (err.code === 'ENOENT') {
-      return { size: 0, valid: false }
-    }
-    if (err.code !== 'EINTEGRITY') {
-      throw err
+        return this._requestMatches(req, false);
     }
 
-    await rm(filepath, { recursive: true, force: true })
-    contentInfo.valid = false
-  }
-  return contentInfo
-}
-
-async function rebuildIndex (cache, opts) {
-  opts.log.silly('verify', 'rebuilding index')
-  const { default: pMap } = await __nccwpck_require__.e(/* import() */ 606).then(__nccwpck_require__.bind(__nccwpck_require__, 606))
-  const entries = await index.ls(cache)
-  const stats = {
-    missingContent: 0,
-    rejectedEntries: 0,
-    totalEntries: 0,
-  }
-  const buckets = {}
-  for (const k in entries) {
-    /* istanbul ignore else */
-    if (hasOwnProperty(entries, k)) {
-      const hashed = index.hashKey(k)
-      const entry = entries[k]
-      const excluded = opts.filter && !opts.filter(entry)
-      excluded && stats.rejectedEntries++
-      if (buckets[hashed] && !excluded) {
-        buckets[hashed].push(entry)
-      } else if (buckets[hashed] && excluded) {
-        // skip
-      } else if (excluded) {
-        buckets[hashed] = []
-        buckets[hashed]._path = index.bucketPath(cache, k)
-      } else {
-        buckets[hashed] = [entry]
-        buckets[hashed]._path = index.bucketPath(cache, k)
-      }
-    }
-  }
-  await pMap(
-    Object.keys(buckets),
-    (key) => {
-      return rebuildBucket(cache, buckets[key], stats, opts)
-    },
-    { concurrency: opts.concurrency }
-  )
-  return stats
-}
+    _requestMatches(req, allowHeadMethod) {
+        // The presented effective request URI and that of the stored response match, and
+        return (
+            (!this._url || this._url === req.url) &&
+            this._host === req.headers.host &&
+            // the request method associated with the stored response allows it to be used for the presented request, and
+            (!req.method ||
+                this._method === req.method ||
+                (allowHeadMethod && 'HEAD' === req.method)) &&
+            // selecting header fields nominated by the stored response (if any) match those presented, and
+            this._varyMatches(req)
+        );
+    }
 
-async function rebuildBucket (cache, bucket, stats) {
-  await truncate(bucket._path)
-  // This needs to be serialized because cacache explicitly
-  // lets very racy bucket conflicts clobber each other.
-  for (const entry of bucket) {
-    const content = contentPath(cache, entry.integrity)
-    try {
-      await stat(content)
-      await index.insert(cache, entry.key, entry.integrity, {
-        metadata: entry.metadata,
-        size: entry.size,
-        time: entry.time,
-      })
-      stats.totalEntries++
-    } catch (err) {
-      if (err.code === 'ENOENT') {
-        stats.rejectedEntries++
-        stats.missingContent++
-      } else {
-        throw err
-      }
+    _allowsStoringAuthenticated() {
+        //  following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.
+        return (
+            this._rescc['must-revalidate'] ||
+            this._rescc.public ||
+            this._rescc['s-maxage']
+        );
     }
-  }
-}
 
-function cleanTmp (cache, opts) {
-  opts.log.silly('verify', 'cleaning tmp directory')
-  return rm(path.join(cache, 'tmp'), { recursive: true, force: true })
-}
+    _varyMatches(req) {
+        if (!this._resHeaders.vary) {
+            return true;
+        }
 
-async function writeVerifile (cache, opts) {
-  const verifile = path.join(cache, '_lastverified')
-  opts.log.silly('verify', 'writing verifile to ' + verifile)
-  return writeFile(verifile, `${Date.now()}`)
-}
+        // A Vary header field-value of "*" always fails to match
+        if (this._resHeaders.vary === '*') {
+            return false;
+        }
 
-module.exports.lastRun = lastRun
+        const fields = this._resHeaders.vary
+            .trim()
+            .toLowerCase()
+            .split(/\s*,\s*/);
+        for (const name of fields) {
+            if (req.headers[name] !== this._reqHeaders[name]) return false;
+        }
+        return true;
+    }
 
-async function lastRun (cache) {
-  const data = await readFile(path.join(cache, '_lastverified'), { encoding: 'utf8' })
-  return new Date(+data)
-}
+    _copyWithoutHopByHopHeaders(inHeaders) {
+        const headers = {};
+        for (const name in inHeaders) {
+            if (hopByHopHeaders[name]) continue;
+            headers[name] = inHeaders[name];
+        }
+        // 9.1.  Connection
+        if (inHeaders.connection) {
+            const tokens = inHeaders.connection.trim().split(/\s*,\s*/);
+            for (const name of tokens) {
+                delete headers[name];
+            }
+        }
+        if (headers.warning) {
+            const warnings = headers.warning.split(/,/).filter(warning => {
+                return !/^\s*1[0-9][0-9]/.test(warning);
+            });
+            if (!warnings.length) {
+                delete headers.warning;
+            } else {
+                headers.warning = warnings.join(',').trim();
+            }
+        }
+        return headers;
+    }
 
+    responseHeaders() {
+        const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
+        const age = this.age();
 
-/***/ }),
+        // A cache SHOULD generate 113 warning if it heuristically chose a freshness
+        // lifetime greater than 24 hours and the response's age is greater than 24 hours.
+        if (
+            age > 3600 * 24 &&
+            !this._hasExplicitExpiration() &&
+            this.maxAge() > 3600 * 24
+        ) {
+            headers.warning =
+                (headers.warning ? `${headers.warning}, ` : '') +
+                '113 - "rfc7234 5.5.4"';
+        }
+        headers.age = `${Math.round(age)}`;
+        headers.date = new Date(this.now()).toUTCString();
+        return headers;
+    }
 
-/***/ 66723:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    /**
+     * Value of the Date response header or current time if Date was invalid
+     * @return timestamp
+     */
+    date() {
+        const serverDate = Date.parse(this._resHeaders.date);
+        if (isFinite(serverDate)) {
+            return serverDate;
+        }
+        return this._responseTime;
+    }
 
-var balanced = __nccwpck_require__(59380);
+    /**
+     * Value of the Age header, in seconds, updated for the current time.
+     * May be fractional.
+     *
+     * @return Number
+     */
+    age() {
+        let age = this._ageValue();
 
-module.exports = expandTop;
+        const residentTime = (this.now() - this._responseTime) / 1000;
+        return age + residentTime;
+    }
 
-var escSlash = '\0SLASH'+Math.random()+'\0';
-var escOpen = '\0OPEN'+Math.random()+'\0';
-var escClose = '\0CLOSE'+Math.random()+'\0';
-var escComma = '\0COMMA'+Math.random()+'\0';
-var escPeriod = '\0PERIOD'+Math.random()+'\0';
+    _ageValue() {
+        return toNumberOrZero(this._resHeaders.age);
+    }
 
-function numeric(str) {
-  return parseInt(str, 10) == str
-    ? parseInt(str, 10)
-    : str.charCodeAt(0);
-}
+    /**
+     * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
+     *
+     * For an up-to-date value, see `timeToLive()`.
+     *
+     * @return Number
+     */
+    maxAge() {
+        if (!this.storable() || this._rescc['no-cache']) {
+            return 0;
+        }
 
-function escapeBraces(str) {
-  return str.split('\\\\').join(escSlash)
-            .split('\\{').join(escOpen)
-            .split('\\}').join(escClose)
-            .split('\\,').join(escComma)
-            .split('\\.').join(escPeriod);
-}
+        // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default
+        // so this implementation requires explicit opt-in via public header
+        if (
+            this._isShared &&
+            (this._resHeaders['set-cookie'] &&
+                !this._rescc.public &&
+                !this._rescc.immutable)
+        ) {
+            return 0;
+        }
 
-function unescapeBraces(str) {
-  return str.split(escSlash).join('\\')
-            .split(escOpen).join('{')
-            .split(escClose).join('}')
-            .split(escComma).join(',')
-            .split(escPeriod).join('.');
-}
+        if (this._resHeaders.vary === '*') {
+            return 0;
+        }
 
+        if (this._isShared) {
+            if (this._rescc['proxy-revalidate']) {
+                return 0;
+            }
+            // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
+            if (this._rescc['s-maxage']) {
+                return toNumberOrZero(this._rescc['s-maxage']);
+            }
+        }
 
-// Basically just str.split(","), but handling cases
-// where we have nested braced sections, which should be
-// treated as individual members, like {a,{b,c},d}
-function parseCommaParts(str) {
-  if (!str)
-    return [''];
+        // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
+        if (this._rescc['max-age']) {
+            return toNumberOrZero(this._rescc['max-age']);
+        }
 
-  var parts = [];
-  var m = balanced('{', '}', str);
+        const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
 
-  if (!m)
-    return str.split(',');
+        const serverDate = this.date();
+        if (this._resHeaders.expires) {
+            const expires = Date.parse(this._resHeaders.expires);
+            // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
+            if (Number.isNaN(expires) || expires < serverDate) {
+                return 0;
+            }
+            return Math.max(defaultMinTtl, (expires - serverDate) / 1000);
+        }
 
-  var pre = m.pre;
-  var body = m.body;
-  var post = m.post;
-  var p = pre.split(',');
+        if (this._resHeaders['last-modified']) {
+            const lastModified = Date.parse(this._resHeaders['last-modified']);
+            if (isFinite(lastModified) && serverDate > lastModified) {
+                return Math.max(
+                    defaultMinTtl,
+                    ((serverDate - lastModified) / 1000) * this._cacheHeuristic
+                );
+            }
+        }
 
-  p[p.length-1] += '{' + body + '}';
-  var postParts = parseCommaParts(post);
-  if (post.length) {
-    p[p.length-1] += postParts.shift();
-    p.push.apply(p, postParts);
-  }
+        return defaultMinTtl;
+    }
 
-  parts.push.apply(parts, p);
+    timeToLive() {
+        const age = this.maxAge() - this.age();
+        const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']);
+        const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']);
+        return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000;
+    }
 
-  return parts;
-}
+    stale() {
+        return this.maxAge() <= this.age();
+    }
 
-function expandTop(str) {
-  if (!str)
-    return [];
+    _useStaleIfError() {
+        return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();
+    }
 
-  // I don't know why Bash 4.3 does this, but it does.
-  // Anything starting with {} will have the first two bytes preserved
-  // but *only* at the top level, so {},a}b will not expand to anything,
-  // but a{},b}c will be expanded to [a}c,abc].
-  // One could argue that this is a bug in Bash, but since the goal of
-  // this module is to match Bash's rules, we escape a leading {}
-  if (str.substr(0, 2) === '{}') {
-    str = '\\{\\}' + str.substr(2);
-  }
+    useStaleWhileRevalidate() {
+        return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age();
+    }
 
-  return expand(escapeBraces(str), true).map(unescapeBraces);
-}
+    static fromObject(obj) {
+        return new this(undefined, undefined, { _fromObject: obj });
+    }
 
-function embrace(str) {
-  return '{' + str + '}';
-}
-function isPadded(el) {
-  return /^-?0\d/.test(el);
-}
+    _fromObject(obj) {
+        if (this._responseTime) throw Error('Reinitialized');
+        if (!obj || obj.v !== 1) throw Error('Invalid serialization');
 
-function lte(i, y) {
-  return i <= y;
-}
-function gte(i, y) {
-  return i >= y;
-}
+        this._responseTime = obj.t;
+        this._isShared = obj.sh;
+        this._cacheHeuristic = obj.ch;
+        this._immutableMinTtl =
+            obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;
+        this._status = obj.st;
+        this._resHeaders = obj.resh;
+        this._rescc = obj.rescc;
+        this._method = obj.m;
+        this._url = obj.u;
+        this._host = obj.h;
+        this._noAuthorization = obj.a;
+        this._reqHeaders = obj.reqh;
+        this._reqcc = obj.reqcc;
+    }
 
-function expand(str, isTop) {
-  var expansions = [];
+    toObject() {
+        return {
+            v: 1,
+            t: this._responseTime,
+            sh: this._isShared,
+            ch: this._cacheHeuristic,
+            imm: this._immutableMinTtl,
+            st: this._status,
+            resh: this._resHeaders,
+            rescc: this._rescc,
+            m: this._method,
+            u: this._url,
+            h: this._host,
+            a: this._noAuthorization,
+            reqh: this._reqHeaders,
+            reqcc: this._reqcc,
+        };
+    }
 
-  var m = balanced('{', '}', str);
-  if (!m) return [str];
+    /**
+     * Headers for sending to the origin server to revalidate stale response.
+     * Allows server to return 304 to allow reuse of the previous response.
+     *
+     * Hop by hop headers are always stripped.
+     * Revalidation headers may be added or removed, depending on request.
+     */
+    revalidationHeaders(incomingReq) {
+        this._assertRequestHasHeaders(incomingReq);
+        const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
 
-  // no need to expand pre, since it is guaranteed to be free of brace-sets
-  var pre = m.pre;
-  var post = m.post.length
-    ? expand(m.post, false)
-    : [''];
+        // This implementation does not understand range requests
+        delete headers['if-range'];
 
-  if (/\$$/.test(m.pre)) {    
-    for (var k = 0; k < post.length; k++) {
-      var expansion = pre+ '{' + m.body + '}' + post[k];
-      expansions.push(expansion);
-    }
-  } else {
-    var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
-    var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
-    var isSequence = isNumericSequence || isAlphaSequence;
-    var isOptions = m.body.indexOf(',') >= 0;
-    if (!isSequence && !isOptions) {
-      // {a},b}
-      if (m.post.match(/,.*\}/)) {
-        str = m.pre + '{' + m.body + escClose + m.post;
-        return expand(str);
-      }
-      return [str];
-    }
+        if (!this._requestMatches(incomingReq, true) || !this.storable()) {
+            // revalidation allowed via HEAD
+            // not for the same resource, or wasn't allowed to be cached anyway
+            delete headers['if-none-match'];
+            delete headers['if-modified-since'];
+            return headers;
+        }
 
-    var n;
-    if (isSequence) {
-      n = m.body.split(/\.\./);
-    } else {
-      n = parseCommaParts(m.body);
-      if (n.length === 1) {
-        // x{{a,b}}y ==> x{a}y x{b}y
-        n = expand(n[0], false).map(embrace);
-        if (n.length === 1) {
-          return post.map(function(p) {
-            return m.pre + n[0] + p;
-          });
+        /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */
+        if (this._resHeaders.etag) {
+            headers['if-none-match'] = headers['if-none-match']
+                ? `${headers['if-none-match']}, ${this._resHeaders.etag}`
+                : this._resHeaders.etag;
         }
-      }
-    }
 
-    // at this point, n is the parts, and we know it's not a comma set
-    // with a single entry.
-    var N;
+        // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.
+        const forbidsWeakValidators =
+            headers['accept-ranges'] ||
+            headers['if-match'] ||
+            headers['if-unmodified-since'] ||
+            (this._method && this._method != 'GET');
 
-    if (isSequence) {
-      var x = numeric(n[0]);
-      var y = numeric(n[1]);
-      var width = Math.max(n[0].length, n[1].length)
-      var incr = n.length == 3
-        ? Math.abs(numeric(n[2]))
-        : 1;
-      var test = lte;
-      var reverse = y < x;
-      if (reverse) {
-        incr *= -1;
-        test = gte;
-      }
-      var pad = n.some(isPadded);
+        /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.
+        Note: This implementation does not understand partial responses (206) */
+        if (forbidsWeakValidators) {
+            delete headers['if-modified-since'];
 
-      N = [];
+            if (headers['if-none-match']) {
+                const etags = headers['if-none-match']
+                    .split(/,/)
+                    .filter(etag => {
+                        return !/^\s*W\//.test(etag);
+                    });
+                if (!etags.length) {
+                    delete headers['if-none-match'];
+                } else {
+                    headers['if-none-match'] = etags.join(',').trim();
+                }
+            }
+        } else if (
+            this._resHeaders['last-modified'] &&
+            !headers['if-modified-since']
+        ) {
+            headers['if-modified-since'] = this._resHeaders['last-modified'];
+        }
 
-      for (var i = x; test(i, y); i += incr) {
-        var c;
-        if (isAlphaSequence) {
-          c = String.fromCharCode(i);
-          if (c === '\\')
-            c = '';
+        return headers;
+    }
+
+    /**
+     * Creates new CachePolicy with information combined from the previews response,
+     * and the new revalidation response.
+     *
+     * Returns {policy, modified} where modified is a boolean indicating
+     * whether the response body has been modified, and old cached body can't be used.
+     *
+     * @return {Object} {policy: CachePolicy, modified: Boolean}
+     */
+    revalidatedPolicy(request, response) {
+        this._assertRequestHasHeaders(request);
+        if(this._useStaleIfError() && isErrorResponse(response)) {  // I consider the revalidation request unsuccessful
+          return {
+            modified: false,
+            matches: false,
+            policy: this,
+          };
+        }
+        if (!response || !response.headers) {
+            throw Error('Response headers missing');
+        }
+
+        // These aren't going to be supported exactly, since one CachePolicy object
+        // doesn't know about all the other cached objects.
+        let matches = false;
+        if (response.status !== undefined && response.status != 304) {
+            matches = false;
+        } else if (
+            response.headers.etag &&
+            !/^\s*W\//.test(response.headers.etag)
+        ) {
+            // "All of the stored responses with the same strong validator are selected.
+            // If none of the stored responses contain the same strong validator,
+            // then the cache MUST NOT use the new response to update any stored responses."
+            matches =
+                this._resHeaders.etag &&
+                this._resHeaders.etag.replace(/^\s*W\//, '') ===
+                    response.headers.etag;
+        } else if (this._resHeaders.etag && response.headers.etag) {
+            // "If the new response contains a weak validator and that validator corresponds
+            // to one of the cache's stored responses,
+            // then the most recent of those matching stored responses is selected for update."
+            matches =
+                this._resHeaders.etag.replace(/^\s*W\//, '') ===
+                response.headers.etag.replace(/^\s*W\//, '');
+        } else if (this._resHeaders['last-modified']) {
+            matches =
+                this._resHeaders['last-modified'] ===
+                response.headers['last-modified'];
         } else {
-          c = String(i);
-          if (pad) {
-            var need = width - c.length;
-            if (need > 0) {
-              var z = new Array(need + 1).join('0');
-              if (i < 0)
-                c = '-' + z + c.slice(1);
-              else
-                c = z + c;
+            // If the new response does not include any form of validator (such as in the case where
+            // a client generates an If-Modified-Since request from a source other than the Last-Modified
+            // response header field), and there is only one stored response, and that stored response also
+            // lacks a validator, then that stored response is selected for update.
+            if (
+                !this._resHeaders.etag &&
+                !this._resHeaders['last-modified'] &&
+                !response.headers.etag &&
+                !response.headers['last-modified']
+            ) {
+                matches = true;
             }
-          }
         }
-        N.push(c);
-      }
-    } else {
-      N = [];
 
-      for (var j = 0; j < n.length; j++) {
-        N.push.apply(N, expand(n[j], false));
-      }
-    }
+        if (!matches) {
+            return {
+                policy: new this.constructor(request, response),
+                // Client receiving 304 without body, even if it's invalid/mismatched has no option
+                // but to reuse a cached body. We don't have a good way to tell clients to do
+                // error recovery in such case.
+                modified: response.status != 304,
+                matches: false,
+            };
+        }
+
+        // use other header fields provided in the 304 (Not Modified) response to replace all instances
+        // of the corresponding header fields in the stored response.
+        const headers = {};
+        for (const k in this._resHeaders) {
+            headers[k] =
+                k in response.headers && !excludedFromRevalidationUpdate[k]
+                    ? response.headers[k]
+                    : this._resHeaders[k];
+        }
 
-    for (var j = 0; j < N.length; j++) {
-      for (var k = 0; k < post.length; k++) {
-        var expansion = pre + N[j] + post[k];
-        if (!isTop || isSequence || expansion)
-          expansions.push(expansion);
-      }
+        const newResponse = Object.assign({}, response, {
+            status: this._status,
+            method: this._method,
+            headers,
+        });
+        return {
+            policy: new this.constructor(request, newResponse, {
+                shared: this._isShared,
+                cacheHeuristic: this._cacheHeuristic,
+                immutableMinTimeToLive: this._immutableMinTtl,
+            }),
+            modified: false,
+            matches: true,
+        };
     }
-  }
-
-  return expansions;
-}
-
+};
 
 
 /***/ }),
 
-/***/ 97087:
-/***/ ((module) => {
+/***/ 81970:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-module.exports = function (xs, fn) {
-    var res = [];
-    for (var i = 0; i < xs.length; i++) {
-        var x = fn(xs[i], i);
-        if (isArray(x)) res.push.apply(res, x);
-        else res.push(x);
+"use strict";
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
     }
-    return res;
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
 };
-
-var isArray = Array.isArray || function (xs) {
-    return Object.prototype.toString.call(xs) === '[object Array]';
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
 };
-
-
-/***/ }),
-
-/***/ 6110:
-/***/ ((module, exports, __nccwpck_require__) => {
-
-/* eslint-env browser */
-
-/**
- * This is the web browser implementation of `debug()`.
- */
-
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.storage = localstorage();
-exports.destroy = (() => {
-	let warned = false;
-
-	return () => {
-		if (!warned) {
-			warned = true;
-			console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
-		}
-	};
-})();
-
-/**
- * Colors.
- */
-
-exports.colors = [
-	'#0000CC',
-	'#0000FF',
-	'#0033CC',
-	'#0033FF',
-	'#0066CC',
-	'#0066FF',
-	'#0099CC',
-	'#0099FF',
-	'#00CC00',
-	'#00CC33',
-	'#00CC66',
-	'#00CC99',
-	'#00CCCC',
-	'#00CCFF',
-	'#3300CC',
-	'#3300FF',
-	'#3333CC',
-	'#3333FF',
-	'#3366CC',
-	'#3366FF',
-	'#3399CC',
-	'#3399FF',
-	'#33CC00',
-	'#33CC33',
-	'#33CC66',
-	'#33CC99',
-	'#33CCCC',
-	'#33CCFF',
-	'#6600CC',
-	'#6600FF',
-	'#6633CC',
-	'#6633FF',
-	'#66CC00',
-	'#66CC33',
-	'#9900CC',
-	'#9900FF',
-	'#9933CC',
-	'#9933FF',
-	'#99CC00',
-	'#99CC33',
-	'#CC0000',
-	'#CC0033',
-	'#CC0066',
-	'#CC0099',
-	'#CC00CC',
-	'#CC00FF',
-	'#CC3300',
-	'#CC3333',
-	'#CC3366',
-	'#CC3399',
-	'#CC33CC',
-	'#CC33FF',
-	'#CC6600',
-	'#CC6633',
-	'#CC9900',
-	'#CC9933',
-	'#CCCC00',
-	'#CCCC33',
-	'#FF0000',
-	'#FF0033',
-	'#FF0066',
-	'#FF0099',
-	'#FF00CC',
-	'#FF00FF',
-	'#FF3300',
-	'#FF3333',
-	'#FF3366',
-	'#FF3399',
-	'#FF33CC',
-	'#FF33FF',
-	'#FF6600',
-	'#FF6633',
-	'#FF9900',
-	'#FF9933',
-	'#FFCC00',
-	'#FFCC33'
-];
-
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpProxyAgent = void 0;
+const net = __importStar(__nccwpck_require__(69278));
+const tls = __importStar(__nccwpck_require__(64756));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const events_1 = __nccwpck_require__(24434);
+const agent_base_1 = __nccwpck_require__(98894);
+const url_1 = __nccwpck_require__(87016);
+const debug = (0, debug_1.default)('http-proxy-agent');
 /**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
+ * to the specified "HTTP proxy server" in order to proxy HTTP requests.
  */
-
-// eslint-disable-next-line complexity
-function useColors() {
-	// NB: In an Electron preload script, document will be defined but not fully
-	// initialized. Since we know we're in Chrome, we'll just detect this case
-	// explicitly
-	if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
-		return true;
-	}
-
-	// Internet Explorer and Edge do not support colors.
-	if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
-		return false;
-	}
-
-	// Is webkit? http://stackoverflow.com/a/16459606/376773
-	// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
-	return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
-		// Is firebug? http://stackoverflow.com/a/398120/376773
-		(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
-		// Is firefox >= v31?
-		// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
-		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
-		// Double check webkit in userAgent just in case we are in a worker
-		(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+class HttpProxyAgent extends agent_base_1.Agent {
+    constructor(proxy, opts) {
+        super(opts);
+        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
+        this.proxyHeaders = opts?.headers ?? {};
+        debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
+        // Trim off the brackets from IPv6 addresses
+        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
+        const port = this.proxy.port
+            ? parseInt(this.proxy.port, 10)
+            : this.proxy.protocol === 'https:'
+                ? 443
+                : 80;
+        this.connectOpts = {
+            ...(opts ? omit(opts, 'headers') : null),
+            host,
+            port,
+        };
+    }
+    addRequest(req, opts) {
+        req._header = null;
+        this.setRequestProps(req, opts);
+        // @ts-expect-error `addRequest()` isn't defined in `@types/node`
+        super.addRequest(req, opts);
+    }
+    setRequestProps(req, opts) {
+        const { proxy } = this;
+        const protocol = opts.secureEndpoint ? 'https:' : 'http:';
+        const hostname = req.getHeader('host') || 'localhost';
+        const base = `${protocol}//${hostname}`;
+        const url = new url_1.URL(req.path, base);
+        if (opts.port !== 80) {
+            url.port = String(opts.port);
+        }
+        // Change the `http.ClientRequest` instance's "path" field
+        // to the absolute path of the URL that will be requested.
+        req.path = String(url);
+        // Inject the `Proxy-Authorization` header if necessary.
+        const headers = typeof this.proxyHeaders === 'function'
+            ? this.proxyHeaders()
+            : { ...this.proxyHeaders };
+        if (proxy.username || proxy.password) {
+            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
+        }
+        if (!headers['Proxy-Connection']) {
+            headers['Proxy-Connection'] = this.keepAlive
+                ? 'Keep-Alive'
+                : 'close';
+        }
+        for (const name of Object.keys(headers)) {
+            const value = headers[name];
+            if (value) {
+                req.setHeader(name, value);
+            }
+        }
+    }
+    async connect(req, opts) {
+        req._header = null;
+        if (!req.path.includes('://')) {
+            this.setRequestProps(req, opts);
+        }
+        // At this point, the http ClientRequest's internal `_header` field
+        // might have already been set. If this is the case then we'll need
+        // to re-generate the string since we just changed the `req.path`.
+        let first;
+        let endOfHeaders;
+        debug('Regenerating stored HTTP header string for request');
+        req._implicitHeader();
+        if (req.outputData && req.outputData.length > 0) {
+            debug('Patching connection write() output buffer with updated header');
+            first = req.outputData[0].data;
+            endOfHeaders = first.indexOf('\r\n\r\n') + 4;
+            req.outputData[0].data =
+                req._header + first.substring(endOfHeaders);
+            debug('Output buffer: %o', req.outputData[0].data);
+        }
+        // Create a socket connection to the proxy server.
+        let socket;
+        if (this.proxy.protocol === 'https:') {
+            debug('Creating `tls.Socket`: %o', this.connectOpts);
+            socket = tls.connect(this.connectOpts);
+        }
+        else {
+            debug('Creating `net.Socket`: %o', this.connectOpts);
+            socket = net.connect(this.connectOpts);
+        }
+        // Wait for the socket's `connect` event, so that this `callback()`
+        // function throws instead of the `http` request machinery. This is
+        // important for i.e. `PacProxyAgent` which determines a failed proxy
+        // connection via the `callback()` function throwing.
+        await (0, events_1.once)(socket, 'connect');
+        return socket;
+    }
 }
+HttpProxyAgent.protocols = ['http', 'https'];
+exports.HttpProxyAgent = HttpProxyAgent;
+function omit(obj, ...keys) {
+    const ret = {};
+    let key;
+    for (key in obj) {
+        if (!keys.includes(key)) {
+            ret[key] = obj[key];
+        }
+    }
+    return ret;
+}
+//# sourceMappingURL=index.js.map
 
-/**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
-
-function formatArgs(args) {
-	args[0] = (this.useColors ? '%c' : '') +
-		this.namespace +
-		(this.useColors ? ' %c' : ' ') +
-		args[0] +
-		(this.useColors ? '%c ' : ' ') +
-		'+' + module.exports.humanize(this.diff);
-
-	if (!this.useColors) {
-		return;
-	}
-
-	const c = 'color: ' + this.color;
-	args.splice(1, 0, c, 'color: inherit');
+/***/ }),
 
-	// The final "%c" is somewhat tricky, because there could be other
-	// arguments passed either before or after the %c, so we need to
-	// figure out the correct index to insert the CSS into
-	let index = 0;
-	let lastC = 0;
-	args[0].replace(/%[a-zA-Z%]/g, match => {
-		if (match === '%%') {
-			return;
-		}
-		index++;
-		if (match === '%c') {
-			// We only are interested in the *last* %c
-			// (the user may have provided their own)
-			lastC = index;
-		}
-	});
+/***/ 3669:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-	args.splice(lastC, 0, c);
-}
+"use strict";
 
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpsProxyAgent = void 0;
+const net = __importStar(__nccwpck_require__(69278));
+const tls = __importStar(__nccwpck_require__(64756));
+const assert_1 = __importDefault(__nccwpck_require__(42613));
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const agent_base_1 = __nccwpck_require__(98894);
+const url_1 = __nccwpck_require__(87016);
+const parse_proxy_response_1 = __nccwpck_require__(37943);
+const debug = (0, debug_1.default)('https-proxy-agent');
 /**
- * Invokes `console.debug()` when available.
- * No-op when `console.debug` is not a "function".
- * If `console.debug` is not available, falls back
- * to `console.log`.
+ * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
+ * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
  *
- * @api public
- */
-exports.log = console.debug || console.log || (() => {});
-
-/**
- * Save `namespaces`.
+ * Outgoing HTTP requests are first tunneled through the proxy server using the
+ * `CONNECT` HTTP request method to establish a connection to the proxy server,
+ * and then the proxy server connects to the destination target and issues the
+ * HTTP request from the proxy server.
  *
- * @param {String} namespaces
- * @api private
+ * `https:` requests have their socket connection upgraded to TLS once
+ * the connection to the proxy server has been established.
  */
-function save(namespaces) {
-	try {
-		if (namespaces) {
-			exports.storage.setItem('debug', namespaces);
-		} else {
-			exports.storage.removeItem('debug');
-		}
-	} catch (error) {
-		// Swallow
-		// XXX (@Qix-) should we be logging these?
-	}
+class HttpsProxyAgent extends agent_base_1.Agent {
+    constructor(proxy, opts) {
+        super(opts);
+        this.options = { path: undefined };
+        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
+        this.proxyHeaders = opts?.headers ?? {};
+        debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
+        // Trim off the brackets from IPv6 addresses
+        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
+        const port = this.proxy.port
+            ? parseInt(this.proxy.port, 10)
+            : this.proxy.protocol === 'https:'
+                ? 443
+                : 80;
+        this.connectOpts = {
+            // Attempt to negotiate http/1.1 for proxy servers that support http/2
+            ALPNProtocols: ['http/1.1'],
+            ...(opts ? omit(opts, 'headers') : null),
+            host,
+            port,
+        };
+    }
+    /**
+     * Called when the node-core HTTP client library is creating a
+     * new HTTP request.
+     */
+    async connect(req, opts) {
+        const { proxy } = this;
+        if (!opts.host) {
+            throw new TypeError('No "host" provided');
+        }
+        // Create a socket connection to the proxy server.
+        let socket;
+        if (proxy.protocol === 'https:') {
+            debug('Creating `tls.Socket`: %o', this.connectOpts);
+            const servername = this.connectOpts.servername || this.connectOpts.host;
+            socket = tls.connect({
+                ...this.connectOpts,
+                servername,
+            });
+        }
+        else {
+            debug('Creating `net.Socket`: %o', this.connectOpts);
+            socket = net.connect(this.connectOpts);
+        }
+        const headers = typeof this.proxyHeaders === 'function'
+            ? this.proxyHeaders()
+            : { ...this.proxyHeaders };
+        const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
+        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
+        // Inject the `Proxy-Authorization` header if necessary.
+        if (proxy.username || proxy.password) {
+            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
+            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
+        }
+        headers.Host = `${host}:${opts.port}`;
+        if (!headers['Proxy-Connection']) {
+            headers['Proxy-Connection'] = this.keepAlive
+                ? 'Keep-Alive'
+                : 'close';
+        }
+        for (const name of Object.keys(headers)) {
+            payload += `${name}: ${headers[name]}\r\n`;
+        }
+        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
+        socket.write(`${payload}\r\n`);
+        const { connect, buffered } = await proxyResponsePromise;
+        req.emit('proxyConnect', connect);
+        this.emit('proxyConnect', connect, req);
+        if (connect.statusCode === 200) {
+            req.once('socket', resume);
+            if (opts.secureEndpoint) {
+                // The proxy is connecting to a TLS server, so upgrade
+                // this socket connection to a TLS connection.
+                debug('Upgrading socket connection to TLS');
+                const servername = opts.servername || opts.host;
+                return tls.connect({
+                    ...omit(opts, 'host', 'path', 'port'),
+                    socket,
+                    servername,
+                });
+            }
+            return socket;
+        }
+        // Some other status code that's not 200... need to re-play the HTTP
+        // header "data" events onto the socket once the HTTP machinery is
+        // attached so that the node core `http` can parse and handle the
+        // error status code.
+        // Close the original socket, and a new "fake" socket is returned
+        // instead, so that the proxy doesn't get the HTTP request
+        // written to it (which may contain `Authorization` headers or other
+        // sensitive data).
+        //
+        // See: https://hackerone.com/reports/541502
+        socket.destroy();
+        const fakeSocket = new net.Socket({ writable: false });
+        fakeSocket.readable = true;
+        // Need to wait for the "socket" event to re-play the "data" events.
+        req.once('socket', (s) => {
+            debug('Replaying proxy buffer for failed request');
+            (0, assert_1.default)(s.listenerCount('data') > 0);
+            // Replay the "buffered" Buffer onto the fake `socket`, since at
+            // this point the HTTP module machinery has been hooked up for
+            // the user.
+            s.push(buffered);
+            s.push(null);
+        });
+        return fakeSocket;
+    }
 }
-
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
-function load() {
-	let r;
-	try {
-		r = exports.storage.getItem('debug');
-	} catch (error) {
-		// Swallow
-		// XXX (@Qix-) should we be logging these?
-	}
-
-	// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
-	if (!r && typeof process !== 'undefined' && 'env' in process) {
-		r = process.env.DEBUG;
-	}
-
-	return r;
+HttpsProxyAgent.protocols = ['http', 'https'];
+exports.HttpsProxyAgent = HttpsProxyAgent;
+function resume(socket) {
+    socket.resume();
 }
-
-/**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
- */
-
-function localstorage() {
-	try {
-		// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
-		// The Browser also has localStorage in the global context.
-		return localStorage;
-	} catch (error) {
-		// Swallow
-		// XXX (@Qix-) should we be logging these?
-	}
+function omit(obj, ...keys) {
+    const ret = {};
+    let key;
+    for (key in obj) {
+        if (!keys.includes(key)) {
+            ret[key] = obj[key];
+        }
+    }
+    return ret;
 }
+//# sourceMappingURL=index.js.map
 
-module.exports = __nccwpck_require__(40897)(exports);
+/***/ }),
 
-const {formatters} = module.exports;
+/***/ 37943:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-/**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
+"use strict";
 
-formatters.j = function (v) {
-	try {
-		return JSON.stringify(v);
-	} catch (error) {
-		return '[UnexpectedJSONParseError]: ' + error.message;
-	}
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
 };
-
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseProxyResponse = void 0;
+const debug_1 = __importDefault(__nccwpck_require__(2830));
+const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
+function parseProxyResponse(socket) {
+    return new Promise((resolve, reject) => {
+        // we need to buffer any HTTP traffic that happens with the proxy before we get
+        // the CONNECT response, so that if the response is anything other than an "200"
+        // response code, then we can re-play the "data" events on the socket once the
+        // HTTP parser is hooked up...
+        let buffersLength = 0;
+        const buffers = [];
+        function read() {
+            const b = socket.read();
+            if (b)
+                ondata(b);
+            else
+                socket.once('readable', read);
+        }
+        function cleanup() {
+            socket.removeListener('end', onend);
+            socket.removeListener('error', onerror);
+            socket.removeListener('readable', read);
+        }
+        function onend() {
+            cleanup();
+            debug('onend');
+            reject(new Error('Proxy connection ended before receiving CONNECT response'));
+        }
+        function onerror(err) {
+            cleanup();
+            debug('onerror %o', err);
+            reject(err);
+        }
+        function ondata(b) {
+            buffers.push(b);
+            buffersLength += b.length;
+            const buffered = Buffer.concat(buffers, buffersLength);
+            const endOfHeaders = buffered.indexOf('\r\n\r\n');
+            if (endOfHeaders === -1) {
+                // keep buffering
+                debug('have not received end of HTTP headers yet...');
+                read();
+                return;
+            }
+            const headerParts = buffered
+                .slice(0, endOfHeaders)
+                .toString('ascii')
+                .split('\r\n');
+            const firstLine = headerParts.shift();
+            if (!firstLine) {
+                socket.destroy();
+                return reject(new Error('No header received from proxy CONNECT response'));
+            }
+            const firstLineParts = firstLine.split(' ');
+            const statusCode = +firstLineParts[1];
+            const statusText = firstLineParts.slice(2).join(' ');
+            const headers = {};
+            for (const header of headerParts) {
+                if (!header)
+                    continue;
+                const firstColon = header.indexOf(':');
+                if (firstColon === -1) {
+                    socket.destroy();
+                    return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
+                }
+                const key = header.slice(0, firstColon).toLowerCase();
+                const value = header.slice(firstColon + 1).trimStart();
+                const current = headers[key];
+                if (typeof current === 'string') {
+                    headers[key] = [current, value];
+                }
+                else if (Array.isArray(current)) {
+                    current.push(value);
+                }
+                else {
+                    headers[key] = value;
+                }
+            }
+            debug('got proxy server response: %o %o', firstLine, headers);
+            cleanup();
+            resolve({
+                connect: {
+                    statusCode,
+                    statusText,
+                    headers,
+                },
+                buffered,
+            });
+        }
+        socket.on('error', onerror);
+        socket.on('end', onend);
+        read();
+    });
+}
+exports.parseProxyResponse = parseProxyResponse;
+//# sourceMappingURL=parse-proxy-response.js.map
 
 /***/ }),
 
-/***/ 40897:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-/**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
- */
-
-function setup(env) {
-	createDebug.debug = createDebug;
-	createDebug.default = createDebug;
-	createDebug.coerce = coerce;
-	createDebug.disable = disable;
-	createDebug.enable = enable;
-	createDebug.enabled = enabled;
-	createDebug.humanize = __nccwpck_require__(70744);
-	createDebug.destroy = destroy;
-
-	Object.keys(env).forEach(key => {
-		createDebug[key] = env[key];
-	});
-
-	/**
-	* The currently active debug mode names, and names to skip.
-	*/
-
-	createDebug.names = [];
-	createDebug.skips = [];
-
-	/**
-	* Map of special "%n" handling functions, for the debug "format" argument.
-	*
-	* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
-	*/
-	createDebug.formatters = {};
-
-	/**
-	* Selects a color for a debug namespace
-	* @param {String} namespace The namespace string for the debug instance to be colored
-	* @return {Number|String} An ANSI color code for the given namespace
-	* @api private
-	*/
-	function selectColor(namespace) {
-		let hash = 0;
-
-		for (let i = 0; i < namespace.length; i++) {
-			hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
-			hash |= 0; // Convert to 32bit integer
-		}
-
-		return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
-	}
-	createDebug.selectColor = selectColor;
-
-	/**
-	* Create a debugger with the given `namespace`.
-	*
-	* @param {String} namespace
-	* @return {Function}
-	* @api public
-	*/
-	function createDebug(namespace) {
-		let prevTime;
-		let enableOverride = null;
-		let namespacesCache;
-		let enabledCache;
-
-		function debug(...args) {
-			// Disabled?
-			if (!debug.enabled) {
-				return;
-			}
-
-			const self = debug;
-
-			// Set `diff` timestamp
-			const curr = Number(new Date());
-			const ms = curr - (prevTime || curr);
-			self.diff = ms;
-			self.prev = prevTime;
-			self.curr = curr;
-			prevTime = curr;
+/***/ 7978:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-			args[0] = createDebug.coerce(args[0]);
+"use strict";
 
-			if (typeof args[0] !== 'string') {
-				// Anything else let's inspect with %O
-				args.unshift('%O');
-			}
+var Buffer = (__nccwpck_require__(12803).Buffer);
 
-			// Apply any `formatters` transformations
-			let index = 0;
-			args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
-				// If we encounter an escaped % then don't increase the array index
-				if (match === '%%') {
-					return '%';
-				}
-				index++;
-				const formatter = createDebug.formatters[format];
-				if (typeof formatter === 'function') {
-					const val = args[index];
-					match = formatter.call(self, val);
+// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
+// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
+// To save memory and loading time, we read table files only when requested.
 
-					// Now we need to remove `args[index]` since it's inlined in the `format`
-					args.splice(index, 1);
-					index--;
-				}
-				return match;
-			});
+exports._dbcs = DBCSCodec;
 
-			// Apply env-specific formatting (colors, etc.)
-			createDebug.formatArgs.call(self, args);
+var UNASSIGNED = -1,
+    GB18030_CODE = -2,
+    SEQ_START  = -10,
+    NODE_START = -1000,
+    UNASSIGNED_NODE = new Array(0x100),
+    DEF_CHAR = -1;
 
-			const logFn = self.log || createDebug.log;
-			logFn.apply(self, args);
-		}
+for (var i = 0; i < 0x100; i++)
+    UNASSIGNED_NODE[i] = UNASSIGNED;
 
-		debug.namespace = namespace;
-		debug.useColors = createDebug.useColors();
-		debug.color = createDebug.selectColor(namespace);
-		debug.extend = extend;
-		debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
 
-		Object.defineProperty(debug, 'enabled', {
-			enumerable: true,
-			configurable: false,
-			get: () => {
-				if (enableOverride !== null) {
-					return enableOverride;
-				}
-				if (namespacesCache !== createDebug.namespaces) {
-					namespacesCache = createDebug.namespaces;
-					enabledCache = createDebug.enabled(namespace);
-				}
+// Class DBCSCodec reads and initializes mapping tables.
+function DBCSCodec(codecOptions, iconv) {
+    this.encodingName = codecOptions.encodingName;
+    if (!codecOptions)
+        throw new Error("DBCS codec is called without the data.")
+    if (!codecOptions.table)
+        throw new Error("Encoding '" + this.encodingName + "' has no data.");
 
-				return enabledCache;
-			},
-			set: v => {
-				enableOverride = v;
-			}
-		});
+    // Load tables.
+    var mappingTable = codecOptions.table();
 
-		// Env-specific initialization logic for debug instances
-		if (typeof createDebug.init === 'function') {
-			createDebug.init(debug);
-		}
 
-		return debug;
-	}
+    // Decode tables: MBCS -> Unicode.
 
-	function extend(namespace, delimiter) {
-		const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
-		newDebug.log = this.log;
-		return newDebug;
-	}
+    // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
+    // Trie root is decodeTables[0].
+    // Values: >=  0 -> unicode character code. can be > 0xFFFF
+    //         == UNASSIGNED -> unknown/unassigned sequence.
+    //         == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
+    //         <= NODE_START -> index of the next node in our trie to process next byte.
+    //         <= SEQ_START  -> index of the start of a character code sequence, in decodeTableSeq.
+    this.decodeTables = [];
+    this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
 
-	/**
-	* Enables a debug mode by namespaces. This can include modes
-	* separated by a colon and wildcards.
-	*
-	* @param {String} namespaces
-	* @api public
-	*/
-	function enable(namespaces) {
-		createDebug.save(namespaces);
-		createDebug.namespaces = namespaces;
+    // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
+    this.decodeTableSeq = [];
 
-		createDebug.names = [];
-		createDebug.skips = [];
+    // Actual mapping tables consist of chunks. Use them to fill up decode tables.
+    for (var i = 0; i < mappingTable.length; i++)
+        this._addDecodeChunk(mappingTable[i]);
 
-		let i;
-		const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
-		const len = split.length;
+    // Load & create GB18030 tables when needed.
+    if (typeof codecOptions.gb18030 === 'function') {
+        this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
 
-		for (i = 0; i < len; i++) {
-			if (!split[i]) {
-				// ignore empty strings
-				continue;
-			}
+        // Add GB18030 common decode nodes.
+        var commonThirdByteNodeIdx = this.decodeTables.length;
+        this.decodeTables.push(UNASSIGNED_NODE.slice(0));
 
-			namespaces = split[i].replace(/\*/g, '.*?');
+        var commonFourthByteNodeIdx = this.decodeTables.length;
+        this.decodeTables.push(UNASSIGNED_NODE.slice(0));
 
-			if (namespaces[0] === '-') {
-				createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
-			} else {
-				createDebug.names.push(new RegExp('^' + namespaces + '$'));
-			}
-		}
-	}
+        // Fill out the tree
+        var firstByteNode = this.decodeTables[0];
+        for (var i = 0x81; i <= 0xFE; i++) {
+            var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]];
+            for (var j = 0x30; j <= 0x39; j++) {
+                if (secondByteNode[j] === UNASSIGNED) {
+                    secondByteNode[j] = NODE_START - commonThirdByteNodeIdx;
+                } else if (secondByteNode[j] > NODE_START) {
+                    throw new Error("gb18030 decode tables conflict at byte 2");
+                }
 
-	/**
-	* Disable debug output.
-	*
-	* @return {String} namespaces
-	* @api public
-	*/
-	function disable() {
-		const namespaces = [
-			...createDebug.names.map(toNamespace),
-			...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
-		].join(',');
-		createDebug.enable('');
-		return namespaces;
-	}
+                var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]];
+                for (var k = 0x81; k <= 0xFE; k++) {
+                    if (thirdByteNode[k] === UNASSIGNED) {
+                        thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx;
+                    } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {
+                        continue;
+                    } else if (thirdByteNode[k] > NODE_START) {
+                        throw new Error("gb18030 decode tables conflict at byte 3");
+                    }
 
-	/**
-	* Returns true if the given mode name is enabled, false otherwise.
-	*
-	* @param {String} name
-	* @return {Boolean}
-	* @api public
-	*/
-	function enabled(name) {
-		if (name[name.length - 1] === '*') {
-			return true;
-		}
+                    var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]];
+                    for (var l = 0x30; l <= 0x39; l++) {
+                        if (fourthByteNode[l] === UNASSIGNED)
+                            fourthByteNode[l] = GB18030_CODE;
+                    }
+                }
+            }
+        }
+    }
 
-		let i;
-		let len;
+    this.defaultCharUnicode = iconv.defaultCharUnicode;
 
-		for (i = 0, len = createDebug.skips.length; i < len; i++) {
-			if (createDebug.skips[i].test(name)) {
-				return false;
-			}
-		}
+    
+    // Encode tables: Unicode -> DBCS.
 
-		for (i = 0, len = createDebug.names.length; i < len; i++) {
-			if (createDebug.names[i].test(name)) {
-				return true;
-			}
-		}
+    // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
+    // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
+    // Values: >=  0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
+    //         == UNASSIGNED -> no conversion found. Output a default char.
+    //         <= SEQ_START  -> it's an index in encodeTableSeq, see below. The character starts a sequence.
+    this.encodeTable = [];
+    
+    // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
+    // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
+    // means end of sequence (needed when one sequence is a strict subsequence of another).
+    // Objects are kept separately from encodeTable to increase performance.
+    this.encodeTableSeq = [];
 
-		return false;
-	}
+    // Some chars can be decoded, but need not be encoded.
+    var skipEncodeChars = {};
+    if (codecOptions.encodeSkipVals)
+        for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
+            var val = codecOptions.encodeSkipVals[i];
+            if (typeof val === 'number')
+                skipEncodeChars[val] = true;
+            else
+                for (var j = val.from; j <= val.to; j++)
+                    skipEncodeChars[j] = true;
+        }
+        
+    // Use decode trie to recursively fill out encode tables.
+    this._fillEncodeTable(0, 0, skipEncodeChars);
 
-	/**
-	* Convert regexp to namespace
-	*
-	* @param {RegExp} regxep
-	* @return {String} namespace
-	* @api private
-	*/
-	function toNamespace(regexp) {
-		return regexp.toString()
-			.substring(2, regexp.toString().length - 2)
-			.replace(/\.\*\?$/, '*');
-	}
+    // Add more encoding pairs when needed.
+    if (codecOptions.encodeAdd) {
+        for (var uChar in codecOptions.encodeAdd)
+            if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
+                this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
+    }
 
-	/**
-	* Coerce `val`.
-	*
-	* @param {Mixed} val
-	* @return {Mixed}
-	* @api private
-	*/
-	function coerce(val) {
-		if (val instanceof Error) {
-			return val.stack || val.message;
-		}
-		return val;
-	}
+    this.defCharSB  = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
+    if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
+    if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
+}
 
-	/**
-	* XXX DO NOT USE. This is a temporary stub function.
-	* XXX It WILL be removed in the next major release.
-	*/
-	function destroy() {
-		console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
-	}
+DBCSCodec.prototype.encoder = DBCSEncoder;
+DBCSCodec.prototype.decoder = DBCSDecoder;
 
-	createDebug.enable(createDebug.load());
+// Decoder helpers
+DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
+    var bytes = [];
+    for (; addr > 0; addr >>>= 8)
+        bytes.push(addr & 0xFF);
+    if (bytes.length == 0)
+        bytes.push(0);
 
-	return createDebug;
+    var node = this.decodeTables[0];
+    for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
+        var val = node[bytes[i]];
+
+        if (val == UNASSIGNED) { // Create new node.
+            node[bytes[i]] = NODE_START - this.decodeTables.length;
+            this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
+        }
+        else if (val <= NODE_START) { // Existing node.
+            node = this.decodeTables[NODE_START - val];
+        }
+        else
+            throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
+    }
+    return node;
 }
 
-module.exports = setup;
 
+DBCSCodec.prototype._addDecodeChunk = function(chunk) {
+    // First element of chunk is the hex mbcs code where we start.
+    var curAddr = parseInt(chunk[0], 16);
 
-/***/ }),
+    // Choose the decoding node where we'll write our chars.
+    var writeTable = this._getDecodeTrieNode(curAddr);
+    curAddr = curAddr & 0xFF;
 
-/***/ 2830:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    // Write all other elements of the chunk to the table.
+    for (var k = 1; k < chunk.length; k++) {
+        var part = chunk[k];
+        if (typeof part === "string") { // String, write as-is.
+            for (var l = 0; l < part.length;) {
+                var code = part.charCodeAt(l++);
+                if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
+                    var codeTrail = part.charCodeAt(l++);
+                    if (0xDC00 <= codeTrail && codeTrail < 0xE000)
+                        writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
+                    else
+                        throw new Error("Incorrect surrogate pair in "  + this.encodingName + " at chunk " + chunk[0]);
+                }
+                else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
+                    var len = 0xFFF - code + 2;
+                    var seq = [];
+                    for (var m = 0; m < len; m++)
+                        seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
 
-/**
- * Detect Electron renderer / nwjs process, which is node, but we should
- * treat as a browser.
- */
+                    writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
+                    this.decodeTableSeq.push(seq);
+                }
+                else
+                    writeTable[curAddr++] = code; // Basic char
+            }
+        } 
+        else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
+            var charCode = writeTable[curAddr - 1] + 1;
+            for (var l = 0; l < part; l++)
+                writeTable[curAddr++] = charCode++;
+        }
+        else
+            throw new Error("Incorrect type '" + typeof part + "' given in "  + this.encodingName + " at chunk " + chunk[0]);
+    }
+    if (curAddr > 0xFF)
+        throw new Error("Incorrect chunk in "  + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
+}
 
-if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
-	module.exports = __nccwpck_require__(6110);
-} else {
-	module.exports = __nccwpck_require__(95108);
+// Encoder helpers
+DBCSCodec.prototype._getEncodeBucket = function(uCode) {
+    var high = uCode >> 8; // This could be > 0xFF because of astral characters.
+    if (this.encodeTable[high] === undefined)
+        this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
+    return this.encodeTable[high];
 }
 
+DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
+    var bucket = this._getEncodeBucket(uCode);
+    var low = uCode & 0xFF;
+    if (bucket[low] <= SEQ_START)
+        this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
+    else if (bucket[low] == UNASSIGNED)
+        bucket[low] = dbcsCode;
+}
 
-/***/ }),
+DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
+    
+    // Get the root of character tree according to first character of the sequence.
+    var uCode = seq[0];
+    var bucket = this._getEncodeBucket(uCode);
+    var low = uCode & 0xFF;
 
-/***/ 95108:
-/***/ ((module, exports, __nccwpck_require__) => {
+    var node;
+    if (bucket[low] <= SEQ_START) {
+        // There's already a sequence with  - use it.
+        node = this.encodeTableSeq[SEQ_START-bucket[low]];
+    }
+    else {
+        // There was no sequence object - allocate a new one.
+        node = {};
+        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
+        bucket[low] = SEQ_START - this.encodeTableSeq.length;
+        this.encodeTableSeq.push(node);
+    }
 
-/**
- * Module dependencies.
- */
+    // Traverse the character tree, allocating new nodes as needed.
+    for (var j = 1; j < seq.length-1; j++) {
+        var oldVal = node[uCode];
+        if (typeof oldVal === 'object')
+            node = oldVal;
+        else {
+            node = node[uCode] = {}
+            if (oldVal !== undefined)
+                node[DEF_CHAR] = oldVal
+        }
+    }
 
-const tty = __nccwpck_require__(52018);
-const util = __nccwpck_require__(39023);
+    // Set the leaf to given dbcsCode.
+    uCode = seq[seq.length-1];
+    node[uCode] = dbcsCode;
+}
 
-/**
- * This is the Node.js implementation of `debug()`.
- */
+DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
+    var node = this.decodeTables[nodeIdx];
+    var hasValues = false;
+    var subNodeEmpty = {};
+    for (var i = 0; i < 0x100; i++) {
+        var uCode = node[i];
+        var mbCode = prefix + i;
+        if (skipEncodeChars[mbCode])
+            continue;
 
-exports.init = init;
-exports.log = log;
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.destroy = util.deprecate(
-	() => {},
-	'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
-);
+        if (uCode >= 0) {
+            this._setEncodeChar(uCode, mbCode);
+            hasValues = true;
+        } else if (uCode <= NODE_START) {
+            var subNodeIdx = NODE_START - uCode;
+            if (!subNodeEmpty[subNodeIdx]) {  // Skip empty subtrees (they are too large in gb18030).
+                var newPrefix = (mbCode << 8) >>> 0;  // NOTE: '>>> 0' keeps 32-bit num positive.
+                if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars))
+                    hasValues = true;
+                else
+                    subNodeEmpty[subNodeIdx] = true;
+            }
+        } else if (uCode <= SEQ_START) {
+            this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
+            hasValues = true;
+        }
+    }
+    return hasValues;
+}
 
-/**
- * Colors.
- */
 
-exports.colors = [6, 2, 3, 4, 5, 1];
 
-try {
-	// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
-	// eslint-disable-next-line import/no-extraneous-dependencies
-	const supportsColor = __nccwpck_require__(21450);
+// == Encoder ==================================================================
 
-	if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
-		exports.colors = [
-			20,
-			21,
-			26,
-			27,
-			32,
-			33,
-			38,
-			39,
-			40,
-			41,
-			42,
-			43,
-			44,
-			45,
-			56,
-			57,
-			62,
-			63,
-			68,
-			69,
-			74,
-			75,
-			76,
-			77,
-			78,
-			79,
-			80,
-			81,
-			92,
-			93,
-			98,
-			99,
-			112,
-			113,
-			128,
-			129,
-			134,
-			135,
-			148,
-			149,
-			160,
-			161,
-			162,
-			163,
-			164,
-			165,
-			166,
-			167,
-			168,
-			169,
-			170,
-			171,
-			172,
-			173,
-			178,
-			179,
-			184,
-			185,
-			196,
-			197,
-			198,
-			199,
-			200,
-			201,
-			202,
-			203,
-			204,
-			205,
-			206,
-			207,
-			208,
-			209,
-			214,
-			215,
-			220,
-			221
-		];
-	}
-} catch (error) {
-	// Swallow - we only care if `supports-color` is available; it doesn't have to be.
+function DBCSEncoder(options, codec) {
+    // Encoder state
+    this.leadSurrogate = -1;
+    this.seqObj = undefined;
+    
+    // Static data
+    this.encodeTable = codec.encodeTable;
+    this.encodeTableSeq = codec.encodeTableSeq;
+    this.defaultCharSingleByte = codec.defCharSB;
+    this.gb18030 = codec.gb18030;
 }
 
-/**
- * Build up the default `inspectOpts` object from the environment variables.
- *
- *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
- */
+DBCSEncoder.prototype.write = function(str) {
+    var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
+        leadSurrogate = this.leadSurrogate,
+        seqObj = this.seqObj, nextChar = -1,
+        i = 0, j = 0;
 
-exports.inspectOpts = Object.keys(process.env).filter(key => {
-	return /^debug_/i.test(key);
-}).reduce((obj, key) => {
-	// Camel-case
-	const prop = key
-		.substring(6)
-		.toLowerCase()
-		.replace(/_([a-z])/g, (_, k) => {
-			return k.toUpperCase();
-		});
+    while (true) {
+        // 0. Get next character.
+        if (nextChar === -1) {
+            if (i == str.length) break;
+            var uCode = str.charCodeAt(i++);
+        }
+        else {
+            var uCode = nextChar;
+            nextChar = -1;    
+        }
 
-	// Coerce string value into JS value
-	let val = process.env[key];
-	if (/^(yes|on|true|enabled)$/i.test(val)) {
-		val = true;
-	} else if (/^(no|off|false|disabled)$/i.test(val)) {
-		val = false;
-	} else if (val === 'null') {
-		val = null;
-	} else {
-		val = Number(val);
-	}
+        // 1. Handle surrogates.
+        if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
+            if (uCode < 0xDC00) { // We've got lead surrogate.
+                if (leadSurrogate === -1) {
+                    leadSurrogate = uCode;
+                    continue;
+                } else {
+                    leadSurrogate = uCode;
+                    // Double lead surrogate found.
+                    uCode = UNASSIGNED;
+                }
+            } else { // We've got trail surrogate.
+                if (leadSurrogate !== -1) {
+                    uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
+                    leadSurrogate = -1;
+                } else {
+                    // Incomplete surrogate pair - only trail surrogate found.
+                    uCode = UNASSIGNED;
+                }
+                
+            }
+        }
+        else if (leadSurrogate !== -1) {
+            // Incomplete surrogate pair - only lead surrogate found.
+            nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
+            leadSurrogate = -1;
+        }
 
-	obj[prop] = val;
-	return obj;
-}, {});
+        // 2. Convert uCode character.
+        var dbcsCode = UNASSIGNED;
+        if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
+            var resCode = seqObj[uCode];
+            if (typeof resCode === 'object') { // Sequence continues.
+                seqObj = resCode;
+                continue;
 
-/**
- * Is stdout a TTY? Colored output is enabled when `true`.
- */
+            } else if (typeof resCode == 'number') { // Sequence finished. Write it.
+                dbcsCode = resCode;
 
-function useColors() {
-	return 'colors' in exports.inspectOpts ?
-		Boolean(exports.inspectOpts.colors) :
-		tty.isatty(process.stderr.fd);
-}
+            } else if (resCode == undefined) { // Current character is not part of the sequence.
 
-/**
- * Adds ANSI color escape codes if enabled.
- *
- * @api public
- */
+                // Try default character for this sequence
+                resCode = seqObj[DEF_CHAR];
+                if (resCode !== undefined) {
+                    dbcsCode = resCode; // Found. Write it.
+                    nextChar = uCode; // Current character will be written too in the next iteration.
 
-function formatArgs(args) {
-	const {namespace: name, useColors} = this;
+                } else {
+                    // TODO: What if we have no default? (resCode == undefined)
+                    // Then, we should write first char of the sequence as-is and try the rest recursively.
+                    // Didn't do it for now because no encoding has this situation yet.
+                    // Currently, just skip the sequence and write current char.
+                }
+            }
+            seqObj = undefined;
+        }
+        else if (uCode >= 0) {  // Regular character
+            var subtable = this.encodeTable[uCode >> 8];
+            if (subtable !== undefined)
+                dbcsCode = subtable[uCode & 0xFF];
+            
+            if (dbcsCode <= SEQ_START) { // Sequence start
+                seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
+                continue;
+            }
 
-	if (useColors) {
-		const c = this.color;
-		const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
-		const prefix = `  ${colorCode};1m${name} \u001B[0m`;
+            if (dbcsCode == UNASSIGNED && this.gb18030) {
+                // Use GB18030 algorithm to find character(s) to write.
+                var idx = findIdx(this.gb18030.uChars, uCode);
+                if (idx != -1) {
+                    var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
+                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
+                    newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
+                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
+                    newBuf[j++] = 0x30 + dbcsCode;
+                    continue;
+                }
+            }
+        }
 
-		args[0] = prefix + args[0].split('\n').join('\n' + prefix);
-		args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
-	} else {
-		args[0] = getDate() + name + ' ' + args[0];
-	}
-}
+        // 3. Write dbcsCode character.
+        if (dbcsCode === UNASSIGNED)
+            dbcsCode = this.defaultCharSingleByte;
+        
+        if (dbcsCode < 0x100) {
+            newBuf[j++] = dbcsCode;
+        }
+        else if (dbcsCode < 0x10000) {
+            newBuf[j++] = dbcsCode >> 8;   // high byte
+            newBuf[j++] = dbcsCode & 0xFF; // low byte
+        }
+        else if (dbcsCode < 0x1000000) {
+            newBuf[j++] = dbcsCode >> 16;
+            newBuf[j++] = (dbcsCode >> 8) & 0xFF;
+            newBuf[j++] = dbcsCode & 0xFF;
+        } else {
+            newBuf[j++] = dbcsCode >>> 24;
+            newBuf[j++] = (dbcsCode >>> 16) & 0xFF;
+            newBuf[j++] = (dbcsCode >>> 8) & 0xFF;
+            newBuf[j++] = dbcsCode & 0xFF;
+        }
+    }
 
-function getDate() {
-	if (exports.inspectOpts.hideDate) {
-		return '';
-	}
-	return new Date().toISOString() + ' ';
+    this.seqObj = seqObj;
+    this.leadSurrogate = leadSurrogate;
+    return newBuf.slice(0, j);
 }
 
-/**
- * Invokes `util.format()` with the specified arguments and writes to stderr.
- */
+DBCSEncoder.prototype.end = function() {
+    if (this.leadSurrogate === -1 && this.seqObj === undefined)
+        return; // All clean. Most often case.
 
-function log(...args) {
-	return process.stderr.write(util.format(...args) + '\n');
-}
+    var newBuf = Buffer.alloc(10), j = 0;
 
-/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
-function save(namespaces) {
-	if (namespaces) {
-		process.env.DEBUG = namespaces;
-	} else {
-		// If you set a process.env field to null or undefined, it gets cast to the
-		// string 'null' or 'undefined'. Just delete instead.
-		delete process.env.DEBUG;
-	}
+    if (this.seqObj) { // We're in the sequence.
+        var dbcsCode = this.seqObj[DEF_CHAR];
+        if (dbcsCode !== undefined) { // Write beginning of the sequence.
+            if (dbcsCode < 0x100) {
+                newBuf[j++] = dbcsCode;
+            }
+            else {
+                newBuf[j++] = dbcsCode >> 8;   // high byte
+                newBuf[j++] = dbcsCode & 0xFF; // low byte
+            }
+        } else {
+            // See todo above.
+        }
+        this.seqObj = undefined;
+    }
+
+    if (this.leadSurrogate !== -1) {
+        // Incomplete surrogate pair - only lead surrogate found.
+        newBuf[j++] = this.defaultCharSingleByte;
+        this.leadSurrogate = -1;
+    }
+    
+    return newBuf.slice(0, j);
 }
 
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
+// Export for testing
+DBCSEncoder.prototype.findIdx = findIdx;
 
-function load() {
-	return process.env.DEBUG;
-}
 
-/**
- * Init logic for `debug` instances.
- *
- * Create a new `inspectOpts` object in case `useColors` is set
- * differently for a particular `debug` instance.
- */
+// == Decoder ==================================================================
 
-function init(debug) {
-	debug.inspectOpts = {};
+function DBCSDecoder(options, codec) {
+    // Decoder state
+    this.nodeIdx = 0;
+    this.prevBytes = [];
 
-	const keys = Object.keys(exports.inspectOpts);
-	for (let i = 0; i < keys.length; i++) {
-		debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
-	}
+    // Static data
+    this.decodeTables = codec.decodeTables;
+    this.decodeTableSeq = codec.decodeTableSeq;
+    this.defaultCharUnicode = codec.defaultCharUnicode;
+    this.gb18030 = codec.gb18030;
 }
 
-module.exports = __nccwpck_require__(40897)(exports);
+DBCSDecoder.prototype.write = function(buf) {
+    var newBuf = Buffer.alloc(buf.length*2),
+        nodeIdx = this.nodeIdx, 
+        prevBytes = this.prevBytes, prevOffset = this.prevBytes.length,
+        seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence.
+        uCode;
 
-const {formatters} = module.exports;
+    for (var i = 0, j = 0; i < buf.length; i++) {
+        var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset];
 
-/**
- * Map %o to `util.inspect()`, all on a single line.
- */
+        // Lookup in current trie node.
+        var uCode = this.decodeTables[nodeIdx][curByte];
 
-formatters.o = function (v) {
-	this.inspectOpts.colors = this.useColors;
-	return util.inspect(v, this.inspectOpts)
-		.split('\n')
-		.map(str => str.trim())
-		.join(' ');
-};
+        if (uCode >= 0) { 
+            // Normal character, just use it.
+        }
+        else if (uCode === UNASSIGNED) { // Unknown char.
+            // TODO: Callback with seq.
+            uCode = this.defaultCharUnicode.charCodeAt(0);
+            i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again.
+        }
+        else if (uCode === GB18030_CODE) {
+            if (i >= 3) {
+                var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30);
+            } else {
+                var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + 
+                          (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + 
+                          (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + 
+                          (curByte-0x30);
+            }
+            var idx = findIdx(this.gb18030.gbChars, ptr);
+            uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
+        }
+        else if (uCode <= NODE_START) { // Go to next trie node.
+            nodeIdx = NODE_START - uCode;
+            continue;
+        }
+        else if (uCode <= SEQ_START) { // Output a sequence of chars.
+            var seq = this.decodeTableSeq[SEQ_START - uCode];
+            for (var k = 0; k < seq.length - 1; k++) {
+                uCode = seq[k];
+                newBuf[j++] = uCode & 0xFF;
+                newBuf[j++] = uCode >> 8;
+            }
+            uCode = seq[seq.length-1];
+        }
+        else
+            throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
 
-/**
- * Map %O to `util.inspect()`, allowing multiple lines if needed.
- */
+        // Write the character to buffer, handling higher planes using surrogate pair.
+        if (uCode >= 0x10000) { 
+            uCode -= 0x10000;
+            var uCodeLead = 0xD800 | (uCode >> 10);
+            newBuf[j++] = uCodeLead & 0xFF;
+            newBuf[j++] = uCodeLead >> 8;
 
-formatters.O = function (v) {
-	this.inspectOpts.colors = this.useColors;
-	return util.inspect(v, this.inspectOpts);
-};
+            uCode = 0xDC00 | (uCode & 0x3FF);
+        }
+        newBuf[j++] = uCode & 0xFF;
+        newBuf[j++] = uCode >> 8;
 
+        // Reset trie node.
+        nodeIdx = 0; seqStart = i+1;
+    }
 
-/***/ }),
+    this.nodeIdx = nodeIdx;
+    this.prevBytes = (seqStart >= 0)
+        ? Array.prototype.slice.call(buf, seqStart)
+        : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));
 
-/***/ 14150:
-/***/ ((__unused_webpack_module, exports) => {
+    return newBuf.slice(0, j).toString('ucs2');
+}
 
-"use strict";
+DBCSDecoder.prototype.end = function() {
+    var ret = '';
 
+    // Try to parse all remaining chars.
+    while (this.prevBytes.length > 0) {
+        // Skip 1 character in the buffer.
+        ret += this.defaultCharUnicode;
+        var bytesArr = this.prevBytes.slice(1);
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+        // Parse remaining as usual.
+        this.prevBytes = [];
+        this.nodeIdx = 0;
+        if (bytesArr.length > 0)
+            ret += this.write(bytesArr);
+    }
 
-class Deprecation extends Error {
-  constructor(message) {
-    super(message); // Maintains proper stack trace (only available on V8)
+    this.prevBytes = [];
+    this.nodeIdx = 0;
+    return ret;
+}
 
-    /* istanbul ignore next */
+// Binary search for GB18030. Returns largest i such that table[i] <= val.
+function findIdx(table, val) {
+    if (table[0] > val)
+        return -1;
 
-    if (Error.captureStackTrace) {
-      Error.captureStackTrace(this, this.constructor);
+    var l = 0, r = table.length;
+    while (l < r-1) { // always table[l] <= val < table[r]
+        var mid = l + ((r-l+1) >> 1);
+        if (table[mid] <= val)
+            l = mid;
+        else
+            r = mid;
     }
-
-    this.name = 'Deprecation';
-  }
-
+    return l;
 }
 
-exports.Deprecation = Deprecation;
 
 
 /***/ }),
 
-/***/ 24056:
+/***/ 11802:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
 
-var iconvLite = __nccwpck_require__(31748);
+// Description of supported double byte encodings and aliases.
+// Tables are not require()-d until they are needed to speed up library load.
+// require()-s are direct to support Browserify.
 
-// Expose to the world
-module.exports.C = convert;
+module.exports = {
+    
+    // == Japanese/ShiftJIS ====================================================
+    // All japanese encodings are based on JIS X set of standards:
+    // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
+    // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. 
+    //              Has several variations in 1978, 1983, 1990 and 1997.
+    // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
+    // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
+    //              2 planes, first is superset of 0208, second - revised 0212.
+    //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
 
-/**
- * Convert encoding of an UTF-8 string or a buffer
- *
- * @param {String|Buffer} str String to be converted
- * @param {String} to Encoding to be converted to
- * @param {String} [from='UTF-8'] Encoding to be converted from
- * @return {Buffer} Encoded string
- */
-function convert(str, to, from) {
-    from = checkEncoding(from || 'UTF-8');
-    to = checkEncoding(to || 'UTF-8');
-    str = str || '';
+    // Byte encodings are:
+    //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
+    //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
+    //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
+    //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
+    //               0x00-0x7F       - lower part of 0201
+    //               0x8E, 0xA1-0xDF - upper part of 0201
+    //               (0xA1-0xFE)x2   - 0208 plane (94x94).
+    //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
+    //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
+    //               Used as-is in ISO2022 family.
+    //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, 
+    //                0201-1976 Roman, 0208-1978, 0208-1983.
+    //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
+    //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
+    //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
+    //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
+    //
+    // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
+    //
+    // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
 
-    var result;
+    'shiftjis': {
+        type: '_dbcs',
+        table: function() { return __nccwpck_require__(40679) },
+        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
+        encodeSkipVals: [{from: 0xED40, to: 0xF940}],
+    },
+    'csshiftjis': 'shiftjis',
+    'mskanji': 'shiftjis',
+    'sjis': 'shiftjis',
+    'windows31j': 'shiftjis',
+    'ms31j': 'shiftjis',
+    'xsjis': 'shiftjis',
+    'windows932': 'shiftjis',
+    'ms932': 'shiftjis',
+    '932': 'shiftjis',
+    'cp932': 'shiftjis',
 
-    if (from !== 'UTF-8' && typeof str === 'string') {
-        str = Buffer.from(str, 'binary');
-    }
+    'eucjp': {
+        type: '_dbcs',
+        table: function() { return __nccwpck_require__(56406) },
+        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
+    },
 
-    if (from === to) {
-        if (typeof str === 'string') {
-            result = Buffer.from(str);
-        } else {
-            result = str;
-        }
-    } else {
-        try {
-            result = convertIconvLite(str, to, from);
-        } catch (E) {
-            console.error(E);
-            result = str;
-        }
-    }
+    // TODO: KDDI extension to Shift_JIS
+    // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
+    // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
 
-    if (typeof result === 'string') {
-        result = Buffer.from(result, 'utf-8');
-    }
 
-    return result;
-}
+    // == Chinese/GBK ==========================================================
+    // http://en.wikipedia.org/wiki/GBK
+    // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
 
-/**
- * Convert encoding of astring with iconv-lite
- *
- * @param {String|Buffer} str String to be converted
- * @param {String} to Encoding to be converted to
- * @param {String} [from='UTF-8'] Encoding to be converted from
- * @return {Buffer} Encoded string
- */
-function convertIconvLite(str, to, from) {
-    if (to === 'UTF-8') {
-        return iconvLite.decode(str, from);
-    } else if (from === 'UTF-8') {
-        return iconvLite.encode(str, to);
-    } else {
-        return iconvLite.encode(iconvLite.decode(str, from), to);
-    }
-}
+    // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
+    'gb2312': 'cp936',
+    'gb231280': 'cp936',
+    'gb23121980': 'cp936',
+    'csgb2312': 'cp936',
+    'csiso58gb231280': 'cp936',
+    'euccn': 'cp936',
 
-/**
- * Converts charset name if needed
- *
- * @param {String} name Character set
- * @return {String} Character set name
- */
-function checkEncoding(name) {
-    return (name || '')
-        .toString()
-        .trim()
-        .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1')
-        .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1')
-        .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1')
-        .replace(/^ks_c_5601\-1987$/i, 'CP949')
-        .replace(/^us[\-_]?ascii$/i, 'ASCII')
-        .toUpperCase();
-}
+    // Microsoft's CP936 is a subset and approximation of GBK.
+    'windows936': 'cp936',
+    'ms936': 'cp936',
+    '936': 'cp936',
+    'cp936': {
+        type: '_dbcs',
+        table: function() { return __nccwpck_require__(74488) },
+    },
 
+    // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
+    'gbk': {
+        type: '_dbcs',
+        table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) },
+    },
+    'xgbk': 'gbk',
+    'isoir58': 'gbk',
 
-/***/ }),
+    // GB18030 is an algorithmic extension of GBK.
+    // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
+    // http://icu-project.org/docs/papers/gb18030.html
+    // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
+    // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
+    'gb18030': {
+        type: '_dbcs',
+        table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) },
+        gb18030: function() { return __nccwpck_require__(99129) },
+        encodeSkipVals: [0x80],
+        encodeAdd: {'€': 0xA2E3},
+    },
 
-/***/ 14339:
-/***/ ((module) => {
+    'chinese': 'gb18030',
 
-"use strict";
 
+    // == Korean ===============================================================
+    // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
+    'windows949': 'cp949',
+    'ms949': 'cp949',
+    '949': 'cp949',
+    'cp949': {
+        type: '_dbcs',
+        table: function() { return __nccwpck_require__(21166) },
+    },
 
-function assign(obj, props) {
-    for (const key in props) {
-        Object.defineProperty(obj, key, {
-            value: props[key],
-            enumerable: true,
-            configurable: true,
-        });
-    }
+    'cseuckr': 'cp949',
+    'csksc56011987': 'cp949',
+    'euckr': 'cp949',
+    'isoir149': 'cp949',
+    'korean': 'cp949',
+    'ksc56011987': 'cp949',
+    'ksc56011989': 'cp949',
+    'ksc5601': 'cp949',
 
-    return obj;
-}
 
-function createError(err, code, props) {
-    if (!err || typeof err === 'string') {
-        throw new TypeError('Please pass an Error to err-code');
-    }
+    // == Big5/Taiwan/Hong Kong ================================================
+    // There are lots of tables for Big5 and cp950. Please see the following links for history:
+    // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
+    // Variations, in roughly number of defined chars:
+    //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
+    //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
+    //  * Big5-2003 (Taiwan standard) almost superset of cp950.
+    //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
+    //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. 
+    //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
+    //    Plus, it has 4 combining sequences.
+    //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
+    //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
+    //    Implementations are not consistent within browsers; sometimes labeled as just big5.
+    //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
+    //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
+    //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
+    //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
+    //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
+    // 
+    // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
+    // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
 
-    if (!props) {
-        props = {};
-    }
+    'windows950': 'cp950',
+    'ms950': 'cp950',
+    '950': 'cp950',
+    'cp950': {
+        type: '_dbcs',
+        table: function() { return __nccwpck_require__(72324) },
+    },
 
-    if (typeof code === 'object') {
-        props = code;
-        code = undefined;
-    }
+    // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
+    'big5': 'big5hkscs',
+    'big5hkscs': {
+        type: '_dbcs',
+        table: function() { return (__nccwpck_require__(72324).concat)(__nccwpck_require__(43267)) },
+        encodeSkipVals: [
+            // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of
+            // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU.
+            // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter.
+            0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe,
+            0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca,
+            0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62,
+            0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef,
+            0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed,
 
-    if (code != null) {
-        props.code = code;
-    }
+            // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345
+            0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce,
+        ],
+    },
 
-    try {
-        return assign(err, props);
-    } catch (_) {
-        props.message = err.message;
-        props.stack = err.stack;
+    'cnbig5': 'big5hkscs',
+    'csbig5': 'big5hkscs',
+    'xxbig5': 'big5hkscs',
+};
 
-        const ErrClass = function () {};
 
-        ErrClass.prototype = Object.create(Object.getPrototypeOf(err));
+/***/ }),
+
+/***/ 27585:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+
+// Update this array if you add/rename/remove files in this directory.
+// We support Browserify by skipping automatic module discovery and requiring modules directly.
+var modules = [
+    __nccwpck_require__(72356),
+    __nccwpck_require__(62021),
+    __nccwpck_require__(8771),
+    __nccwpck_require__(28231),
+    __nccwpck_require__(82473),
+    __nccwpck_require__(97083),
+    __nccwpck_require__(69487),
+    __nccwpck_require__(7978),
+    __nccwpck_require__(11802),
+];
 
-        return assign(new ErrClass(), props);
-    }
+// Put all encoding/alias/codec definitions to single object and export it.
+for (var i = 0; i < modules.length; i++) {
+    var module = modules[i];
+    for (var enc in module)
+        if (Object.prototype.hasOwnProperty.call(module, enc))
+            exports[enc] = module[enc];
 }
 
-module.exports = createError;
-
 
 /***/ }),
 
-/***/ 25032:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 72356:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
-const { Minipass } = __nccwpck_require__(78275)
-const EE = (__nccwpck_require__(24434).EventEmitter)
-const fs = __nccwpck_require__(79896)
+var Buffer = (__nccwpck_require__(12803).Buffer);
 
-const writev = fs.writev
+// Export Node.js internal encodings.
 
-const _autoClose = Symbol('_autoClose')
-const _close = Symbol('_close')
-const _ended = Symbol('_ended')
-const _fd = Symbol('_fd')
-const _finished = Symbol('_finished')
-const _flags = Symbol('_flags')
-const _flush = Symbol('_flush')
-const _handleChunk = Symbol('_handleChunk')
-const _makeBuf = Symbol('_makeBuf')
-const _mode = Symbol('_mode')
-const _needDrain = Symbol('_needDrain')
-const _onerror = Symbol('_onerror')
-const _onopen = Symbol('_onopen')
-const _onread = Symbol('_onread')
-const _onwrite = Symbol('_onwrite')
-const _open = Symbol('_open')
-const _path = Symbol('_path')
-const _pos = Symbol('_pos')
-const _queue = Symbol('_queue')
-const _read = Symbol('_read')
-const _readSize = Symbol('_readSize')
-const _reading = Symbol('_reading')
-const _remain = Symbol('_remain')
-const _size = Symbol('_size')
-const _write = Symbol('_write')
-const _writing = Symbol('_writing')
-const _defaultFlag = Symbol('_defaultFlag')
-const _errored = Symbol('_errored')
+module.exports = {
+    // Encodings
+    utf8:   { type: "_internal", bomAware: true},
+    cesu8:  { type: "_internal", bomAware: true},
+    unicode11utf8: "utf8",
 
-class ReadStream extends Minipass {
-  constructor (path, opt) {
-    opt = opt || {}
-    super(opt)
+    ucs2:   { type: "_internal", bomAware: true},
+    utf16le: "ucs2",
 
-    this.readable = true
-    this.writable = false
+    binary: { type: "_internal" },
+    base64: { type: "_internal" },
+    hex:    { type: "_internal" },
 
-    if (typeof path !== 'string') {
-      throw new TypeError('path must be a string')
-    }
+    // Codec.
+    _internal: InternalCodec,
+};
 
-    this[_errored] = false
-    this[_fd] = typeof opt.fd === 'number' ? opt.fd : null
-    this[_path] = path
-    this[_readSize] = opt.readSize || 16 * 1024 * 1024
-    this[_reading] = false
-    this[_size] = typeof opt.size === 'number' ? opt.size : Infinity
-    this[_remain] = this[_size]
-    this[_autoClose] = typeof opt.autoClose === 'boolean' ?
-      opt.autoClose : true
+//------------------------------------------------------------------------------
 
-    if (typeof this[_fd] === 'number') {
-      this[_read]()
-    } else {
-      this[_open]()
+function InternalCodec(codecOptions, iconv) {
+    this.enc = codecOptions.encodingName;
+    this.bomAware = codecOptions.bomAware;
+
+    if (this.enc === "base64")
+        this.encoder = InternalEncoderBase64;
+    else if (this.enc === "cesu8") {
+        this.enc = "utf8"; // Use utf8 for decoding.
+        this.encoder = InternalEncoderCesu8;
+
+        // Add decoder for versions of Node not supporting CESU-8
+        if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
+            this.decoder = InternalDecoderCesu8;
+            this.defaultCharUnicode = iconv.defaultCharUnicode;
+        }
     }
-  }
+}
 
-  get fd () {
-    return this[_fd]
-  }
+InternalCodec.prototype.encoder = InternalEncoder;
+InternalCodec.prototype.decoder = InternalDecoder;
 
-  get path () {
-    return this[_path]
-  }
+//------------------------------------------------------------------------------
 
-  write () {
-    throw new TypeError('this is a readable stream')
-  }
+// We use node.js internal decoder. Its signature is the same as ours.
+var StringDecoder = (__nccwpck_require__(13193).StringDecoder);
 
-  end () {
-    throw new TypeError('this is a readable stream')
-  }
+if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
+    StringDecoder.prototype.end = function() {};
 
-  [_open] () {
-    fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd))
-  }
 
-  [_onopen] (er, fd) {
-    if (er) {
-      this[_onerror](er)
-    } else {
-      this[_fd] = fd
-      this.emit('open', fd)
-      this[_read]()
+function InternalDecoder(options, codec) {
+    this.decoder = new StringDecoder(codec.enc);
+}
+
+InternalDecoder.prototype.write = function(buf) {
+    if (!Buffer.isBuffer(buf)) {
+        buf = Buffer.from(buf);
     }
-  }
 
-  [_makeBuf] () {
-    return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]))
-  }
+    return this.decoder.write(buf);
+}
 
-  [_read] () {
-    if (!this[_reading]) {
-      this[_reading] = true
-      const buf = this[_makeBuf]()
-      /* istanbul ignore if */
-      if (buf.length === 0) {
-        return process.nextTick(() => this[_onread](null, 0, buf))
-      }
-      fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) =>
-        this[_onread](er, br, b))
-    }
-  }
+InternalDecoder.prototype.end = function() {
+    return this.decoder.end();
+}
 
-  [_onread] (er, br, buf) {
-    this[_reading] = false
-    if (er) {
-      this[_onerror](er)
-    } else if (this[_handleChunk](br, buf)) {
-      this[_read]()
-    }
-  }
 
-  [_close] () {
-    if (this[_autoClose] && typeof this[_fd] === 'number') {
-      const fd = this[_fd]
-      this[_fd] = null
-      fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'))
-    }
-  }
+//------------------------------------------------------------------------------
+// Encoder is mostly trivial
 
-  [_onerror] (er) {
-    this[_reading] = true
-    this[_close]()
-    this.emit('error', er)
-  }
+function InternalEncoder(options, codec) {
+    this.enc = codec.enc;
+}
 
-  [_handleChunk] (br, buf) {
-    let ret = false
-    // no effect if infinite
-    this[_remain] -= br
-    if (br > 0) {
-      ret = super.write(br < buf.length ? buf.slice(0, br) : buf)
-    }
+InternalEncoder.prototype.write = function(str) {
+    return Buffer.from(str, this.enc);
+}
 
-    if (br === 0 || this[_remain] <= 0) {
-      ret = false
-      this[_close]()
-      super.end()
-    }
+InternalEncoder.prototype.end = function() {
+}
 
-    return ret
-  }
 
-  emit (ev, data) {
-    switch (ev) {
-      case 'prefinish':
-      case 'finish':
-        break
+//------------------------------------------------------------------------------
+// Except base64 encoder, which must keep its state.
 
-      case 'drain':
-        if (typeof this[_fd] === 'number') {
-          this[_read]()
-        }
-        break
+function InternalEncoderBase64(options, codec) {
+    this.prevStr = '';
+}
 
-      case 'error':
-        if (this[_errored]) {
-          return
-        }
-        this[_errored] = true
-        return super.emit(ev, data)
+InternalEncoderBase64.prototype.write = function(str) {
+    str = this.prevStr + str;
+    var completeQuads = str.length - (str.length % 4);
+    this.prevStr = str.slice(completeQuads);
+    str = str.slice(0, completeQuads);
 
-      default:
-        return super.emit(ev, data)
-    }
-  }
+    return Buffer.from(str, "base64");
 }
 
-class ReadStreamSync extends ReadStream {
-  [_open] () {
-    let threw = true
-    try {
-      this[_onopen](null, fs.openSync(this[_path], 'r'))
-      threw = false
-    } finally {
-      if (threw) {
-        this[_close]()
-      }
-    }
-  }
+InternalEncoderBase64.prototype.end = function() {
+    return Buffer.from(this.prevStr, "base64");
+}
 
-  [_read] () {
-    let threw = true
-    try {
-      if (!this[_reading]) {
-        this[_reading] = true
-        do {
-          const buf = this[_makeBuf]()
-          /* istanbul ignore next */
-          const br = buf.length === 0 ? 0
-            : fs.readSync(this[_fd], buf, 0, buf.length, null)
-          if (!this[_handleChunk](br, buf)) {
-            break
-          }
-        } while (true)
-        this[_reading] = false
-      }
-      threw = false
-    } finally {
-      if (threw) {
-        this[_close]()
-      }
-    }
-  }
 
-  [_close] () {
-    if (this[_autoClose] && typeof this[_fd] === 'number') {
-      const fd = this[_fd]
-      this[_fd] = null
-      fs.closeSync(fd)
-      this.emit('close')
+//------------------------------------------------------------------------------
+// CESU-8 encoder is also special.
+
+function InternalEncoderCesu8(options, codec) {
+}
+
+InternalEncoderCesu8.prototype.write = function(str) {
+    var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
+    for (var i = 0; i < str.length; i++) {
+        var charCode = str.charCodeAt(i);
+        // Naive implementation, but it works because CESU-8 is especially easy
+        // to convert from UTF-16 (which all JS strings are encoded in).
+        if (charCode < 0x80)
+            buf[bufIdx++] = charCode;
+        else if (charCode < 0x800) {
+            buf[bufIdx++] = 0xC0 + (charCode >>> 6);
+            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
+        }
+        else { // charCode will always be < 0x10000 in javascript.
+            buf[bufIdx++] = 0xE0 + (charCode >>> 12);
+            buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
+            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
+        }
     }
-  }
+    return buf.slice(0, bufIdx);
 }
 
-class WriteStream extends EE {
-  constructor (path, opt) {
-    opt = opt || {}
-    super(opt)
-    this.readable = false
-    this.writable = true
-    this[_errored] = false
-    this[_writing] = false
-    this[_ended] = false
-    this[_needDrain] = false
-    this[_queue] = []
-    this[_path] = path
-    this[_fd] = typeof opt.fd === 'number' ? opt.fd : null
-    this[_mode] = opt.mode === undefined ? 0o666 : opt.mode
-    this[_pos] = typeof opt.start === 'number' ? opt.start : null
-    this[_autoClose] = typeof opt.autoClose === 'boolean' ?
-      opt.autoClose : true
+InternalEncoderCesu8.prototype.end = function() {
+}
 
-    // truncating makes no sense when writing into the middle
-    const defaultFlag = this[_pos] !== null ? 'r+' : 'w'
-    this[_defaultFlag] = opt.flags === undefined
-    this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags
+//------------------------------------------------------------------------------
+// CESU-8 decoder is not implemented in Node v4.0+
 
-    if (this[_fd] === null) {
-      this[_open]()
-    }
-  }
+function InternalDecoderCesu8(options, codec) {
+    this.acc = 0;
+    this.contBytes = 0;
+    this.accBytes = 0;
+    this.defaultCharUnicode = codec.defaultCharUnicode;
+}
 
-  emit (ev, data) {
-    if (ev === 'error') {
-      if (this[_errored]) {
-        return
-      }
-      this[_errored] = true
+InternalDecoderCesu8.prototype.write = function(buf) {
+    var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, 
+        res = '';
+    for (var i = 0; i < buf.length; i++) {
+        var curByte = buf[i];
+        if ((curByte & 0xC0) !== 0x80) { // Leading byte
+            if (contBytes > 0) { // Previous code is invalid
+                res += this.defaultCharUnicode;
+                contBytes = 0;
+            }
+
+            if (curByte < 0x80) { // Single-byte code
+                res += String.fromCharCode(curByte);
+            } else if (curByte < 0xE0) { // Two-byte code
+                acc = curByte & 0x1F;
+                contBytes = 1; accBytes = 1;
+            } else if (curByte < 0xF0) { // Three-byte code
+                acc = curByte & 0x0F;
+                contBytes = 2; accBytes = 1;
+            } else { // Four or more are not supported for CESU-8.
+                res += this.defaultCharUnicode;
+            }
+        } else { // Continuation byte
+            if (contBytes > 0) { // We're waiting for it.
+                acc = (acc << 6) | (curByte & 0x3f);
+                contBytes--; accBytes++;
+                if (contBytes === 0) {
+                    // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
+                    if (accBytes === 2 && acc < 0x80 && acc > 0)
+                        res += this.defaultCharUnicode;
+                    else if (accBytes === 3 && acc < 0x800)
+                        res += this.defaultCharUnicode;
+                    else
+                        // Actually add character.
+                        res += String.fromCharCode(acc);
+                }
+            } else { // Unexpected continuation byte
+                res += this.defaultCharUnicode;
+            }
+        }
     }
-    return super.emit(ev, data)
-  }
+    this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
+    return res;
+}
 
-  get fd () {
-    return this[_fd]
-  }
+InternalDecoderCesu8.prototype.end = function() {
+    var res = 0;
+    if (this.contBytes > 0)
+        res += this.defaultCharUnicode;
+    return res;
+}
 
-  get path () {
-    return this[_path]
-  }
 
-  [_onerror] (er) {
-    this[_close]()
-    this[_writing] = true
-    this.emit('error', er)
-  }
+/***/ }),
 
-  [_open] () {
-    fs.open(this[_path], this[_flags], this[_mode],
-      (er, fd) => this[_onopen](er, fd))
-  }
+/***/ 82473:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-  [_onopen] (er, fd) {
-    if (this[_defaultFlag] &&
-        this[_flags] === 'r+' &&
-        er && er.code === 'ENOENT') {
-      this[_flags] = 'w'
-      this[_open]()
-    } else if (er) {
-      this[_onerror](er)
-    } else {
-      this[_fd] = fd
-      this.emit('open', fd)
-      if (!this[_writing]) {
-        this[_flush]()
-      }
-    }
-  }
+"use strict";
 
-  end (buf, enc) {
-    if (buf) {
-      this.write(buf, enc)
-    }
+var Buffer = (__nccwpck_require__(12803).Buffer);
 
-    this[_ended] = true
+// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
+// correspond to encoded bytes (if 128 - then lower half is ASCII). 
 
-    // synthetic after-write logic, where drain/finish live
-    if (!this[_writing] && !this[_queue].length &&
-        typeof this[_fd] === 'number') {
-      this[_onwrite](null, 0)
+exports._sbcs = SBCSCodec;
+function SBCSCodec(codecOptions, iconv) {
+    if (!codecOptions)
+        throw new Error("SBCS codec is called without the data.")
+    
+    // Prepare char buffer for decoding.
+    if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
+        throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
+    
+    if (codecOptions.chars.length === 128) {
+        var asciiString = "";
+        for (var i = 0; i < 128; i++)
+            asciiString += String.fromCharCode(i);
+        codecOptions.chars = asciiString + codecOptions.chars;
     }
-    return this
-  }
 
-  write (buf, enc) {
-    if (typeof buf === 'string') {
-      buf = Buffer.from(buf, enc)
-    }
+    this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
+    
+    // Encoding buffer.
+    var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
 
-    if (this[_ended]) {
-      this.emit('error', new Error('write() after end()'))
-      return false
-    }
+    for (var i = 0; i < codecOptions.chars.length; i++)
+        encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
 
-    if (this[_fd] === null || this[_writing] || this[_queue].length) {
-      this[_queue].push(buf)
-      this[_needDrain] = true
-      return false
-    }
+    this.encodeBuf = encodeBuf;
+}
 
-    this[_writing] = true
-    this[_write](buf)
-    return true
-  }
+SBCSCodec.prototype.encoder = SBCSEncoder;
+SBCSCodec.prototype.decoder = SBCSDecoder;
 
-  [_write] (buf) {
-    fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) =>
-      this[_onwrite](er, bw))
-  }
 
-  [_onwrite] (er, bw) {
-    if (er) {
-      this[_onerror](er)
-    } else {
-      if (this[_pos] !== null) {
-        this[_pos] += bw
-      }
-      if (this[_queue].length) {
-        this[_flush]()
-      } else {
-        this[_writing] = false
+function SBCSEncoder(options, codec) {
+    this.encodeBuf = codec.encodeBuf;
+}
+
+SBCSEncoder.prototype.write = function(str) {
+    var buf = Buffer.alloc(str.length);
+    for (var i = 0; i < str.length; i++)
+        buf[i] = this.encodeBuf[str.charCodeAt(i)];
+    
+    return buf;
+}
 
-        if (this[_ended] && !this[_finished]) {
-          this[_finished] = true
-          this[_close]()
-          this.emit('finish')
-        } else if (this[_needDrain]) {
-          this[_needDrain] = false
-          this.emit('drain')
-        }
-      }
-    }
-  }
+SBCSEncoder.prototype.end = function() {
+}
 
-  [_flush] () {
-    if (this[_queue].length === 0) {
-      if (this[_ended]) {
-        this[_onwrite](null, 0)
-      }
-    } else if (this[_queue].length === 1) {
-      this[_write](this[_queue].pop())
-    } else {
-      const iovec = this[_queue]
-      this[_queue] = []
-      writev(this[_fd], iovec, this[_pos],
-        (er, bw) => this[_onwrite](er, bw))
-    }
-  }
 
-  [_close] () {
-    if (this[_autoClose] && typeof this[_fd] === 'number') {
-      const fd = this[_fd]
-      this[_fd] = null
-      fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'))
-    }
-  }
+function SBCSDecoder(options, codec) {
+    this.decodeBuf = codec.decodeBuf;
 }
 
-class WriteStreamSync extends WriteStream {
-  [_open] () {
-    let fd
-    // only wrap in a try{} block if we know we'll retry, to avoid
-    // the rethrow obscuring the error's source frame in most cases.
-    if (this[_defaultFlag] && this[_flags] === 'r+') {
-      try {
-        fd = fs.openSync(this[_path], this[_flags], this[_mode])
-      } catch (er) {
-        if (er.code === 'ENOENT') {
-          this[_flags] = 'w'
-          return this[_open]()
-        } else {
-          throw er
-        }
-      }
-    } else {
-      fd = fs.openSync(this[_path], this[_flags], this[_mode])
+SBCSDecoder.prototype.write = function(buf) {
+    // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
+    var decodeBuf = this.decodeBuf;
+    var newBuf = Buffer.alloc(buf.length*2);
+    var idx1 = 0, idx2 = 0;
+    for (var i = 0; i < buf.length; i++) {
+        idx1 = buf[i]*2; idx2 = i*2;
+        newBuf[idx2] = decodeBuf[idx1];
+        newBuf[idx2+1] = decodeBuf[idx1+1];
     }
+    return newBuf.toString('ucs2');
+}
 
-    this[_onopen](null, fd)
-  }
+SBCSDecoder.prototype.end = function() {
+}
 
-  [_close] () {
-    if (this[_autoClose] && typeof this[_fd] === 'number') {
-      const fd = this[_fd]
-      this[_fd] = null
-      fs.closeSync(fd)
-      this.emit('close')
-    }
-  }
 
-  [_write] (buf) {
-    // throw the original, but try to close if it fails
-    let threw = true
-    try {
-      this[_onwrite](null,
-        fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos]))
-      threw = false
-    } finally {
-      if (threw) {
-        try {
-          this[_close]()
-        } catch {
-          // ok error
-        }
-      }
-    }
+/***/ }),
+
+/***/ 69487:
+/***/ ((module) => {
+
+"use strict";
+
+
+// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
+module.exports = {
+  "437": "cp437",
+  "737": "cp737",
+  "775": "cp775",
+  "850": "cp850",
+  "852": "cp852",
+  "855": "cp855",
+  "856": "cp856",
+  "857": "cp857",
+  "858": "cp858",
+  "860": "cp860",
+  "861": "cp861",
+  "862": "cp862",
+  "863": "cp863",
+  "864": "cp864",
+  "865": "cp865",
+  "866": "cp866",
+  "869": "cp869",
+  "874": "windows874",
+  "922": "cp922",
+  "1046": "cp1046",
+  "1124": "cp1124",
+  "1125": "cp1125",
+  "1129": "cp1129",
+  "1133": "cp1133",
+  "1161": "cp1161",
+  "1162": "cp1162",
+  "1163": "cp1163",
+  "1250": "windows1250",
+  "1251": "windows1251",
+  "1252": "windows1252",
+  "1253": "windows1253",
+  "1254": "windows1254",
+  "1255": "windows1255",
+  "1256": "windows1256",
+  "1257": "windows1257",
+  "1258": "windows1258",
+  "28591": "iso88591",
+  "28592": "iso88592",
+  "28593": "iso88593",
+  "28594": "iso88594",
+  "28595": "iso88595",
+  "28596": "iso88596",
+  "28597": "iso88597",
+  "28598": "iso88598",
+  "28599": "iso88599",
+  "28600": "iso885910",
+  "28601": "iso885911",
+  "28603": "iso885913",
+  "28604": "iso885914",
+  "28605": "iso885915",
+  "28606": "iso885916",
+  "windows874": {
+    "type": "_sbcs",
+    "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
+  },
+  "win874": "windows874",
+  "cp874": "windows874",
+  "windows1250": {
+    "type": "_sbcs",
+    "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
+  },
+  "win1250": "windows1250",
+  "cp1250": "windows1250",
+  "windows1251": {
+    "type": "_sbcs",
+    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
+  },
+  "win1251": "windows1251",
+  "cp1251": "windows1251",
+  "windows1252": {
+    "type": "_sbcs",
+    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
+  },
+  "win1252": "windows1252",
+  "cp1252": "windows1252",
+  "windows1253": {
+    "type": "_sbcs",
+    "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
+  },
+  "win1253": "windows1253",
+  "cp1253": "windows1253",
+  "windows1254": {
+    "type": "_sbcs",
+    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
+  },
+  "win1254": "windows1254",
+  "cp1254": "windows1254",
+  "windows1255": {
+    "type": "_sbcs",
+    "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
+  },
+  "win1255": "windows1255",
+  "cp1255": "windows1255",
+  "windows1256": {
+    "type": "_sbcs",
+    "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"
+  },
+  "win1256": "windows1256",
+  "cp1256": "windows1256",
+  "windows1257": {
+    "type": "_sbcs",
+    "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
+  },
+  "win1257": "windows1257",
+  "cp1257": "windows1257",
+  "windows1258": {
+    "type": "_sbcs",
+    "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
+  },
+  "win1258": "windows1258",
+  "cp1258": "windows1258",
+  "iso88591": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
+  },
+  "cp28591": "iso88591",
+  "iso88592": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
+  },
+  "cp28592": "iso88592",
+  "iso88593": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
+  },
+  "cp28593": "iso88593",
+  "iso88594": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
+  },
+  "cp28594": "iso88594",
+  "iso88595": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
+  },
+  "cp28595": "iso88595",
+  "iso88596": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
+  },
+  "cp28596": "iso88596",
+  "iso88597": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
+  },
+  "cp28597": "iso88597",
+  "iso88598": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
+  },
+  "cp28598": "iso88598",
+  "iso88599": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
+  },
+  "cp28599": "iso88599",
+  "iso885910": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
+  },
+  "cp28600": "iso885910",
+  "iso885911": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
+  },
+  "cp28601": "iso885911",
+  "iso885913": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
+  },
+  "cp28603": "iso885913",
+  "iso885914": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
+  },
+  "cp28604": "iso885914",
+  "iso885915": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
+  },
+  "cp28605": "iso885915",
+  "iso885916": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
+  },
+  "cp28606": "iso885916",
+  "cp437": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+  },
+  "ibm437": "cp437",
+  "csibm437": "cp437",
+  "cp737": {
+    "type": "_sbcs",
+    "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
+  },
+  "ibm737": "cp737",
+  "csibm737": "cp737",
+  "cp775": {
+    "type": "_sbcs",
+    "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "
+  },
+  "ibm775": "cp775",
+  "csibm775": "cp775",
+  "cp850": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
+  },
+  "ibm850": "cp850",
+  "csibm850": "cp850",
+  "cp852": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "
+  },
+  "ibm852": "cp852",
+  "csibm852": "cp852",
+  "cp855": {
+    "type": "_sbcs",
+    "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "
+  },
+  "ibm855": "cp855",
+  "csibm855": "cp855",
+  "cp856": {
+    "type": "_sbcs",
+    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "
+  },
+  "ibm856": "cp856",
+  "csibm856": "cp856",
+  "cp857": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "
+  },
+  "ibm857": "cp857",
+  "csibm857": "cp857",
+  "cp858": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
+  },
+  "ibm858": "cp858",
+  "csibm858": "cp858",
+  "cp860": {
+    "type": "_sbcs",
+    "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+  },
+  "ibm860": "cp860",
+  "csibm860": "cp860",
+  "cp861": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+  },
+  "ibm861": "cp861",
+  "csibm861": "cp861",
+  "cp862": {
+    "type": "_sbcs",
+    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+  },
+  "ibm862": "cp862",
+  "csibm862": "cp862",
+  "cp863": {
+    "type": "_sbcs",
+    "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+  },
+  "ibm863": "cp863",
+  "csibm863": "cp863",
+  "cp864": {
+    "type": "_sbcs",
+    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
+  },
+  "ibm864": "cp864",
+  "csibm864": "cp864",
+  "cp865": {
+    "type": "_sbcs",
+    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+  },
+  "ibm865": "cp865",
+  "csibm865": "cp865",
+  "cp866": {
+    "type": "_sbcs",
+    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
+  },
+  "ibm866": "cp866",
+  "csibm866": "cp866",
+  "cp869": {
+    "type": "_sbcs",
+    "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "
+  },
+  "ibm869": "cp869",
+  "csibm869": "cp869",
+  "cp922": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
+  },
+  "ibm922": "cp922",
+  "csibm922": "cp922",
+  "cp1046": {
+    "type": "_sbcs",
+    "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
+  },
+  "ibm1046": "cp1046",
+  "csibm1046": "cp1046",
+  "cp1124": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
+  },
+  "ibm1124": "cp1124",
+  "csibm1124": "cp1124",
+  "cp1125": {
+    "type": "_sbcs",
+    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
+  },
+  "ibm1125": "cp1125",
+  "csibm1125": "cp1125",
+  "cp1129": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
+  },
+  "ibm1129": "cp1129",
+  "csibm1129": "cp1129",
+  "cp1133": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
+  },
+  "ibm1133": "cp1133",
+  "csibm1133": "cp1133",
+  "cp1161": {
+    "type": "_sbcs",
+    "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
+  },
+  "ibm1161": "cp1161",
+  "csibm1161": "cp1161",
+  "cp1162": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
+  },
+  "ibm1162": "cp1162",
+  "csibm1162": "cp1162",
+  "cp1163": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
+  },
+  "ibm1163": "cp1163",
+  "csibm1163": "cp1163",
+  "maccroatian": {
+    "type": "_sbcs",
+    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
+  },
+  "maccyrillic": {
+    "type": "_sbcs",
+    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
+  },
+  "macgreek": {
+    "type": "_sbcs",
+    "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
+  },
+  "maciceland": {
+    "type": "_sbcs",
+    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
+  },
+  "macroman": {
+    "type": "_sbcs",
+    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
+  },
+  "macromania": {
+    "type": "_sbcs",
+    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
+  },
+  "macthai": {
+    "type": "_sbcs",
+    "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
+  },
+  "macturkish": {
+    "type": "_sbcs",
+    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
+  },
+  "macukraine": {
+    "type": "_sbcs",
+    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
+  },
+  "koi8r": {
+    "type": "_sbcs",
+    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
+  },
+  "koi8u": {
+    "type": "_sbcs",
+    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
+  },
+  "koi8ru": {
+    "type": "_sbcs",
+    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
+  },
+  "koi8t": {
+    "type": "_sbcs",
+    "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
+  },
+  "armscii8": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
+  },
+  "rk1048": {
+    "type": "_sbcs",
+    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
+  },
+  "tcvn": {
+    "type": "_sbcs",
+    "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
+  },
+  "georgianacademy": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
+  },
+  "georgianps": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
+  },
+  "pt154": {
+    "type": "_sbcs",
+    "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
+  },
+  "viscii": {
+    "type": "_sbcs",
+    "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
+  },
+  "iso646cn": {
+    "type": "_sbcs",
+    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
+  },
+  "iso646jp": {
+    "type": "_sbcs",
+    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
+  },
+  "hproman8": {
+    "type": "_sbcs",
+    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
+  },
+  "macintosh": {
+    "type": "_sbcs",
+    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
+  },
+  "ascii": {
+    "type": "_sbcs",
+    "chars": "��������������������������������������������������������������������������������������������������������������������������������"
+  },
+  "tis620": {
+    "type": "_sbcs",
+    "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
   }
 }
 
-exports.ReadStream = ReadStream
-exports.ReadStreamSync = ReadStreamSync
-
-exports.WriteStream = WriteStream
-exports.WriteStreamSync = WriteStreamSync
-
-
-/***/ }),
-
-/***/ 83813:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = (flag, argv = process.argv) => {
-	const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
-	const position = argv.indexOf(prefix + flag);
-	const terminatorPosition = argv.indexOf('--');
-	return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
-};
-
-
 /***/ }),
 
-/***/ 12203:
+/***/ 97083:
 /***/ ((module) => {
 
 "use strict";
 
-// rfc7231 6.1
-const statusCodeCacheableByDefault = new Set([
-    200,
-    203,
-    204,
-    206,
-    300,
-    301,
-    308,
-    404,
-    405,
-    410,
-    414,
-    501,
-]);
-
-// This implementation does not understand partial responses (206)
-const understoodStatuses = new Set([
-    200,
-    203,
-    204,
-    300,
-    301,
-    302,
-    303,
-    307,
-    308,
-    404,
-    405,
-    410,
-    414,
-    501,
-]);
-
-const errorStatusCodes = new Set([
-    500,
-    502,
-    503, 
-    504,
-]);
-
-const hopByHopHeaders = {
-    date: true, // included, because we add Age update Date
-    connection: true,
-    'keep-alive': true,
-    'proxy-authenticate': true,
-    'proxy-authorization': true,
-    te: true,
-    trailer: true,
-    'transfer-encoding': true,
-    upgrade: true,
-};
-
-const excludedFromRevalidationUpdate = {
-    // Since the old body is reused, it doesn't make sense to change properties of the body
-    'content-length': true,
-    'content-encoding': true,
-    'transfer-encoding': true,
-    'content-range': true,
-};
-
-function toNumberOrZero(s) {
-    const n = parseInt(s, 10);
-    return isFinite(n) ? n : 0;
-}
-
-// RFC 5861
-function isErrorResponse(response) {
-    // consider undefined response as faulty
-    if(!response) {
-        return true
-    }
-    return errorStatusCodes.has(response.status);
-}
-
-function parseCacheControl(header) {
-    const cc = {};
-    if (!header) return cc;
-
-    // TODO: When there is more than one value present for a given directive (e.g., two Expires header fields, multiple Cache-Control: max-age directives),
-    // the directive's value is considered invalid. Caches are encouraged to consider responses that have invalid freshness information to be stale
-    const parts = header.trim().split(/,/);
-    for (const part of parts) {
-        const [k, v] = part.split(/=/, 2);
-        cc[k.trim()] = v === undefined ? true : v.trim().replace(/^"|"$/g, '');
-    }
-
-    return cc;
-}
-
-function formatCacheControl(cc) {
-    let parts = [];
-    for (const k in cc) {
-        const v = cc[k];
-        parts.push(v === true ? k : k + '=' + v);
-    }
-    if (!parts.length) {
-        return undefined;
-    }
-    return parts.join(', ');
-}
-
-module.exports = class CachePolicy {
-    constructor(
-        req,
-        res,
-        {
-            shared,
-            cacheHeuristic,
-            immutableMinTimeToLive,
-            ignoreCargoCult,
-            _fromObject,
-        } = {}
-    ) {
-        if (_fromObject) {
-            this._fromObject(_fromObject);
-            return;
-        }
-
-        if (!res || !res.headers) {
-            throw Error('Response headers missing');
-        }
-        this._assertRequestHasHeaders(req);
-
-        this._responseTime = this.now();
-        this._isShared = shared !== false;
-        this._cacheHeuristic =
-            undefined !== cacheHeuristic ? cacheHeuristic : 0.1; // 10% matches IE
-        this._immutableMinTtl =
-            undefined !== immutableMinTimeToLive
-                ? immutableMinTimeToLive
-                : 24 * 3600 * 1000;
-
-        this._status = 'status' in res ? res.status : 200;
-        this._resHeaders = res.headers;
-        this._rescc = parseCacheControl(res.headers['cache-control']);
-        this._method = 'method' in req ? req.method : 'GET';
-        this._url = req.url;
-        this._host = req.headers.host;
-        this._noAuthorization = !req.headers.authorization;
-        this._reqHeaders = res.headers.vary ? req.headers : null; // Don't keep all request headers if they won't be used
-        this._reqcc = parseCacheControl(req.headers['cache-control']);
-
-        // Assume that if someone uses legacy, non-standard uncecessary options they don't understand caching,
-        // so there's no point stricly adhering to the blindly copy&pasted directives.
-        if (
-            ignoreCargoCult &&
-            'pre-check' in this._rescc &&
-            'post-check' in this._rescc
-        ) {
-            delete this._rescc['pre-check'];
-            delete this._rescc['post-check'];
-            delete this._rescc['no-cache'];
-            delete this._rescc['no-store'];
-            delete this._rescc['must-revalidate'];
-            this._resHeaders = Object.assign({}, this._resHeaders, {
-                'cache-control': formatCacheControl(this._rescc),
-            });
-            delete this._resHeaders.expires;
-            delete this._resHeaders.pragma;
-        }
-
-        // When the Cache-Control header field is not present in a request, caches MUST consider the no-cache request pragma-directive
-        // as having the same effect as if "Cache-Control: no-cache" were present (see Section 5.2.1).
-        if (
-            res.headers['cache-control'] == null &&
-            /no-cache/.test(res.headers.pragma)
-        ) {
-            this._rescc['no-cache'] = true;
-        }
-    }
-
-    now() {
-        return Date.now();
-    }
-
-    storable() {
-        // The "no-store" request directive indicates that a cache MUST NOT store any part of either this request or any response to it.
-        return !!(
-            !this._reqcc['no-store'] &&
-            // A cache MUST NOT store a response to any request, unless:
-            // The request method is understood by the cache and defined as being cacheable, and
-            ('GET' === this._method ||
-                'HEAD' === this._method ||
-                ('POST' === this._method && this._hasExplicitExpiration())) &&
-            // the response status code is understood by the cache, and
-            understoodStatuses.has(this._status) &&
-            // the "no-store" cache directive does not appear in request or response header fields, and
-            !this._rescc['no-store'] &&
-            // the "private" response directive does not appear in the response, if the cache is shared, and
-            (!this._isShared || !this._rescc.private) &&
-            // the Authorization header field does not appear in the request, if the cache is shared,
-            (!this._isShared ||
-                this._noAuthorization ||
-                this._allowsStoringAuthenticated()) &&
-            // the response either:
-            // contains an Expires header field, or
-            (this._resHeaders.expires ||
-                // contains a max-age response directive, or
-                // contains a s-maxage response directive and the cache is shared, or
-                // contains a public response directive.
-                this._rescc['max-age'] ||
-                (this._isShared && this._rescc['s-maxage']) ||
-                this._rescc.public ||
-                // has a status code that is defined as cacheable by default
-                statusCodeCacheableByDefault.has(this._status))
-        );
-    }
-
-    _hasExplicitExpiration() {
-        // 4.2.1 Calculating Freshness Lifetime
-        return (
-            (this._isShared && this._rescc['s-maxage']) ||
-            this._rescc['max-age'] ||
-            this._resHeaders.expires
-        );
-    }
-
-    _assertRequestHasHeaders(req) {
-        if (!req || !req.headers) {
-            throw Error('Request headers missing');
-        }
-    }
-
-    satisfiesWithoutRevalidation(req) {
-        this._assertRequestHasHeaders(req);
-
-        // When presented with a request, a cache MUST NOT reuse a stored response, unless:
-        // the presented request does not contain the no-cache pragma (Section 5.4), nor the no-cache cache directive,
-        // unless the stored response is successfully validated (Section 4.3), and
-        const requestCC = parseCacheControl(req.headers['cache-control']);
-        if (requestCC['no-cache'] || /no-cache/.test(req.headers.pragma)) {
-            return false;
-        }
-
-        if (requestCC['max-age'] && this.age() > requestCC['max-age']) {
-            return false;
-        }
-
-        if (
-            requestCC['min-fresh'] &&
-            this.timeToLive() < 1000 * requestCC['min-fresh']
-        ) {
-            return false;
-        }
 
-        // the stored response is either:
-        // fresh, or allowed to be served stale
-        if (this.stale()) {
-            const allowsStale =
-                requestCC['max-stale'] &&
-                !this._rescc['must-revalidate'] &&
-                (true === requestCC['max-stale'] ||
-                    requestCC['max-stale'] > this.age() - this.maxAge());
-            if (!allowsStale) {
-                return false;
-            }
-        }
+// Manually added data to be used by sbcs codec in addition to generated one.
 
-        return this._requestMatches(req, false);
-    }
+module.exports = {
+    // Not supported by iconv, not sure why.
+    "10029": "maccenteuro",
+    "maccenteuro": {
+        "type": "_sbcs",
+        "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
+    },
 
-    _requestMatches(req, allowHeadMethod) {
-        // The presented effective request URI and that of the stored response match, and
-        return (
-            (!this._url || this._url === req.url) &&
-            this._host === req.headers.host &&
-            // the request method associated with the stored response allows it to be used for the presented request, and
-            (!req.method ||
-                this._method === req.method ||
-                (allowHeadMethod && 'HEAD' === req.method)) &&
-            // selecting header fields nominated by the stored response (if any) match those presented, and
-            this._varyMatches(req)
-        );
-    }
+    "808": "cp808",
+    "ibm808": "cp808",
+    "cp808": {
+        "type": "_sbcs",
+        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
+    },
 
-    _allowsStoringAuthenticated() {
-        //  following Cache-Control response directives (Section 5.2.2) have such an effect: must-revalidate, public, and s-maxage.
-        return (
-            this._rescc['must-revalidate'] ||
-            this._rescc.public ||
-            this._rescc['s-maxage']
-        );
-    }
+    "mik": {
+        "type": "_sbcs",
+        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
+    },
 
-    _varyMatches(req) {
-        if (!this._resHeaders.vary) {
-            return true;
-        }
+    "cp720": {
+        "type": "_sbcs",
+        "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0"
+    },
 
-        // A Vary header field-value of "*" always fails to match
-        if (this._resHeaders.vary === '*') {
-            return false;
-        }
+    // Aliases of generated encodings.
+    "ascii8bit": "ascii",
+    "usascii": "ascii",
+    "ansix34": "ascii",
+    "ansix341968": "ascii",
+    "ansix341986": "ascii",
+    "csascii": "ascii",
+    "cp367": "ascii",
+    "ibm367": "ascii",
+    "isoir6": "ascii",
+    "iso646us": "ascii",
+    "iso646irv": "ascii",
+    "us": "ascii",
 
-        const fields = this._resHeaders.vary
-            .trim()
-            .toLowerCase()
-            .split(/\s*,\s*/);
-        for (const name of fields) {
-            if (req.headers[name] !== this._reqHeaders[name]) return false;
-        }
-        return true;
-    }
+    "latin1": "iso88591",
+    "latin2": "iso88592",
+    "latin3": "iso88593",
+    "latin4": "iso88594",
+    "latin5": "iso88599",
+    "latin6": "iso885910",
+    "latin7": "iso885913",
+    "latin8": "iso885914",
+    "latin9": "iso885915",
+    "latin10": "iso885916",
 
-    _copyWithoutHopByHopHeaders(inHeaders) {
-        const headers = {};
-        for (const name in inHeaders) {
-            if (hopByHopHeaders[name]) continue;
-            headers[name] = inHeaders[name];
-        }
-        // 9.1.  Connection
-        if (inHeaders.connection) {
-            const tokens = inHeaders.connection.trim().split(/\s*,\s*/);
-            for (const name of tokens) {
-                delete headers[name];
-            }
-        }
-        if (headers.warning) {
-            const warnings = headers.warning.split(/,/).filter(warning => {
-                return !/^\s*1[0-9][0-9]/.test(warning);
-            });
-            if (!warnings.length) {
-                delete headers.warning;
-            } else {
-                headers.warning = warnings.join(',').trim();
-            }
-        }
-        return headers;
-    }
+    "csisolatin1": "iso88591",
+    "csisolatin2": "iso88592",
+    "csisolatin3": "iso88593",
+    "csisolatin4": "iso88594",
+    "csisolatincyrillic": "iso88595",
+    "csisolatinarabic": "iso88596",
+    "csisolatingreek" : "iso88597",
+    "csisolatinhebrew": "iso88598",
+    "csisolatin5": "iso88599",
+    "csisolatin6": "iso885910",
 
-    responseHeaders() {
-        const headers = this._copyWithoutHopByHopHeaders(this._resHeaders);
-        const age = this.age();
+    "l1": "iso88591",
+    "l2": "iso88592",
+    "l3": "iso88593",
+    "l4": "iso88594",
+    "l5": "iso88599",
+    "l6": "iso885910",
+    "l7": "iso885913",
+    "l8": "iso885914",
+    "l9": "iso885915",
+    "l10": "iso885916",
 
-        // A cache SHOULD generate 113 warning if it heuristically chose a freshness
-        // lifetime greater than 24 hours and the response's age is greater than 24 hours.
-        if (
-            age > 3600 * 24 &&
-            !this._hasExplicitExpiration() &&
-            this.maxAge() > 3600 * 24
-        ) {
-            headers.warning =
-                (headers.warning ? `${headers.warning}, ` : '') +
-                '113 - "rfc7234 5.5.4"';
-        }
-        headers.age = `${Math.round(age)}`;
-        headers.date = new Date(this.now()).toUTCString();
-        return headers;
-    }
+    "isoir14": "iso646jp",
+    "isoir57": "iso646cn",
+    "isoir100": "iso88591",
+    "isoir101": "iso88592",
+    "isoir109": "iso88593",
+    "isoir110": "iso88594",
+    "isoir144": "iso88595",
+    "isoir127": "iso88596",
+    "isoir126": "iso88597",
+    "isoir138": "iso88598",
+    "isoir148": "iso88599",
+    "isoir157": "iso885910",
+    "isoir166": "tis620",
+    "isoir179": "iso885913",
+    "isoir199": "iso885914",
+    "isoir203": "iso885915",
+    "isoir226": "iso885916",
 
-    /**
-     * Value of the Date response header or current time if Date was invalid
-     * @return timestamp
-     */
-    date() {
-        const serverDate = Date.parse(this._resHeaders.date);
-        if (isFinite(serverDate)) {
-            return serverDate;
-        }
-        return this._responseTime;
-    }
+    "cp819": "iso88591",
+    "ibm819": "iso88591",
 
-    /**
-     * Value of the Age header, in seconds, updated for the current time.
-     * May be fractional.
-     *
-     * @return Number
-     */
-    age() {
-        let age = this._ageValue();
+    "cyrillic": "iso88595",
 
-        const residentTime = (this.now() - this._responseTime) / 1000;
-        return age + residentTime;
-    }
+    "arabic": "iso88596",
+    "arabic8": "iso88596",
+    "ecma114": "iso88596",
+    "asmo708": "iso88596",
 
-    _ageValue() {
-        return toNumberOrZero(this._resHeaders.age);
-    }
+    "greek" : "iso88597",
+    "greek8" : "iso88597",
+    "ecma118" : "iso88597",
+    "elot928" : "iso88597",
 
-    /**
-     * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
-     *
-     * For an up-to-date value, see `timeToLive()`.
-     *
-     * @return Number
-     */
-    maxAge() {
-        if (!this.storable() || this._rescc['no-cache']) {
-            return 0;
-        }
+    "hebrew": "iso88598",
+    "hebrew8": "iso88598",
 
-        // Shared responses with cookies are cacheable according to the RFC, but IMHO it'd be unwise to do so by default
-        // so this implementation requires explicit opt-in via public header
-        if (
-            this._isShared &&
-            (this._resHeaders['set-cookie'] &&
-                !this._rescc.public &&
-                !this._rescc.immutable)
-        ) {
-            return 0;
-        }
+    "turkish": "iso88599",
+    "turkish8": "iso88599",
 
-        if (this._resHeaders.vary === '*') {
-            return 0;
-        }
+    "thai": "iso885911",
+    "thai8": "iso885911",
 
-        if (this._isShared) {
-            if (this._rescc['proxy-revalidate']) {
-                return 0;
-            }
-            // if a response includes the s-maxage directive, a shared cache recipient MUST ignore the Expires field.
-            if (this._rescc['s-maxage']) {
-                return toNumberOrZero(this._rescc['s-maxage']);
-            }
-        }
+    "celtic": "iso885914",
+    "celtic8": "iso885914",
+    "isoceltic": "iso885914",
 
-        // If a response includes a Cache-Control field with the max-age directive, a recipient MUST ignore the Expires field.
-        if (this._rescc['max-age']) {
-            return toNumberOrZero(this._rescc['max-age']);
-        }
+    "tis6200": "tis620",
+    "tis62025291": "tis620",
+    "tis62025330": "tis620",
 
-        const defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0;
+    "10000": "macroman",
+    "10006": "macgreek",
+    "10007": "maccyrillic",
+    "10079": "maciceland",
+    "10081": "macturkish",
 
-        const serverDate = this.date();
-        if (this._resHeaders.expires) {
-            const expires = Date.parse(this._resHeaders.expires);
-            // A cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").
-            if (Number.isNaN(expires) || expires < serverDate) {
-                return 0;
-            }
-            return Math.max(defaultMinTtl, (expires - serverDate) / 1000);
-        }
+    "cspc8codepage437": "cp437",
+    "cspc775baltic": "cp775",
+    "cspc850multilingual": "cp850",
+    "cspcp852": "cp852",
+    "cspc862latinhebrew": "cp862",
+    "cpgr": "cp869",
 
-        if (this._resHeaders['last-modified']) {
-            const lastModified = Date.parse(this._resHeaders['last-modified']);
-            if (isFinite(lastModified) && serverDate > lastModified) {
-                return Math.max(
-                    defaultMinTtl,
-                    ((serverDate - lastModified) / 1000) * this._cacheHeuristic
-                );
-            }
-        }
+    "msee": "cp1250",
+    "mscyrl": "cp1251",
+    "msansi": "cp1252",
+    "msgreek": "cp1253",
+    "msturk": "cp1254",
+    "mshebr": "cp1255",
+    "msarab": "cp1256",
+    "winbaltrim": "cp1257",
 
-        return defaultMinTtl;
-    }
+    "cp20866": "koi8r",
+    "20866": "koi8r",
+    "ibm878": "koi8r",
+    "cskoi8r": "koi8r",
 
-    timeToLive() {
-        const age = this.maxAge() - this.age();
-        const staleIfErrorAge = age + toNumberOrZero(this._rescc['stale-if-error']);
-        const staleWhileRevalidateAge = age + toNumberOrZero(this._rescc['stale-while-revalidate']);
-        return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1000;
-    }
+    "cp21866": "koi8u",
+    "21866": "koi8u",
+    "ibm1168": "koi8u",
 
-    stale() {
-        return this.maxAge() <= this.age();
-    }
+    "strk10482002": "rk1048",
 
-    _useStaleIfError() {
-        return this.maxAge() + toNumberOrZero(this._rescc['stale-if-error']) > this.age();
-    }
+    "tcvn5712": "tcvn",
+    "tcvn57121": "tcvn",
 
-    useStaleWhileRevalidate() {
-        return this.maxAge() + toNumberOrZero(this._rescc['stale-while-revalidate']) > this.age();
-    }
+    "gb198880": "iso646cn",
+    "cn": "iso646cn",
 
-    static fromObject(obj) {
-        return new this(undefined, undefined, { _fromObject: obj });
-    }
+    "csiso14jisc6220ro": "iso646jp",
+    "jisc62201969ro": "iso646jp",
+    "jp": "iso646jp",
 
-    _fromObject(obj) {
-        if (this._responseTime) throw Error('Reinitialized');
-        if (!obj || obj.v !== 1) throw Error('Invalid serialization');
+    "cshproman8": "hproman8",
+    "r8": "hproman8",
+    "roman8": "hproman8",
+    "xroman8": "hproman8",
+    "ibm1051": "hproman8",
 
-        this._responseTime = obj.t;
-        this._isShared = obj.sh;
-        this._cacheHeuristic = obj.ch;
-        this._immutableMinTtl =
-            obj.imm !== undefined ? obj.imm : 24 * 3600 * 1000;
-        this._status = obj.st;
-        this._resHeaders = obj.resh;
-        this._rescc = obj.rescc;
-        this._method = obj.m;
-        this._url = obj.u;
-        this._host = obj.h;
-        this._noAuthorization = obj.a;
-        this._reqHeaders = obj.reqh;
-        this._reqcc = obj.reqcc;
-    }
+    "mac": "macintosh",
+    "csmacintosh": "macintosh",
+};
 
-    toObject() {
-        return {
-            v: 1,
-            t: this._responseTime,
-            sh: this._isShared,
-            ch: this._cacheHeuristic,
-            imm: this._immutableMinTtl,
-            st: this._status,
-            resh: this._resHeaders,
-            rescc: this._rescc,
-            m: this._method,
-            u: this._url,
-            h: this._host,
-            a: this._noAuthorization,
-            reqh: this._reqHeaders,
-            reqcc: this._reqcc,
-        };
-    }
 
-    /**
-     * Headers for sending to the origin server to revalidate stale response.
-     * Allows server to return 304 to allow reuse of the previous response.
-     *
-     * Hop by hop headers are always stripped.
-     * Revalidation headers may be added or removed, depending on request.
-     */
-    revalidationHeaders(incomingReq) {
-        this._assertRequestHasHeaders(incomingReq);
-        const headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
 
-        // This implementation does not understand range requests
-        delete headers['if-range'];
+/***/ }),
 
-        if (!this._requestMatches(incomingReq, true) || !this.storable()) {
-            // revalidation allowed via HEAD
-            // not for the same resource, or wasn't allowed to be cached anyway
-            delete headers['if-none-match'];
-            delete headers['if-modified-since'];
-            return headers;
-        }
+/***/ 8771:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-        /* MUST send that entity-tag in any cache validation request (using If-Match or If-None-Match) if an entity-tag has been provided by the origin server. */
-        if (this._resHeaders.etag) {
-            headers['if-none-match'] = headers['if-none-match']
-                ? `${headers['if-none-match']}, ${this._resHeaders.etag}`
-                : this._resHeaders.etag;
-        }
+"use strict";
 
-        // Clients MAY issue simple (non-subrange) GET requests with either weak validators or strong validators. Clients MUST NOT use weak validators in other forms of request.
-        const forbidsWeakValidators =
-            headers['accept-ranges'] ||
-            headers['if-match'] ||
-            headers['if-unmodified-since'] ||
-            (this._method && this._method != 'GET');
+var Buffer = (__nccwpck_require__(12803).Buffer);
 
-        /* SHOULD send the Last-Modified value in non-subrange cache validation requests (using If-Modified-Since) if only a Last-Modified value has been provided by the origin server.
-        Note: This implementation does not understand partial responses (206) */
-        if (forbidsWeakValidators) {
-            delete headers['if-modified-since'];
+// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js
 
-            if (headers['if-none-match']) {
-                const etags = headers['if-none-match']
-                    .split(/,/)
-                    .filter(etag => {
-                        return !/^\s*W\//.test(etag);
-                    });
-                if (!etags.length) {
-                    delete headers['if-none-match'];
-                } else {
-                    headers['if-none-match'] = etags.join(',').trim();
-                }
-            }
-        } else if (
-            this._resHeaders['last-modified'] &&
-            !headers['if-modified-since']
-        ) {
-            headers['if-modified-since'] = this._resHeaders['last-modified'];
-        }
+// == UTF16-BE codec. ==========================================================
 
-        return headers;
-    }
+exports.utf16be = Utf16BECodec;
+function Utf16BECodec() {
+}
 
-    /**
-     * Creates new CachePolicy with information combined from the previews response,
-     * and the new revalidation response.
-     *
-     * Returns {policy, modified} where modified is a boolean indicating
-     * whether the response body has been modified, and old cached body can't be used.
-     *
-     * @return {Object} {policy: CachePolicy, modified: Boolean}
-     */
-    revalidatedPolicy(request, response) {
-        this._assertRequestHasHeaders(request);
-        if(this._useStaleIfError() && isErrorResponse(response)) {  // I consider the revalidation request unsuccessful
-          return {
-            modified: false,
-            matches: false,
-            policy: this,
-          };
-        }
-        if (!response || !response.headers) {
-            throw Error('Response headers missing');
-        }
+Utf16BECodec.prototype.encoder = Utf16BEEncoder;
+Utf16BECodec.prototype.decoder = Utf16BEDecoder;
+Utf16BECodec.prototype.bomAware = true;
 
-        // These aren't going to be supported exactly, since one CachePolicy object
-        // doesn't know about all the other cached objects.
-        let matches = false;
-        if (response.status !== undefined && response.status != 304) {
-            matches = false;
-        } else if (
-            response.headers.etag &&
-            !/^\s*W\//.test(response.headers.etag)
-        ) {
-            // "All of the stored responses with the same strong validator are selected.
-            // If none of the stored responses contain the same strong validator,
-            // then the cache MUST NOT use the new response to update any stored responses."
-            matches =
-                this._resHeaders.etag &&
-                this._resHeaders.etag.replace(/^\s*W\//, '') ===
-                    response.headers.etag;
-        } else if (this._resHeaders.etag && response.headers.etag) {
-            // "If the new response contains a weak validator and that validator corresponds
-            // to one of the cache's stored responses,
-            // then the most recent of those matching stored responses is selected for update."
-            matches =
-                this._resHeaders.etag.replace(/^\s*W\//, '') ===
-                response.headers.etag.replace(/^\s*W\//, '');
-        } else if (this._resHeaders['last-modified']) {
-            matches =
-                this._resHeaders['last-modified'] ===
-                response.headers['last-modified'];
-        } else {
-            // If the new response does not include any form of validator (such as in the case where
-            // a client generates an If-Modified-Since request from a source other than the Last-Modified
-            // response header field), and there is only one stored response, and that stored response also
-            // lacks a validator, then that stored response is selected for update.
-            if (
-                !this._resHeaders.etag &&
-                !this._resHeaders['last-modified'] &&
-                !response.headers.etag &&
-                !response.headers['last-modified']
-            ) {
-                matches = true;
-            }
-        }
 
-        if (!matches) {
-            return {
-                policy: new this.constructor(request, response),
-                // Client receiving 304 without body, even if it's invalid/mismatched has no option
-                // but to reuse a cached body. We don't have a good way to tell clients to do
-                // error recovery in such case.
-                modified: response.status != 304,
-                matches: false,
-            };
-        }
+// -- Encoding
 
-        // use other header fields provided in the 304 (Not Modified) response to replace all instances
-        // of the corresponding header fields in the stored response.
-        const headers = {};
-        for (const k in this._resHeaders) {
-            headers[k] =
-                k in response.headers && !excludedFromRevalidationUpdate[k]
-                    ? response.headers[k]
-                    : this._resHeaders[k];
-        }
+function Utf16BEEncoder() {
+}
 
-        const newResponse = Object.assign({}, response, {
-            status: this._status,
-            method: this._method,
-            headers,
-        });
-        return {
-            policy: new this.constructor(request, newResponse, {
-                shared: this._isShared,
-                cacheHeuristic: this._cacheHeuristic,
-                immutableMinTimeToLive: this._immutableMinTtl,
-            }),
-            modified: false,
-            matches: true,
-        };
+Utf16BEEncoder.prototype.write = function(str) {
+    var buf = Buffer.from(str, 'ucs2');
+    for (var i = 0; i < buf.length; i += 2) {
+        var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
     }
-};
+    return buf;
+}
 
+Utf16BEEncoder.prototype.end = function() {
+}
 
-/***/ }),
 
-/***/ 81970:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+// -- Decoding
 
-"use strict";
+function Utf16BEDecoder() {
+    this.overflowByte = -1;
+}
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpProxyAgent = void 0;
-const net = __importStar(__nccwpck_require__(69278));
-const tls = __importStar(__nccwpck_require__(64756));
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const events_1 = __nccwpck_require__(24434);
-const agent_base_1 = __nccwpck_require__(98894);
-const url_1 = __nccwpck_require__(87016);
-const debug = (0, debug_1.default)('http-proxy-agent');
-/**
- * The `HttpProxyAgent` implements an HTTP Agent subclass that connects
- * to the specified "HTTP proxy server" in order to proxy HTTP requests.
- */
-class HttpProxyAgent extends agent_base_1.Agent {
-    constructor(proxy, opts) {
-        super(opts);
-        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
-        this.proxyHeaders = opts?.headers ?? {};
-        debug('Creating new HttpProxyAgent instance: %o', this.proxy.href);
-        // Trim off the brackets from IPv6 addresses
-        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
-        const port = this.proxy.port
-            ? parseInt(this.proxy.port, 10)
-            : this.proxy.protocol === 'https:'
-                ? 443
-                : 80;
-        this.connectOpts = {
-            ...(opts ? omit(opts, 'headers') : null),
-            host,
-            port,
-        };
-    }
-    addRequest(req, opts) {
-        req._header = null;
-        this.setRequestProps(req, opts);
-        // @ts-expect-error `addRequest()` isn't defined in `@types/node`
-        super.addRequest(req, opts);
-    }
-    setRequestProps(req, opts) {
-        const { proxy } = this;
-        const protocol = opts.secureEndpoint ? 'https:' : 'http:';
-        const hostname = req.getHeader('host') || 'localhost';
-        const base = `${protocol}//${hostname}`;
-        const url = new url_1.URL(req.path, base);
-        if (opts.port !== 80) {
-            url.port = String(opts.port);
-        }
-        // Change the `http.ClientRequest` instance's "path" field
-        // to the absolute path of the URL that will be requested.
-        req.path = String(url);
-        // Inject the `Proxy-Authorization` header if necessary.
-        const headers = typeof this.proxyHeaders === 'function'
-            ? this.proxyHeaders()
-            : { ...this.proxyHeaders };
-        if (proxy.username || proxy.password) {
-            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
-            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
-        }
-        if (!headers['Proxy-Connection']) {
-            headers['Proxy-Connection'] = this.keepAlive
-                ? 'Keep-Alive'
-                : 'close';
-        }
-        for (const name of Object.keys(headers)) {
-            const value = headers[name];
-            if (value) {
-                req.setHeader(name, value);
-            }
-        }
-    }
-    async connect(req, opts) {
-        req._header = null;
-        if (!req.path.includes('://')) {
-            this.setRequestProps(req, opts);
-        }
-        // At this point, the http ClientRequest's internal `_header` field
-        // might have already been set. If this is the case then we'll need
-        // to re-generate the string since we just changed the `req.path`.
-        let first;
-        let endOfHeaders;
-        debug('Regenerating stored HTTP header string for request');
-        req._implicitHeader();
-        if (req.outputData && req.outputData.length > 0) {
-            debug('Patching connection write() output buffer with updated header');
-            first = req.outputData[0].data;
-            endOfHeaders = first.indexOf('\r\n\r\n') + 4;
-            req.outputData[0].data =
-                req._header + first.substring(endOfHeaders);
-            debug('Output buffer: %o', req.outputData[0].data);
-        }
-        // Create a socket connection to the proxy server.
-        let socket;
-        if (this.proxy.protocol === 'https:') {
-            debug('Creating `tls.Socket`: %o', this.connectOpts);
-            socket = tls.connect(this.connectOpts);
-        }
-        else {
-            debug('Creating `net.Socket`: %o', this.connectOpts);
-            socket = net.connect(this.connectOpts);
-        }
-        // Wait for the socket's `connect` event, so that this `callback()`
-        // function throws instead of the `http` request machinery. This is
-        // important for i.e. `PacProxyAgent` which determines a failed proxy
-        // connection via the `callback()` function throwing.
-        await (0, events_1.once)(socket, 'connect');
-        return socket;
+Utf16BEDecoder.prototype.write = function(buf) {
+    if (buf.length == 0)
+        return '';
+
+    var buf2 = Buffer.alloc(buf.length + 1),
+        i = 0, j = 0;
+
+    if (this.overflowByte !== -1) {
+        buf2[0] = buf[0];
+        buf2[1] = this.overflowByte;
+        i = 1; j = 2;
     }
-}
-HttpProxyAgent.protocols = ['http', 'https'];
-exports.HttpProxyAgent = HttpProxyAgent;
-function omit(obj, ...keys) {
-    const ret = {};
-    let key;
-    for (key in obj) {
-        if (!keys.includes(key)) {
-            ret[key] = obj[key];
-        }
+
+    for (; i < buf.length-1; i += 2, j+= 2) {
+        buf2[j] = buf[i+1];
+        buf2[j+1] = buf[i];
     }
-    return ret;
+
+    this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;
+
+    return buf2.slice(0, j).toString('ucs2');
 }
-//# sourceMappingURL=index.js.map
 
-/***/ }),
+Utf16BEDecoder.prototype.end = function() {
+    this.overflowByte = -1;
+}
 
-/***/ 3669:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-"use strict";
+// == UTF-16 codec =============================================================
+// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
+// Defaults to UTF-16LE, as it's prevalent and default in Node.
+// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
+// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpsProxyAgent = void 0;
-const net = __importStar(__nccwpck_require__(69278));
-const tls = __importStar(__nccwpck_require__(64756));
-const assert_1 = __importDefault(__nccwpck_require__(42613));
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const agent_base_1 = __nccwpck_require__(98894);
-const url_1 = __nccwpck_require__(87016);
-const parse_proxy_response_1 = __nccwpck_require__(37943);
-const debug = (0, debug_1.default)('https-proxy-agent');
-/**
- * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
- * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
- *
- * Outgoing HTTP requests are first tunneled through the proxy server using the
- * `CONNECT` HTTP request method to establish a connection to the proxy server,
- * and then the proxy server connects to the destination target and issues the
- * HTTP request from the proxy server.
- *
- * `https:` requests have their socket connection upgraded to TLS once
- * the connection to the proxy server has been established.
- */
-class HttpsProxyAgent extends agent_base_1.Agent {
-    constructor(proxy, opts) {
-        super(opts);
-        this.options = { path: undefined };
-        this.proxy = typeof proxy === 'string' ? new url_1.URL(proxy) : proxy;
-        this.proxyHeaders = opts?.headers ?? {};
-        debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
-        // Trim off the brackets from IPv6 addresses
-        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
-        const port = this.proxy.port
-            ? parseInt(this.proxy.port, 10)
-            : this.proxy.protocol === 'https:'
-                ? 443
-                : 80;
-        this.connectOpts = {
-            // Attempt to negotiate http/1.1 for proxy servers that support http/2
-            ALPNProtocols: ['http/1.1'],
-            ...(opts ? omit(opts, 'headers') : null),
-            host,
-            port,
-        };
-    }
-    /**
-     * Called when the node-core HTTP client library is creating a
-     * new HTTP request.
-     */
-    async connect(req, opts) {
-        const { proxy } = this;
-        if (!opts.host) {
-            throw new TypeError('No "host" provided');
-        }
-        // Create a socket connection to the proxy server.
-        let socket;
-        if (proxy.protocol === 'https:') {
-            debug('Creating `tls.Socket`: %o', this.connectOpts);
-            const servername = this.connectOpts.servername || this.connectOpts.host;
-            socket = tls.connect({
-                ...this.connectOpts,
-                servername,
-            });
-        }
-        else {
-            debug('Creating `net.Socket`: %o', this.connectOpts);
-            socket = net.connect(this.connectOpts);
-        }
-        const headers = typeof this.proxyHeaders === 'function'
-            ? this.proxyHeaders()
-            : { ...this.proxyHeaders };
-        const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
-        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
-        // Inject the `Proxy-Authorization` header if necessary.
-        if (proxy.username || proxy.password) {
-            const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
-            headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
-        }
-        headers.Host = `${host}:${opts.port}`;
-        if (!headers['Proxy-Connection']) {
-            headers['Proxy-Connection'] = this.keepAlive
-                ? 'Keep-Alive'
-                : 'close';
-        }
-        for (const name of Object.keys(headers)) {
-            payload += `${name}: ${headers[name]}\r\n`;
-        }
-        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
-        socket.write(`${payload}\r\n`);
-        const { connect, buffered } = await proxyResponsePromise;
-        req.emit('proxyConnect', connect);
-        this.emit('proxyConnect', connect, req);
-        if (connect.statusCode === 200) {
-            req.once('socket', resume);
-            if (opts.secureEndpoint) {
-                // The proxy is connecting to a TLS server, so upgrade
-                // this socket connection to a TLS connection.
-                debug('Upgrading socket connection to TLS');
-                const servername = opts.servername || opts.host;
-                return tls.connect({
-                    ...omit(opts, 'host', 'path', 'port'),
-                    socket,
-                    servername,
-                });
-            }
-            return socket;
-        }
-        // Some other status code that's not 200... need to re-play the HTTP
-        // header "data" events onto the socket once the HTTP machinery is
-        // attached so that the node core `http` can parse and handle the
-        // error status code.
-        // Close the original socket, and a new "fake" socket is returned
-        // instead, so that the proxy doesn't get the HTTP request
-        // written to it (which may contain `Authorization` headers or other
-        // sensitive data).
-        //
-        // See: https://hackerone.com/reports/541502
-        socket.destroy();
-        const fakeSocket = new net.Socket({ writable: false });
-        fakeSocket.readable = true;
-        // Need to wait for the "socket" event to re-play the "data" events.
-        req.once('socket', (s) => {
-            debug('Replaying proxy buffer for failed request');
-            (0, assert_1.default)(s.listenerCount('data') > 0);
-            // Replay the "buffered" Buffer onto the fake `socket`, since at
-            // this point the HTTP module machinery has been hooked up for
-            // the user.
-            s.push(buffered);
-            s.push(null);
-        });
-        return fakeSocket;
-    }
+// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).
+
+exports.utf16 = Utf16Codec;
+function Utf16Codec(codecOptions, iconv) {
+    this.iconv = iconv;
 }
-HttpsProxyAgent.protocols = ['http', 'https'];
-exports.HttpsProxyAgent = HttpsProxyAgent;
-function resume(socket) {
-    socket.resume();
+
+Utf16Codec.prototype.encoder = Utf16Encoder;
+Utf16Codec.prototype.decoder = Utf16Decoder;
+
+
+// -- Encoding (pass-through)
+
+function Utf16Encoder(options, codec) {
+    options = options || {};
+    if (options.addBOM === undefined)
+        options.addBOM = true;
+    this.encoder = codec.iconv.getEncoder('utf-16le', options);
 }
-function omit(obj, ...keys) {
-    const ret = {};
-    let key;
-    for (key in obj) {
-        if (!keys.includes(key)) {
-            ret[key] = obj[key];
-        }
+
+Utf16Encoder.prototype.write = function(str) {
+    return this.encoder.write(str);
+}
+
+Utf16Encoder.prototype.end = function() {
+    return this.encoder.end();
+}
+
+
+// -- Decoding
+
+function Utf16Decoder(options, codec) {
+    this.decoder = null;
+    this.initialBufs = [];
+    this.initialBufsLen = 0;
+
+    this.options = options || {};
+    this.iconv = codec.iconv;
+}
+
+Utf16Decoder.prototype.write = function(buf) {
+    if (!this.decoder) {
+        // Codec is not chosen yet. Accumulate initial bytes.
+        this.initialBufs.push(buf);
+        this.initialBufsLen += buf.length;
+        
+        if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below)
+            return '';
+
+        // We have enough bytes -> detect endianness.
+        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
+        this.decoder = this.iconv.getDecoder(encoding, this.options);
+
+        var resStr = '';
+        for (var i = 0; i < this.initialBufs.length; i++)
+            resStr += this.decoder.write(this.initialBufs[i]);
+
+        this.initialBufs.length = this.initialBufsLen = 0;
+        return resStr;
     }
-    return ret;
+
+    return this.decoder.write(buf);
 }
-//# sourceMappingURL=index.js.map
 
-/***/ }),
+Utf16Decoder.prototype.end = function() {
+    if (!this.decoder) {
+        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
+        this.decoder = this.iconv.getDecoder(encoding, this.options);
 
-/***/ 37943:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+        var resStr = '';
+        for (var i = 0; i < this.initialBufs.length; i++)
+            resStr += this.decoder.write(this.initialBufs[i]);
 
-"use strict";
+        var trail = this.decoder.end();
+        if (trail)
+            resStr += trail;
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseProxyResponse = void 0;
-const debug_1 = __importDefault(__nccwpck_require__(2830));
-const debug = (0, debug_1.default)('https-proxy-agent:parse-proxy-response');
-function parseProxyResponse(socket) {
-    return new Promise((resolve, reject) => {
-        // we need to buffer any HTTP traffic that happens with the proxy before we get
-        // the CONNECT response, so that if the response is anything other than an "200"
-        // response code, then we can re-play the "data" events on the socket once the
-        // HTTP parser is hooked up...
-        let buffersLength = 0;
-        const buffers = [];
-        function read() {
-            const b = socket.read();
-            if (b)
-                ondata(b);
-            else
-                socket.once('readable', read);
-        }
-        function cleanup() {
-            socket.removeListener('end', onend);
-            socket.removeListener('error', onerror);
-            socket.removeListener('readable', read);
-        }
-        function onend() {
-            cleanup();
-            debug('onend');
-            reject(new Error('Proxy connection ended before receiving CONNECT response'));
-        }
-        function onerror(err) {
-            cleanup();
-            debug('onerror %o', err);
-            reject(err);
-        }
-        function ondata(b) {
-            buffers.push(b);
-            buffersLength += b.length;
-            const buffered = Buffer.concat(buffers, buffersLength);
-            const endOfHeaders = buffered.indexOf('\r\n\r\n');
-            if (endOfHeaders === -1) {
-                // keep buffering
-                debug('have not received end of HTTP headers yet...');
-                read();
-                return;
-            }
-            const headerParts = buffered
-                .slice(0, endOfHeaders)
-                .toString('ascii')
-                .split('\r\n');
-            const firstLine = headerParts.shift();
-            if (!firstLine) {
-                socket.destroy();
-                return reject(new Error('No header received from proxy CONNECT response'));
-            }
-            const firstLineParts = firstLine.split(' ');
-            const statusCode = +firstLineParts[1];
-            const statusText = firstLineParts.slice(2).join(' ');
-            const headers = {};
-            for (const header of headerParts) {
-                if (!header)
-                    continue;
-                const firstColon = header.indexOf(':');
-                if (firstColon === -1) {
-                    socket.destroy();
-                    return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
-                }
-                const key = header.slice(0, firstColon).toLowerCase();
-                const value = header.slice(firstColon + 1).trimStart();
-                const current = headers[key];
-                if (typeof current === 'string') {
-                    headers[key] = [current, value];
-                }
-                else if (Array.isArray(current)) {
-                    current.push(value);
+        this.initialBufs.length = this.initialBufsLen = 0;
+        return resStr;
+    }
+    return this.decoder.end();
+}
+
+function detectEncoding(bufs, defaultEncoding) {
+    var b = [];
+    var charsProcessed = 0;
+    var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE.
+
+    outer_loop:
+    for (var i = 0; i < bufs.length; i++) {
+        var buf = bufs[i];
+        for (var j = 0; j < buf.length; j++) {
+            b.push(buf[j]);
+            if (b.length === 2) {
+                if (charsProcessed === 0) {
+                    // Check BOM first.
+                    if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le';
+                    if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be';
                 }
-                else {
-                    headers[key] = value;
+
+                if (b[0] === 0 && b[1] !== 0) asciiCharsBE++;
+                if (b[0] !== 0 && b[1] === 0) asciiCharsLE++;
+
+                b.length = 0;
+                charsProcessed++;
+
+                if (charsProcessed >= 100) {
+                    break outer_loop;
                 }
             }
-            debug('got proxy server response: %o %o', firstLine, headers);
-            cleanup();
-            resolve({
-                connect: {
-                    statusCode,
-                    statusText,
-                    headers,
-                },
-                buffered,
-            });
         }
-        socket.on('error', onerror);
-        socket.on('end', onend);
-        read();
-    });
+    }
+
+    // Make decisions.
+    // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
+    // So, we count ASCII as if it was LE or BE, and decide from that.
+    if (asciiCharsBE > asciiCharsLE) return 'utf-16be';
+    if (asciiCharsBE < asciiCharsLE) return 'utf-16le';
+
+    // Couldn't decide (likely all zeros or not enough data).
+    return defaultEncoding || 'utf-16le';
 }
-exports.parseProxyResponse = parseProxyResponse;
-//# sourceMappingURL=parse-proxy-response.js.map
+
+
+
 
 /***/ }),
 
-/***/ 7978:
+/***/ 62021:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
+
 var Buffer = (__nccwpck_require__(12803).Buffer);
 
-// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
-// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
-// To save memory and loading time, we read table files only when requested.
+// == UTF32-LE/BE codec. ==========================================================
 
-exports._dbcs = DBCSCodec;
+exports._utf32 = Utf32Codec;
 
-var UNASSIGNED = -1,
-    GB18030_CODE = -2,
-    SEQ_START  = -10,
-    NODE_START = -1000,
-    UNASSIGNED_NODE = new Array(0x100),
-    DEF_CHAR = -1;
+function Utf32Codec(codecOptions, iconv) {
+    this.iconv = iconv;
+    this.bomAware = true;
+    this.isLE = codecOptions.isLE;
+}
 
-for (var i = 0; i < 0x100; i++)
-    UNASSIGNED_NODE[i] = UNASSIGNED;
+exports.utf32le = { type: '_utf32', isLE: true };
+exports.utf32be = { type: '_utf32', isLE: false };
 
+// Aliases
+exports.ucs4le = 'utf32le';
+exports.ucs4be = 'utf32be';
 
-// Class DBCSCodec reads and initializes mapping tables.
-function DBCSCodec(codecOptions, iconv) {
-    this.encodingName = codecOptions.encodingName;
-    if (!codecOptions)
-        throw new Error("DBCS codec is called without the data.")
-    if (!codecOptions.table)
-        throw new Error("Encoding '" + this.encodingName + "' has no data.");
+Utf32Codec.prototype.encoder = Utf32Encoder;
+Utf32Codec.prototype.decoder = Utf32Decoder;
 
-    // Load tables.
-    var mappingTable = codecOptions.table();
+// -- Encoding
 
+function Utf32Encoder(options, codec) {
+    this.isLE = codec.isLE;
+    this.highSurrogate = 0;
+}
 
-    // Decode tables: MBCS -> Unicode.
+Utf32Encoder.prototype.write = function(str) {
+    var src = Buffer.from(str, 'ucs2');
+    var dst = Buffer.alloc(src.length * 2);
+    var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
+    var offset = 0;
 
-    // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
-    // Trie root is decodeTables[0].
-    // Values: >=  0 -> unicode character code. can be > 0xFFFF
-    //         == UNASSIGNED -> unknown/unassigned sequence.
-    //         == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
-    //         <= NODE_START -> index of the next node in our trie to process next byte.
-    //         <= SEQ_START  -> index of the start of a character code sequence, in decodeTableSeq.
-    this.decodeTables = [];
-    this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
+    for (var i = 0; i < src.length; i += 2) {
+        var code = src.readUInt16LE(i);
+        var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
+        var isLowSurrogate = (0xDC00 <= code && code < 0xE000);
 
-    // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
-    this.decodeTableSeq = [];
+        if (this.highSurrogate) {
+            if (isHighSurrogate || !isLowSurrogate) {
+                // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
+                // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
+                // (technically wrong, but expected by some applications, like Windows file names).
+                write32.call(dst, this.highSurrogate, offset);
+                offset += 4;
+            }
+            else {
+                // Create 32-bit value from high and low surrogates;
+                var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;
+
+                write32.call(dst, codepoint, offset);
+                offset += 4;
+                this.highSurrogate = 0;
+
+                continue;
+            }
+        }
+
+        if (isHighSurrogate)
+            this.highSurrogate = code;
+        else {
+            // Even if the current character is a low surrogate, with no previous high surrogate, we'll
+            // encode it as a semi-invalid stand-alone character for the same reasons expressed above for
+            // unpaired high surrogates.
+            write32.call(dst, code, offset);
+            offset += 4;
+            this.highSurrogate = 0;
+        }
+    }
+
+    if (offset < dst.length)
+        dst = dst.slice(0, offset);
+
+    return dst;
+};
+
+Utf32Encoder.prototype.end = function() {
+    // Treat any leftover high surrogate as a semi-valid independent character.
+    if (!this.highSurrogate)
+        return;
+
+    var buf = Buffer.alloc(4);
+
+    if (this.isLE)
+        buf.writeUInt32LE(this.highSurrogate, 0);
+    else
+        buf.writeUInt32BE(this.highSurrogate, 0);
 
-    // Actual mapping tables consist of chunks. Use them to fill up decode tables.
-    for (var i = 0; i < mappingTable.length; i++)
-        this._addDecodeChunk(mappingTable[i]);
+    this.highSurrogate = 0;
 
-    // Load & create GB18030 tables when needed.
-    if (typeof codecOptions.gb18030 === 'function') {
-        this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
+    return buf;
+};
 
-        // Add GB18030 common decode nodes.
-        var commonThirdByteNodeIdx = this.decodeTables.length;
-        this.decodeTables.push(UNASSIGNED_NODE.slice(0));
+// -- Decoding
 
-        var commonFourthByteNodeIdx = this.decodeTables.length;
-        this.decodeTables.push(UNASSIGNED_NODE.slice(0));
+function Utf32Decoder(options, codec) {
+    this.isLE = codec.isLE;
+    this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
+    this.overflow = [];
+}
 
-        // Fill out the tree
-        var firstByteNode = this.decodeTables[0];
-        for (var i = 0x81; i <= 0xFE; i++) {
-            var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]];
-            for (var j = 0x30; j <= 0x39; j++) {
-                if (secondByteNode[j] === UNASSIGNED) {
-                    secondByteNode[j] = NODE_START - commonThirdByteNodeIdx;
-                } else if (secondByteNode[j] > NODE_START) {
-                    throw new Error("gb18030 decode tables conflict at byte 2");
-                }
+Utf32Decoder.prototype.write = function(src) {
+    if (src.length === 0)
+        return '';
 
-                var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]];
-                for (var k = 0x81; k <= 0xFE; k++) {
-                    if (thirdByteNode[k] === UNASSIGNED) {
-                        thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx;
-                    } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {
-                        continue;
-                    } else if (thirdByteNode[k] > NODE_START) {
-                        throw new Error("gb18030 decode tables conflict at byte 3");
-                    }
+    var i = 0;
+    var codepoint = 0;
+    var dst = Buffer.alloc(src.length + 4);
+    var offset = 0;
+    var isLE = this.isLE;
+    var overflow = this.overflow;
+    var badChar = this.badChar;
 
-                    var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]];
-                    for (var l = 0x30; l <= 0x39; l++) {
-                        if (fourthByteNode[l] === UNASSIGNED)
-                            fourthByteNode[l] = GB18030_CODE;
-                    }
-                }
+    if (overflow.length > 0) {
+        for (; i < src.length && overflow.length < 4; i++)
+            overflow.push(src[i]);
+        
+        if (overflow.length === 4) {
+            // NOTE: codepoint is a signed int32 and can be negative.
+            // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer).
+            if (isLE) {
+                codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24);
+            } else {
+                codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24);
             }
+            overflow.length = 0;
+
+            offset = _writeCodepoint(dst, offset, codepoint, badChar);
         }
     }
 
-    this.defaultCharUnicode = iconv.defaultCharUnicode;
-
-    
-    // Encode tables: Unicode -> DBCS.
-
-    // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
-    // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
-    // Values: >=  0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
-    //         == UNASSIGNED -> no conversion found. Output a default char.
-    //         <= SEQ_START  -> it's an index in encodeTableSeq, see below. The character starts a sequence.
-    this.encodeTable = [];
-    
-    // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
-    // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
-    // means end of sequence (needed when one sequence is a strict subsequence of another).
-    // Objects are kept separately from encodeTable to increase performance.
-    this.encodeTableSeq = [];
-
-    // Some chars can be decoded, but need not be encoded.
-    var skipEncodeChars = {};
-    if (codecOptions.encodeSkipVals)
-        for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
-            var val = codecOptions.encodeSkipVals[i];
-            if (typeof val === 'number')
-                skipEncodeChars[val] = true;
-            else
-                for (var j = val.from; j <= val.to; j++)
-                    skipEncodeChars[j] = true;
+    // Main loop. Should be as optimized as possible.
+    for (; i < src.length - 3; i += 4) {
+        // NOTE: codepoint is a signed int32 and can be negative.
+        if (isLE) {
+            codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24);
+        } else {
+            codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24);
         }
-        
-    // Use decode trie to recursively fill out encode tables.
-    this._fillEncodeTable(0, 0, skipEncodeChars);
+        offset = _writeCodepoint(dst, offset, codepoint, badChar);
+    }
 
-    // Add more encoding pairs when needed.
-    if (codecOptions.encodeAdd) {
-        for (var uChar in codecOptions.encodeAdd)
-            if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
-                this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
+    // Keep overflowing bytes.
+    for (; i < src.length; i++) {
+        overflow.push(src[i]);
     }
 
-    this.defCharSB  = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
-    if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
-    if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
-}
+    return dst.slice(0, offset).toString('ucs2');
+};
 
-DBCSCodec.prototype.encoder = DBCSEncoder;
-DBCSCodec.prototype.decoder = DBCSDecoder;
+function _writeCodepoint(dst, offset, codepoint, badChar) {
+    // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations.
+    if (codepoint < 0 || codepoint > 0x10FFFF) {
+        // Not a valid Unicode codepoint
+        codepoint = badChar;
+    } 
 
-// Decoder helpers
-DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
-    var bytes = [];
-    for (; addr > 0; addr >>>= 8)
-        bytes.push(addr & 0xFF);
-    if (bytes.length == 0)
-        bytes.push(0);
+    // Ephemeral Planes: Write high surrogate.
+    if (codepoint >= 0x10000) {
+        codepoint -= 0x10000;
 
-    var node = this.decodeTables[0];
-    for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
-        var val = node[bytes[i]];
+        var high = 0xD800 | (codepoint >> 10);
+        dst[offset++] = high & 0xff;
+        dst[offset++] = high >> 8;
 
-        if (val == UNASSIGNED) { // Create new node.
-            node[bytes[i]] = NODE_START - this.decodeTables.length;
-            this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
-        }
-        else if (val <= NODE_START) { // Existing node.
-            node = this.decodeTables[NODE_START - val];
-        }
-        else
-            throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
+        // Low surrogate is written below.
+        var codepoint = 0xDC00 | (codepoint & 0x3FF);
     }
-    return node;
-}
 
+    // Write BMP char or low surrogate.
+    dst[offset++] = codepoint & 0xff;
+    dst[offset++] = codepoint >> 8;
 
-DBCSCodec.prototype._addDecodeChunk = function(chunk) {
-    // First element of chunk is the hex mbcs code where we start.
-    var curAddr = parseInt(chunk[0], 16);
+    return offset;
+};
 
-    // Choose the decoding node where we'll write our chars.
-    var writeTable = this._getDecodeTrieNode(curAddr);
-    curAddr = curAddr & 0xFF;
+Utf32Decoder.prototype.end = function() {
+    this.overflow.length = 0;
+};
 
-    // Write all other elements of the chunk to the table.
-    for (var k = 1; k < chunk.length; k++) {
-        var part = chunk[k];
-        if (typeof part === "string") { // String, write as-is.
-            for (var l = 0; l < part.length;) {
-                var code = part.charCodeAt(l++);
-                if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
-                    var codeTrail = part.charCodeAt(l++);
-                    if (0xDC00 <= codeTrail && codeTrail < 0xE000)
-                        writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
-                    else
-                        throw new Error("Incorrect surrogate pair in "  + this.encodingName + " at chunk " + chunk[0]);
-                }
-                else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
-                    var len = 0xFFF - code + 2;
-                    var seq = [];
-                    for (var m = 0; m < len; m++)
-                        seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
+// == UTF-32 Auto codec =============================================================
+// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
+// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
+// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});
 
-                    writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
-                    this.decodeTableSeq.push(seq);
-                }
-                else
-                    writeTable[curAddr++] = code; // Basic char
-            }
-        } 
-        else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
-            var charCode = writeTable[curAddr - 1] + 1;
-            for (var l = 0; l < part; l++)
-                writeTable[curAddr++] = charCode++;
-        }
-        else
-            throw new Error("Incorrect type '" + typeof part + "' given in "  + this.encodingName + " at chunk " + chunk[0]);
-    }
-    if (curAddr > 0xFF)
-        throw new Error("Incorrect chunk in "  + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
-}
+// Encoder prepends BOM (which can be overridden with (addBOM: false}).
 
-// Encoder helpers
-DBCSCodec.prototype._getEncodeBucket = function(uCode) {
-    var high = uCode >> 8; // This could be > 0xFF because of astral characters.
-    if (this.encodeTable[high] === undefined)
-        this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
-    return this.encodeTable[high];
-}
+exports.utf32 = Utf32AutoCodec;
+exports.ucs4 = 'utf32';
 
-DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
-    var bucket = this._getEncodeBucket(uCode);
-    var low = uCode & 0xFF;
-    if (bucket[low] <= SEQ_START)
-        this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
-    else if (bucket[low] == UNASSIGNED)
-        bucket[low] = dbcsCode;
+function Utf32AutoCodec(options, iconv) {
+    this.iconv = iconv;
 }
 
-DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
-    
-    // Get the root of character tree according to first character of the sequence.
-    var uCode = seq[0];
-    var bucket = this._getEncodeBucket(uCode);
-    var low = uCode & 0xFF;
+Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
+Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;
 
-    var node;
-    if (bucket[low] <= SEQ_START) {
-        // There's already a sequence with  - use it.
-        node = this.encodeTableSeq[SEQ_START-bucket[low]];
-    }
-    else {
-        // There was no sequence object - allocate a new one.
-        node = {};
-        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
-        bucket[low] = SEQ_START - this.encodeTableSeq.length;
-        this.encodeTableSeq.push(node);
-    }
+// -- Encoding
 
-    // Traverse the character tree, allocating new nodes as needed.
-    for (var j = 1; j < seq.length-1; j++) {
-        var oldVal = node[uCode];
-        if (typeof oldVal === 'object')
-            node = oldVal;
-        else {
-            node = node[uCode] = {}
-            if (oldVal !== undefined)
-                node[DEF_CHAR] = oldVal
-        }
-    }
+function Utf32AutoEncoder(options, codec) {
+    options = options || {};
 
-    // Set the leaf to given dbcsCode.
-    uCode = seq[seq.length-1];
-    node[uCode] = dbcsCode;
+    if (options.addBOM === undefined)
+        options.addBOM = true;
+
+    this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
 }
 
-DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
-    var node = this.decodeTables[nodeIdx];
-    var hasValues = false;
-    var subNodeEmpty = {};
-    for (var i = 0; i < 0x100; i++) {
-        var uCode = node[i];
-        var mbCode = prefix + i;
-        if (skipEncodeChars[mbCode])
-            continue;
+Utf32AutoEncoder.prototype.write = function(str) {
+    return this.encoder.write(str);
+};
 
-        if (uCode >= 0) {
-            this._setEncodeChar(uCode, mbCode);
-            hasValues = true;
-        } else if (uCode <= NODE_START) {
-            var subNodeIdx = NODE_START - uCode;
-            if (!subNodeEmpty[subNodeIdx]) {  // Skip empty subtrees (they are too large in gb18030).
-                var newPrefix = (mbCode << 8) >>> 0;  // NOTE: '>>> 0' keeps 32-bit num positive.
-                if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars))
-                    hasValues = true;
-                else
-                    subNodeEmpty[subNodeIdx] = true;
-            }
-        } else if (uCode <= SEQ_START) {
-            this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
-            hasValues = true;
-        }
-    }
-    return hasValues;
+Utf32AutoEncoder.prototype.end = function() {
+    return this.encoder.end();
+};
+
+// -- Decoding
+
+function Utf32AutoDecoder(options, codec) {
+    this.decoder = null;
+    this.initialBufs = [];
+    this.initialBufsLen = 0;
+    this.options = options || {};
+    this.iconv = codec.iconv;
 }
 
+Utf32AutoDecoder.prototype.write = function(buf) {
+    if (!this.decoder) { 
+        // Codec is not chosen yet. Accumulate initial bytes.
+        this.initialBufs.push(buf);
+        this.initialBufsLen += buf.length;
 
+        if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below)
+            return '';
 
-// == Encoder ==================================================================
+        // We have enough bytes -> detect endianness.
+        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
+        this.decoder = this.iconv.getDecoder(encoding, this.options);
 
-function DBCSEncoder(options, codec) {
-    // Encoder state
-    this.leadSurrogate = -1;
-    this.seqObj = undefined;
-    
-    // Static data
-    this.encodeTable = codec.encodeTable;
-    this.encodeTableSeq = codec.encodeTableSeq;
-    this.defaultCharSingleByte = codec.defCharSB;
-    this.gb18030 = codec.gb18030;
-}
+        var resStr = '';
+        for (var i = 0; i < this.initialBufs.length; i++)
+            resStr += this.decoder.write(this.initialBufs[i]);
 
-DBCSEncoder.prototype.write = function(str) {
-    var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
-        leadSurrogate = this.leadSurrogate,
-        seqObj = this.seqObj, nextChar = -1,
-        i = 0, j = 0;
+        this.initialBufs.length = this.initialBufsLen = 0;
+        return resStr;
+    }
 
-    while (true) {
-        // 0. Get next character.
-        if (nextChar === -1) {
-            if (i == str.length) break;
-            var uCode = str.charCodeAt(i++);
-        }
-        else {
-            var uCode = nextChar;
-            nextChar = -1;    
-        }
+    return this.decoder.write(buf);
+};
 
-        // 1. Handle surrogates.
-        if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
-            if (uCode < 0xDC00) { // We've got lead surrogate.
-                if (leadSurrogate === -1) {
-                    leadSurrogate = uCode;
-                    continue;
-                } else {
-                    leadSurrogate = uCode;
-                    // Double lead surrogate found.
-                    uCode = UNASSIGNED;
-                }
-            } else { // We've got trail surrogate.
-                if (leadSurrogate !== -1) {
-                    uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
-                    leadSurrogate = -1;
-                } else {
-                    // Incomplete surrogate pair - only trail surrogate found.
-                    uCode = UNASSIGNED;
-                }
-                
-            }
-        }
-        else if (leadSurrogate !== -1) {
-            // Incomplete surrogate pair - only lead surrogate found.
-            nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
-            leadSurrogate = -1;
-        }
+Utf32AutoDecoder.prototype.end = function() {
+    if (!this.decoder) {
+        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
+        this.decoder = this.iconv.getDecoder(encoding, this.options);
 
-        // 2. Convert uCode character.
-        var dbcsCode = UNASSIGNED;
-        if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
-            var resCode = seqObj[uCode];
-            if (typeof resCode === 'object') { // Sequence continues.
-                seqObj = resCode;
-                continue;
+        var resStr = '';
+        for (var i = 0; i < this.initialBufs.length; i++)
+            resStr += this.decoder.write(this.initialBufs[i]);
 
-            } else if (typeof resCode == 'number') { // Sequence finished. Write it.
-                dbcsCode = resCode;
+        var trail = this.decoder.end();
+        if (trail)
+            resStr += trail;
 
-            } else if (resCode == undefined) { // Current character is not part of the sequence.
+        this.initialBufs.length = this.initialBufsLen = 0;
+        return resStr;
+    }
 
-                // Try default character for this sequence
-                resCode = seqObj[DEF_CHAR];
-                if (resCode !== undefined) {
-                    dbcsCode = resCode; // Found. Write it.
-                    nextChar = uCode; // Current character will be written too in the next iteration.
+    return this.decoder.end();
+};
 
-                } else {
-                    // TODO: What if we have no default? (resCode == undefined)
-                    // Then, we should write first char of the sequence as-is and try the rest recursively.
-                    // Didn't do it for now because no encoding has this situation yet.
-                    // Currently, just skip the sequence and write current char.
+function detectEncoding(bufs, defaultEncoding) {
+    var b = [];
+    var charsProcessed = 0;
+    var invalidLE = 0, invalidBE = 0;   // Number of invalid chars when decoded as LE or BE.
+    var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE.
+
+    outer_loop:
+    for (var i = 0; i < bufs.length; i++) {
+        var buf = bufs[i];
+        for (var j = 0; j < buf.length; j++) {
+            b.push(buf[j]);
+            if (b.length === 4) {
+                if (charsProcessed === 0) {
+                    // Check BOM first.
+                    if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) {
+                        return 'utf-32le';
+                    }
+                    if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) {
+                        return 'utf-32be';
+                    }
                 }
-            }
-            seqObj = undefined;
-        }
-        else if (uCode >= 0) {  // Regular character
-            var subtable = this.encodeTable[uCode >> 8];
-            if (subtable !== undefined)
-                dbcsCode = subtable[uCode & 0xFF];
-            
-            if (dbcsCode <= SEQ_START) { // Sequence start
-                seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
-                continue;
-            }
 
-            if (dbcsCode == UNASSIGNED && this.gb18030) {
-                // Use GB18030 algorithm to find character(s) to write.
-                var idx = findIdx(this.gb18030.uChars, uCode);
-                if (idx != -1) {
-                    var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
-                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
-                    newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
-                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
-                    newBuf[j++] = 0x30 + dbcsCode;
-                    continue;
+                if (b[0] !== 0 || b[1] > 0x10) invalidBE++;
+                if (b[3] !== 0 || b[2] > 0x10) invalidLE++;
+
+                if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++;
+                if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++;
+
+                b.length = 0;
+                charsProcessed++;
+
+                if (charsProcessed >= 100) {
+                    break outer_loop;
                 }
             }
         }
-
-        // 3. Write dbcsCode character.
-        if (dbcsCode === UNASSIGNED)
-            dbcsCode = this.defaultCharSingleByte;
-        
-        if (dbcsCode < 0x100) {
-            newBuf[j++] = dbcsCode;
-        }
-        else if (dbcsCode < 0x10000) {
-            newBuf[j++] = dbcsCode >> 8;   // high byte
-            newBuf[j++] = dbcsCode & 0xFF; // low byte
-        }
-        else if (dbcsCode < 0x1000000) {
-            newBuf[j++] = dbcsCode >> 16;
-            newBuf[j++] = (dbcsCode >> 8) & 0xFF;
-            newBuf[j++] = dbcsCode & 0xFF;
-        } else {
-            newBuf[j++] = dbcsCode >>> 24;
-            newBuf[j++] = (dbcsCode >>> 16) & 0xFF;
-            newBuf[j++] = (dbcsCode >>> 8) & 0xFF;
-            newBuf[j++] = dbcsCode & 0xFF;
-        }
     }
 
-    this.seqObj = seqObj;
-    this.leadSurrogate = leadSurrogate;
-    return newBuf.slice(0, j);
-}
+    // Make decisions.
+    if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE)  return 'utf-32be';
+    if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE)  return 'utf-32le';
+
+    // Couldn't decide (likely all zeros or not enough data).
+    return defaultEncoding || 'utf-32le';
+}
+
+
+/***/ }),
+
+/***/ 28231:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
 
-DBCSEncoder.prototype.end = function() {
-    if (this.leadSurrogate === -1 && this.seqObj === undefined)
-        return; // All clean. Most often case.
+var Buffer = (__nccwpck_require__(12803).Buffer);
 
-    var newBuf = Buffer.alloc(10), j = 0;
+// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
+// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3
 
-    if (this.seqObj) { // We're in the sequence.
-        var dbcsCode = this.seqObj[DEF_CHAR];
-        if (dbcsCode !== undefined) { // Write beginning of the sequence.
-            if (dbcsCode < 0x100) {
-                newBuf[j++] = dbcsCode;
-            }
-            else {
-                newBuf[j++] = dbcsCode >> 8;   // high byte
-                newBuf[j++] = dbcsCode & 0xFF; // low byte
-            }
-        } else {
-            // See todo above.
-        }
-        this.seqObj = undefined;
-    }
+exports.utf7 = Utf7Codec;
+exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
+function Utf7Codec(codecOptions, iconv) {
+    this.iconv = iconv;
+};
 
-    if (this.leadSurrogate !== -1) {
-        // Incomplete surrogate pair - only lead surrogate found.
-        newBuf[j++] = this.defaultCharSingleByte;
-        this.leadSurrogate = -1;
-    }
-    
-    return newBuf.slice(0, j);
+Utf7Codec.prototype.encoder = Utf7Encoder;
+Utf7Codec.prototype.decoder = Utf7Decoder;
+Utf7Codec.prototype.bomAware = true;
+
+
+// -- Encoding
+
+var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
+
+function Utf7Encoder(options, codec) {
+    this.iconv = codec.iconv;
 }
 
-// Export for testing
-DBCSEncoder.prototype.findIdx = findIdx;
+Utf7Encoder.prototype.write = function(str) {
+    // Naive implementation.
+    // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-".
+    return Buffer.from(str.replace(nonDirectChars, function(chunk) {
+        return "+" + (chunk === '+' ? '' : 
+            this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) 
+            + "-";
+    }.bind(this)));
+}
 
+Utf7Encoder.prototype.end = function() {
+}
 
-// == Decoder ==================================================================
 
-function DBCSDecoder(options, codec) {
-    // Decoder state
-    this.nodeIdx = 0;
-    this.prevBytes = [];
+// -- Decoding
 
-    // Static data
-    this.decodeTables = codec.decodeTables;
-    this.decodeTableSeq = codec.decodeTableSeq;
-    this.defaultCharUnicode = codec.defaultCharUnicode;
-    this.gb18030 = codec.gb18030;
+function Utf7Decoder(options, codec) {
+    this.iconv = codec.iconv;
+    this.inBase64 = false;
+    this.base64Accum = '';
 }
 
-DBCSDecoder.prototype.write = function(buf) {
-    var newBuf = Buffer.alloc(buf.length*2),
-        nodeIdx = this.nodeIdx, 
-        prevBytes = this.prevBytes, prevOffset = this.prevBytes.length,
-        seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence.
-        uCode;
+var base64Regex = /[A-Za-z0-9\/+]/;
+var base64Chars = [];
+for (var i = 0; i < 256; i++)
+    base64Chars[i] = base64Regex.test(String.fromCharCode(i));
 
-    for (var i = 0, j = 0; i < buf.length; i++) {
-        var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset];
+var plusChar = '+'.charCodeAt(0), 
+    minusChar = '-'.charCodeAt(0),
+    andChar = '&'.charCodeAt(0);
 
-        // Lookup in current trie node.
-        var uCode = this.decodeTables[nodeIdx][curByte];
+Utf7Decoder.prototype.write = function(buf) {
+    var res = "", lastI = 0,
+        inBase64 = this.inBase64,
+        base64Accum = this.base64Accum;
 
-        if (uCode >= 0) { 
-            // Normal character, just use it.
-        }
-        else if (uCode === UNASSIGNED) { // Unknown char.
-            // TODO: Callback with seq.
-            uCode = this.defaultCharUnicode.charCodeAt(0);
-            i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again.
-        }
-        else if (uCode === GB18030_CODE) {
-            if (i >= 3) {
-                var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30);
-            } else {
-                var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + 
-                          (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + 
-                          (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + 
-                          (curByte-0x30);
-            }
-            var idx = findIdx(this.gb18030.gbChars, ptr);
-            uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
-        }
-        else if (uCode <= NODE_START) { // Go to next trie node.
-            nodeIdx = NODE_START - uCode;
-            continue;
-        }
-        else if (uCode <= SEQ_START) { // Output a sequence of chars.
-            var seq = this.decodeTableSeq[SEQ_START - uCode];
-            for (var k = 0; k < seq.length - 1; k++) {
-                uCode = seq[k];
-                newBuf[j++] = uCode & 0xFF;
-                newBuf[j++] = uCode >> 8;
+    // The decoder is more involved as we must handle chunks in stream.
+
+    for (var i = 0; i < buf.length; i++) {
+        if (!inBase64) { // We're in direct mode.
+            // Write direct chars until '+'
+            if (buf[i] == plusChar) {
+                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
+                lastI = i+1;
+                inBase64 = true;
             }
-            uCode = seq[seq.length-1];
-        }
-        else
-            throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
+        } else { // We decode base64.
+            if (!base64Chars[buf[i]]) { // Base64 ended.
+                if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
+                    res += "+";
+                } else {
+                    var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii");
+                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
+                }
 
-        // Write the character to buffer, handling higher planes using surrogate pair.
-        if (uCode >= 0x10000) { 
-            uCode -= 0x10000;
-            var uCodeLead = 0xD800 | (uCode >> 10);
-            newBuf[j++] = uCodeLead & 0xFF;
-            newBuf[j++] = uCodeLead >> 8;
+                if (buf[i] != minusChar) // Minus is absorbed after base64.
+                    i--;
 
-            uCode = 0xDC00 | (uCode & 0x3FF);
+                lastI = i+1;
+                inBase64 = false;
+                base64Accum = '';
+            }
         }
-        newBuf[j++] = uCode & 0xFF;
-        newBuf[j++] = uCode >> 8;
-
-        // Reset trie node.
-        nodeIdx = 0; seqStart = i+1;
     }
 
-    this.nodeIdx = nodeIdx;
-    this.prevBytes = (seqStart >= 0)
-        ? Array.prototype.slice.call(buf, seqStart)
-        : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));
-
-    return newBuf.slice(0, j).toString('ucs2');
-}
-
-DBCSDecoder.prototype.end = function() {
-    var ret = '';
+    if (!inBase64) {
+        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
+    } else {
+        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii");
 
-    // Try to parse all remaining chars.
-    while (this.prevBytes.length > 0) {
-        // Skip 1 character in the buffer.
-        ret += this.defaultCharUnicode;
-        var bytesArr = this.prevBytes.slice(1);
+        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
+        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
+        b64str = b64str.slice(0, canBeDecoded);
 
-        // Parse remaining as usual.
-        this.prevBytes = [];
-        this.nodeIdx = 0;
-        if (bytesArr.length > 0)
-            ret += this.write(bytesArr);
+        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
     }
 
-    this.prevBytes = [];
-    this.nodeIdx = 0;
-    return ret;
+    this.inBase64 = inBase64;
+    this.base64Accum = base64Accum;
+
+    return res;
 }
 
-// Binary search for GB18030. Returns largest i such that table[i] <= val.
-function findIdx(table, val) {
-    if (table[0] > val)
-        return -1;
+Utf7Decoder.prototype.end = function() {
+    var res = "";
+    if (this.inBase64 && this.base64Accum.length > 0)
+        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
 
-    var l = 0, r = table.length;
-    while (l < r-1) { // always table[l] <= val < table[r]
-        var mid = l + ((r-l+1) >> 1);
-        if (table[mid] <= val)
-            l = mid;
-        else
-            r = mid;
-    }
-    return l;
+    this.inBase64 = false;
+    this.base64Accum = '';
+    return res;
 }
 
 
+// UTF-7-IMAP codec.
+// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
+// Differences:
+//  * Base64 part is started by "&" instead of "+"
+//  * Direct characters are 0x20-0x7E, except "&" (0x26)
+//  * In Base64, "," is used instead of "/"
+//  * Base64 must not be used to represent direct characters.
+//  * No implicit shift back from Base64 (should always end with '-')
+//  * String must end in non-shifted position.
+//  * "-&" while in base64 is not allowed.
 
-/***/ }),
 
-/***/ 11802:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+exports.utf7imap = Utf7IMAPCodec;
+function Utf7IMAPCodec(codecOptions, iconv) {
+    this.iconv = iconv;
+};
 
-"use strict";
+Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
+Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
+Utf7IMAPCodec.prototype.bomAware = true;
 
 
-// Description of supported double byte encodings and aliases.
-// Tables are not require()-d until they are needed to speed up library load.
-// require()-s are direct to support Browserify.
+// -- Encoding
 
-module.exports = {
-    
-    // == Japanese/ShiftJIS ====================================================
-    // All japanese encodings are based on JIS X set of standards:
-    // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
-    // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. 
-    //              Has several variations in 1978, 1983, 1990 and 1997.
-    // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
-    // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
-    //              2 planes, first is superset of 0208, second - revised 0212.
-    //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
+function Utf7IMAPEncoder(options, codec) {
+    this.iconv = codec.iconv;
+    this.inBase64 = false;
+    this.base64Accum = Buffer.alloc(6);
+    this.base64AccumIdx = 0;
+}
 
-    // Byte encodings are:
-    //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
-    //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
-    //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
-    //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
-    //               0x00-0x7F       - lower part of 0201
-    //               0x8E, 0xA1-0xDF - upper part of 0201
-    //               (0xA1-0xFE)x2   - 0208 plane (94x94).
-    //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
-    //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
-    //               Used as-is in ISO2022 family.
-    //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, 
-    //                0201-1976 Roman, 0208-1978, 0208-1983.
-    //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
-    //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
-    //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
-    //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
-    //
-    // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
-    //
-    // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
+Utf7IMAPEncoder.prototype.write = function(str) {
+    var inBase64 = this.inBase64,
+        base64Accum = this.base64Accum,
+        base64AccumIdx = this.base64AccumIdx,
+        buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;
 
-    'shiftjis': {
-        type: '_dbcs',
-        table: function() { return __nccwpck_require__(40679) },
-        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
-        encodeSkipVals: [{from: 0xED40, to: 0xF940}],
-    },
-    'csshiftjis': 'shiftjis',
-    'mskanji': 'shiftjis',
-    'sjis': 'shiftjis',
-    'windows31j': 'shiftjis',
-    'ms31j': 'shiftjis',
-    'xsjis': 'shiftjis',
-    'windows932': 'shiftjis',
-    'ms932': 'shiftjis',
-    '932': 'shiftjis',
-    'cp932': 'shiftjis',
+    for (var i = 0; i < str.length; i++) {
+        var uChar = str.charCodeAt(i);
+        if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
+            if (inBase64) {
+                if (base64AccumIdx > 0) {
+                    bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
+                    base64AccumIdx = 0;
+                }
 
-    'eucjp': {
-        type: '_dbcs',
-        table: function() { return __nccwpck_require__(56406) },
-        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
-    },
+                buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
+                inBase64 = false;
+            }
 
-    // TODO: KDDI extension to Shift_JIS
-    // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
-    // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
+            if (!inBase64) {
+                buf[bufIdx++] = uChar; // Write direct character
 
+                if (uChar === andChar)  // Ampersand -> '&-'
+                    buf[bufIdx++] = minusChar;
+            }
 
-    // == Chinese/GBK ==========================================================
-    // http://en.wikipedia.org/wiki/GBK
-    // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
+        } else { // Non-direct character
+            if (!inBase64) {
+                buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
+                inBase64 = true;
+            }
+            if (inBase64) {
+                base64Accum[base64AccumIdx++] = uChar >> 8;
+                base64Accum[base64AccumIdx++] = uChar & 0xFF;
 
-    // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
-    'gb2312': 'cp936',
-    'gb231280': 'cp936',
-    'gb23121980': 'cp936',
-    'csgb2312': 'cp936',
-    'csiso58gb231280': 'cp936',
-    'euccn': 'cp936',
+                if (base64AccumIdx == base64Accum.length) {
+                    bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
+                    base64AccumIdx = 0;
+                }
+            }
+        }
+    }
 
-    // Microsoft's CP936 is a subset and approximation of GBK.
-    'windows936': 'cp936',
-    'ms936': 'cp936',
-    '936': 'cp936',
-    'cp936': {
-        type: '_dbcs',
-        table: function() { return __nccwpck_require__(74488) },
-    },
+    this.inBase64 = inBase64;
+    this.base64AccumIdx = base64AccumIdx;
 
-    // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
-    'gbk': {
-        type: '_dbcs',
-        table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) },
-    },
-    'xgbk': 'gbk',
-    'isoir58': 'gbk',
+    return buf.slice(0, bufIdx);
+}
 
-    // GB18030 is an algorithmic extension of GBK.
-    // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
-    // http://icu-project.org/docs/papers/gb18030.html
-    // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
-    // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
-    'gb18030': {
-        type: '_dbcs',
-        table: function() { return (__nccwpck_require__(74488).concat)(__nccwpck_require__(55914)) },
-        gb18030: function() { return __nccwpck_require__(99129) },
-        encodeSkipVals: [0x80],
-        encodeAdd: {'€': 0xA2E3},
-    },
+Utf7IMAPEncoder.prototype.end = function() {
+    var buf = Buffer.alloc(10), bufIdx = 0;
+    if (this.inBase64) {
+        if (this.base64AccumIdx > 0) {
+            bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
+            this.base64AccumIdx = 0;
+        }
 
-    'chinese': 'gb18030',
+        buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
+        this.inBase64 = false;
+    }
 
+    return buf.slice(0, bufIdx);
+}
 
-    // == Korean ===============================================================
-    // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
-    'windows949': 'cp949',
-    'ms949': 'cp949',
-    '949': 'cp949',
-    'cp949': {
-        type: '_dbcs',
-        table: function() { return __nccwpck_require__(21166) },
-    },
 
-    'cseuckr': 'cp949',
-    'csksc56011987': 'cp949',
-    'euckr': 'cp949',
-    'isoir149': 'cp949',
-    'korean': 'cp949',
-    'ksc56011987': 'cp949',
-    'ksc56011989': 'cp949',
-    'ksc5601': 'cp949',
+// -- Decoding
 
+function Utf7IMAPDecoder(options, codec) {
+    this.iconv = codec.iconv;
+    this.inBase64 = false;
+    this.base64Accum = '';
+}
 
-    // == Big5/Taiwan/Hong Kong ================================================
-    // There are lots of tables for Big5 and cp950. Please see the following links for history:
-    // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
-    // Variations, in roughly number of defined chars:
-    //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
-    //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
-    //  * Big5-2003 (Taiwan standard) almost superset of cp950.
-    //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
-    //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. 
-    //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
-    //    Plus, it has 4 combining sequences.
-    //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
-    //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
-    //    Implementations are not consistent within browsers; sometimes labeled as just big5.
-    //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
-    //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
-    //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
-    //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
-    //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
-    // 
-    // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
-    // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
+var base64IMAPChars = base64Chars.slice();
+base64IMAPChars[','.charCodeAt(0)] = true;
 
-    'windows950': 'cp950',
-    'ms950': 'cp950',
-    '950': 'cp950',
-    'cp950': {
-        type: '_dbcs',
-        table: function() { return __nccwpck_require__(72324) },
-    },
+Utf7IMAPDecoder.prototype.write = function(buf) {
+    var res = "", lastI = 0,
+        inBase64 = this.inBase64,
+        base64Accum = this.base64Accum;
 
-    // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
-    'big5': 'big5hkscs',
-    'big5hkscs': {
-        type: '_dbcs',
-        table: function() { return (__nccwpck_require__(72324).concat)(__nccwpck_require__(43267)) },
-        encodeSkipVals: [
-            // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of
-            // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU.
-            // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter.
-            0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe,
-            0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca,
-            0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62,
-            0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef,
-            0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed,
+    // The decoder is more involved as we must handle chunks in stream.
+    // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).
 
-            // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345
-            0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce,
-        ],
-    },
+    for (var i = 0; i < buf.length; i++) {
+        if (!inBase64) { // We're in direct mode.
+            // Write direct chars until '&'
+            if (buf[i] == andChar) {
+                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
+                lastI = i+1;
+                inBase64 = true;
+            }
+        } else { // We decode base64.
+            if (!base64IMAPChars[buf[i]]) { // Base64 ended.
+                if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
+                    res += "&";
+                } else {
+                    var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/');
+                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
+                }
 
-    'cnbig5': 'big5hkscs',
-    'csbig5': 'big5hkscs',
-    'xxbig5': 'big5hkscs',
-};
+                if (buf[i] != minusChar) // Minus may be absorbed after base64.
+                    i--;
+
+                lastI = i+1;
+                inBase64 = false;
+                base64Accum = '';
+            }
+        }
+    }
 
+    if (!inBase64) {
+        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
+    } else {
+        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/');
 
-/***/ }),
+        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
+        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
+        b64str = b64str.slice(0, canBeDecoded);
 
-/***/ 27585:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
+    }
 
-"use strict";
+    this.inBase64 = inBase64;
+    this.base64Accum = base64Accum;
 
+    return res;
+}
 
-// Update this array if you add/rename/remove files in this directory.
-// We support Browserify by skipping automatic module discovery and requiring modules directly.
-var modules = [
-    __nccwpck_require__(72356),
-    __nccwpck_require__(62021),
-    __nccwpck_require__(8771),
-    __nccwpck_require__(28231),
-    __nccwpck_require__(82473),
-    __nccwpck_require__(97083),
-    __nccwpck_require__(69487),
-    __nccwpck_require__(7978),
-    __nccwpck_require__(11802),
-];
+Utf7IMAPDecoder.prototype.end = function() {
+    var res = "";
+    if (this.inBase64 && this.base64Accum.length > 0)
+        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
 
-// Put all encoding/alias/codec definitions to single object and export it.
-for (var i = 0; i < modules.length; i++) {
-    var module = modules[i];
-    for (var enc in module)
-        if (Object.prototype.hasOwnProperty.call(module, enc))
-            exports[enc] = module[enc];
+    this.inBase64 = false;
+    this.base64Accum = '';
+    return res;
 }
 
 
+
+
 /***/ }),
 
-/***/ 72356:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 74250:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
-var Buffer = (__nccwpck_require__(12803).Buffer);
 
-// Export Node.js internal encodings.
+var BOMChar = '\uFEFF';
 
-module.exports = {
-    // Encodings
-    utf8:   { type: "_internal", bomAware: true},
-    cesu8:  { type: "_internal", bomAware: true},
-    unicode11utf8: "utf8",
+exports.PrependBOM = PrependBOMWrapper
+function PrependBOMWrapper(encoder, options) {
+    this.encoder = encoder;
+    this.addBOM = true;
+}
 
-    ucs2:   { type: "_internal", bomAware: true},
-    utf16le: "ucs2",
+PrependBOMWrapper.prototype.write = function(str) {
+    if (this.addBOM) {
+        str = BOMChar + str;
+        this.addBOM = false;
+    }
 
-    binary: { type: "_internal" },
-    base64: { type: "_internal" },
-    hex:    { type: "_internal" },
+    return this.encoder.write(str);
+}
+
+PrependBOMWrapper.prototype.end = function() {
+    return this.encoder.end();
+}
 
-    // Codec.
-    _internal: InternalCodec,
-};
 
 //------------------------------------------------------------------------------
 
-function InternalCodec(codecOptions, iconv) {
-    this.enc = codecOptions.encodingName;
-    this.bomAware = codecOptions.bomAware;
+exports.StripBOM = StripBOMWrapper;
+function StripBOMWrapper(decoder, options) {
+    this.decoder = decoder;
+    this.pass = false;
+    this.options = options || {};
+}
 
-    if (this.enc === "base64")
-        this.encoder = InternalEncoderBase64;
-    else if (this.enc === "cesu8") {
-        this.enc = "utf8"; // Use utf8 for decoding.
-        this.encoder = InternalEncoderCesu8;
+StripBOMWrapper.prototype.write = function(buf) {
+    var res = this.decoder.write(buf);
+    if (this.pass || !res)
+        return res;
 
-        // Add decoder for versions of Node not supporting CESU-8
-        if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
-            this.decoder = InternalDecoderCesu8;
-            this.defaultCharUnicode = iconv.defaultCharUnicode;
-        }
+    if (res[0] === BOMChar) {
+        res = res.slice(1);
+        if (typeof this.options.stripBOM === 'function')
+            this.options.stripBOM();
     }
+
+    this.pass = true;
+    return res;
 }
 
-InternalCodec.prototype.encoder = InternalEncoder;
-InternalCodec.prototype.decoder = InternalDecoder;
+StripBOMWrapper.prototype.end = function() {
+    return this.decoder.end();
+}
 
-//------------------------------------------------------------------------------
 
-// We use node.js internal decoder. Its signature is the same as ours.
-var StringDecoder = (__nccwpck_require__(13193).StringDecoder);
 
-if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
-    StringDecoder.prototype.end = function() {};
+/***/ }),
 
+/***/ 31748:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function InternalDecoder(options, codec) {
-    this.decoder = new StringDecoder(codec.enc);
-}
+"use strict";
 
-InternalDecoder.prototype.write = function(buf) {
-    if (!Buffer.isBuffer(buf)) {
-        buf = Buffer.from(buf);
-    }
 
-    return this.decoder.write(buf);
-}
+var Buffer = (__nccwpck_require__(12803).Buffer);
 
-InternalDecoder.prototype.end = function() {
-    return this.decoder.end();
-}
+var bomHandling = __nccwpck_require__(74250),
+    iconv = module.exports;
 
+// All codecs and aliases are kept here, keyed by encoding name/alias.
+// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
+iconv.encodings = null;
 
-//------------------------------------------------------------------------------
-// Encoder is mostly trivial
+// Characters emitted in case of error.
+iconv.defaultCharUnicode = '�';
+iconv.defaultCharSingleByte = '?';
 
-function InternalEncoder(options, codec) {
-    this.enc = codec.enc;
-}
+// Public API.
+iconv.encode = function encode(str, encoding, options) {
+    str = "" + (str || ""); // Ensure string.
 
-InternalEncoder.prototype.write = function(str) {
-    return Buffer.from(str, this.enc);
-}
+    var encoder = iconv.getEncoder(encoding, options);
 
-InternalEncoder.prototype.end = function() {
+    var res = encoder.write(str);
+    var trail = encoder.end();
+    
+    return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
 }
 
+iconv.decode = function decode(buf, encoding, options) {
+    if (typeof buf === 'string') {
+        if (!iconv.skipDecodeWarning) {
+            console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
+            iconv.skipDecodeWarning = true;
+        }
 
-//------------------------------------------------------------------------------
-// Except base64 encoder, which must keep its state.
+        buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
+    }
 
-function InternalEncoderBase64(options, codec) {
-    this.prevStr = '';
-}
+    var decoder = iconv.getDecoder(encoding, options);
 
-InternalEncoderBase64.prototype.write = function(str) {
-    str = this.prevStr + str;
-    var completeQuads = str.length - (str.length % 4);
-    this.prevStr = str.slice(completeQuads);
-    str = str.slice(0, completeQuads);
+    var res = decoder.write(buf);
+    var trail = decoder.end();
 
-    return Buffer.from(str, "base64");
+    return trail ? (res + trail) : res;
 }
 
-InternalEncoderBase64.prototype.end = function() {
-    return Buffer.from(this.prevStr, "base64");
+iconv.encodingExists = function encodingExists(enc) {
+    try {
+        iconv.getCodec(enc);
+        return true;
+    } catch (e) {
+        return false;
+    }
 }
 
+// Legacy aliases to convert functions
+iconv.toEncoding = iconv.encode;
+iconv.fromEncoding = iconv.decode;
 
-//------------------------------------------------------------------------------
-// CESU-8 encoder is also special.
+// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
+iconv._codecDataCache = {};
+iconv.getCodec = function getCodec(encoding) {
+    if (!iconv.encodings)
+        iconv.encodings = __nccwpck_require__(27585); // Lazy load all encoding definitions.
+    
+    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
+    var enc = iconv._canonicalizeEncoding(encoding);
 
-function InternalEncoderCesu8(options, codec) {
-}
+    // Traverse iconv.encodings to find actual codec.
+    var codecOptions = {};
+    while (true) {
+        var codec = iconv._codecDataCache[enc];
+        if (codec)
+            return codec;
 
-InternalEncoderCesu8.prototype.write = function(str) {
-    var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
-    for (var i = 0; i < str.length; i++) {
-        var charCode = str.charCodeAt(i);
-        // Naive implementation, but it works because CESU-8 is especially easy
-        // to convert from UTF-16 (which all JS strings are encoded in).
-        if (charCode < 0x80)
-            buf[bufIdx++] = charCode;
-        else if (charCode < 0x800) {
-            buf[bufIdx++] = 0xC0 + (charCode >>> 6);
-            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
-        }
-        else { // charCode will always be < 0x10000 in javascript.
-            buf[bufIdx++] = 0xE0 + (charCode >>> 12);
-            buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
-            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
+        var codecDef = iconv.encodings[enc];
+
+        switch (typeof codecDef) {
+            case "string": // Direct alias to other encoding.
+                enc = codecDef;
+                break;
+
+            case "object": // Alias with options. Can be layered.
+                for (var key in codecDef)
+                    codecOptions[key] = codecDef[key];
+
+                if (!codecOptions.encodingName)
+                    codecOptions.encodingName = enc;
+                
+                enc = codecDef.type;
+                break;
+
+            case "function": // Codec itself.
+                if (!codecOptions.encodingName)
+                    codecOptions.encodingName = enc;
+
+                // The codec function must load all tables and return object with .encoder and .decoder methods.
+                // It'll be called only once (for each different options object).
+                codec = new codecDef(codecOptions, iconv);
+
+                iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
+                return codec;
+
+            default:
+                throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
         }
     }
-    return buf.slice(0, bufIdx);
 }
 
-InternalEncoderCesu8.prototype.end = function() {
+iconv._canonicalizeEncoding = function(encoding) {
+    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
+    return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
 }
 
-//------------------------------------------------------------------------------
-// CESU-8 decoder is not implemented in Node v4.0+
+iconv.getEncoder = function getEncoder(encoding, options) {
+    var codec = iconv.getCodec(encoding),
+        encoder = new codec.encoder(options, codec);
 
-function InternalDecoderCesu8(options, codec) {
-    this.acc = 0;
-    this.contBytes = 0;
-    this.accBytes = 0;
-    this.defaultCharUnicode = codec.defaultCharUnicode;
+    if (codec.bomAware && options && options.addBOM)
+        encoder = new bomHandling.PrependBOM(encoder, options);
+
+    return encoder;
 }
 
-InternalDecoderCesu8.prototype.write = function(buf) {
-    var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, 
-        res = '';
-    for (var i = 0; i < buf.length; i++) {
-        var curByte = buf[i];
-        if ((curByte & 0xC0) !== 0x80) { // Leading byte
-            if (contBytes > 0) { // Previous code is invalid
-                res += this.defaultCharUnicode;
-                contBytes = 0;
-            }
+iconv.getDecoder = function getDecoder(encoding, options) {
+    var codec = iconv.getCodec(encoding),
+        decoder = new codec.decoder(options, codec);
 
-            if (curByte < 0x80) { // Single-byte code
-                res += String.fromCharCode(curByte);
-            } else if (curByte < 0xE0) { // Two-byte code
-                acc = curByte & 0x1F;
-                contBytes = 1; accBytes = 1;
-            } else if (curByte < 0xF0) { // Three-byte code
-                acc = curByte & 0x0F;
-                contBytes = 2; accBytes = 1;
-            } else { // Four or more are not supported for CESU-8.
-                res += this.defaultCharUnicode;
-            }
-        } else { // Continuation byte
-            if (contBytes > 0) { // We're waiting for it.
-                acc = (acc << 6) | (curByte & 0x3f);
-                contBytes--; accBytes++;
-                if (contBytes === 0) {
-                    // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
-                    if (accBytes === 2 && acc < 0x80 && acc > 0)
-                        res += this.defaultCharUnicode;
-                    else if (accBytes === 3 && acc < 0x800)
-                        res += this.defaultCharUnicode;
-                    else
-                        // Actually add character.
-                        res += String.fromCharCode(acc);
-                }
-            } else { // Unexpected continuation byte
-                res += this.defaultCharUnicode;
-            }
-        }
+    if (codec.bomAware && !(options && options.stripBOM === false))
+        decoder = new bomHandling.StripBOM(decoder, options);
+
+    return decoder;
+}
+
+// Streaming API
+// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add
+// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default.
+// If you would like to enable it explicitly, please add the following code to your app:
+// > iconv.enableStreamingAPI(require('stream'));
+iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) {
+    if (iconv.supportsStreams)
+        return;
+
+    // Dependency-inject stream module to create IconvLite stream classes.
+    var streams = __nccwpck_require__(42281)(stream_module);
+
+    // Not public API yet, but expose the stream classes.
+    iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream;
+    iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream;
+
+    // Streaming API.
+    iconv.encodeStream = function encodeStream(encoding, options) {
+        return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
     }
-    this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
-    return res;
+
+    iconv.decodeStream = function decodeStream(encoding, options) {
+        return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
+    }
+
+    iconv.supportsStreams = true;
 }
 
-InternalDecoderCesu8.prototype.end = function() {
-    var res = 0;
-    if (this.contBytes > 0)
-        res += this.defaultCharUnicode;
-    return res;
+// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments).
+var stream_module;
+try {
+    stream_module = __nccwpck_require__(2203);
+} catch (e) {}
+
+if (stream_module && stream_module.Transform) {
+    iconv.enableStreamingAPI(stream_module);
+
+} else {
+    // In rare cases where 'stream' module is not available by default, throw a helpful exception.
+    iconv.encodeStream = iconv.decodeStream = function() {
+        throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.");
+    };
 }
 
+if (false) {}
+
 
 /***/ }),
 
-/***/ 82473:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 42281:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
+
 var Buffer = (__nccwpck_require__(12803).Buffer);
 
-// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
-// correspond to encoded bytes (if 128 - then lower half is ASCII). 
+// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), 
+// we opt to dependency-inject it instead of creating a hard dependency.
+module.exports = function(stream_module) {
+    var Transform = stream_module.Transform;
 
-exports._sbcs = SBCSCodec;
-function SBCSCodec(codecOptions, iconv) {
-    if (!codecOptions)
-        throw new Error("SBCS codec is called without the data.")
-    
-    // Prepare char buffer for decoding.
-    if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
-        throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
-    
-    if (codecOptions.chars.length === 128) {
-        var asciiString = "";
-        for (var i = 0; i < 128; i++)
-            asciiString += String.fromCharCode(i);
-        codecOptions.chars = asciiString + codecOptions.chars;
+    // == Encoder stream =======================================================
+
+    function IconvLiteEncoderStream(conv, options) {
+        this.conv = conv;
+        options = options || {};
+        options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
+        Transform.call(this, options);
     }
 
-    this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
-    
-    // Encoding buffer.
-    var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
+    IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
+        constructor: { value: IconvLiteEncoderStream }
+    });
 
-    for (var i = 0; i < codecOptions.chars.length; i++)
-        encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
+    IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
+        if (typeof chunk != 'string')
+            return done(new Error("Iconv encoding stream needs strings as its input."));
+        try {
+            var res = this.conv.write(chunk);
+            if (res && res.length) this.push(res);
+            done();
+        }
+        catch (e) {
+            done(e);
+        }
+    }
 
-    this.encodeBuf = encodeBuf;
-}
+    IconvLiteEncoderStream.prototype._flush = function(done) {
+        try {
+            var res = this.conv.end();
+            if (res && res.length) this.push(res);
+            done();
+        }
+        catch (e) {
+            done(e);
+        }
+    }
 
-SBCSCodec.prototype.encoder = SBCSEncoder;
-SBCSCodec.prototype.decoder = SBCSDecoder;
+    IconvLiteEncoderStream.prototype.collect = function(cb) {
+        var chunks = [];
+        this.on('error', cb);
+        this.on('data', function(chunk) { chunks.push(chunk); });
+        this.on('end', function() {
+            cb(null, Buffer.concat(chunks));
+        });
+        return this;
+    }
 
 
-function SBCSEncoder(options, codec) {
-    this.encodeBuf = codec.encodeBuf;
-}
+    // == Decoder stream =======================================================
 
-SBCSEncoder.prototype.write = function(str) {
-    var buf = Buffer.alloc(str.length);
-    for (var i = 0; i < str.length; i++)
-        buf[i] = this.encodeBuf[str.charCodeAt(i)];
-    
-    return buf;
-}
+    function IconvLiteDecoderStream(conv, options) {
+        this.conv = conv;
+        options = options || {};
+        options.encoding = this.encoding = 'utf8'; // We output strings.
+        Transform.call(this, options);
+    }
 
-SBCSEncoder.prototype.end = function() {
-}
+    IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
+        constructor: { value: IconvLiteDecoderStream }
+    });
 
+    IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
+        if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))
+            return done(new Error("Iconv decoding stream needs buffers as its input."));
+        try {
+            var res = this.conv.write(chunk);
+            if (res && res.length) this.push(res, this.encoding);
+            done();
+        }
+        catch (e) {
+            done(e);
+        }
+    }
 
-function SBCSDecoder(options, codec) {
-    this.decodeBuf = codec.decodeBuf;
-}
+    IconvLiteDecoderStream.prototype._flush = function(done) {
+        try {
+            var res = this.conv.end();
+            if (res && res.length) this.push(res, this.encoding);                
+            done();
+        }
+        catch (e) {
+            done(e);
+        }
+    }
 
-SBCSDecoder.prototype.write = function(buf) {
-    // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
-    var decodeBuf = this.decodeBuf;
-    var newBuf = Buffer.alloc(buf.length*2);
-    var idx1 = 0, idx2 = 0;
-    for (var i = 0; i < buf.length; i++) {
-        idx1 = buf[i]*2; idx2 = i*2;
-        newBuf[idx2] = decodeBuf[idx1];
-        newBuf[idx2+1] = decodeBuf[idx1+1];
+    IconvLiteDecoderStream.prototype.collect = function(cb) {
+        var res = '';
+        this.on('error', cb);
+        this.on('data', function(chunk) { res += chunk; });
+        this.on('end', function() {
+            cb(null, res);
+        });
+        return this;
     }
-    return newBuf.toString('ucs2');
-}
 
-SBCSDecoder.prototype.end = function() {
-}
+    return {
+        IconvLiteEncoderStream: IconvLiteEncoderStream,
+        IconvLiteDecoderStream: IconvLiteDecoderStream,
+    };
+};
 
 
 /***/ }),
 
-/***/ 69487:
+/***/ 72024:
 /***/ ((module) => {
 
-"use strict";
+/**
+ * @preserve
+ * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013)
+ *
+ * @author Jens Taylor
+ * @see http://github.com/homebrewing/brauhaus-diff
+ * @author Gary Court
+ * @see http://github.com/garycourt/murmurhash-js
+ * @author Austin Appleby
+ * @see http://sites.google.com/site/murmurhash/
+ */
+(function(){
+    var cache;
 
+    // Call this function without `new` to use the cached object (good for
+    // single-threaded environments), or with `new` to create a new object.
+    //
+    // @param {string} key A UTF-16 or ASCII string
+    // @param {number} seed An optional positive integer
+    // @return {object} A MurmurHash3 object for incremental hashing
+    function MurmurHash3(key, seed) {
+        var m = this instanceof MurmurHash3 ? this : cache;
+        m.reset(seed)
+        if (typeof key === 'string' && key.length > 0) {
+            m.hash(key);
+        }
 
-// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
-module.exports = {
-  "437": "cp437",
-  "737": "cp737",
-  "775": "cp775",
-  "850": "cp850",
-  "852": "cp852",
-  "855": "cp855",
-  "856": "cp856",
-  "857": "cp857",
-  "858": "cp858",
-  "860": "cp860",
-  "861": "cp861",
-  "862": "cp862",
-  "863": "cp863",
-  "864": "cp864",
-  "865": "cp865",
-  "866": "cp866",
-  "869": "cp869",
-  "874": "windows874",
-  "922": "cp922",
-  "1046": "cp1046",
-  "1124": "cp1124",
-  "1125": "cp1125",
-  "1129": "cp1129",
-  "1133": "cp1133",
-  "1161": "cp1161",
-  "1162": "cp1162",
-  "1163": "cp1163",
-  "1250": "windows1250",
-  "1251": "windows1251",
-  "1252": "windows1252",
-  "1253": "windows1253",
-  "1254": "windows1254",
-  "1255": "windows1255",
-  "1256": "windows1256",
-  "1257": "windows1257",
-  "1258": "windows1258",
-  "28591": "iso88591",
-  "28592": "iso88592",
-  "28593": "iso88593",
-  "28594": "iso88594",
-  "28595": "iso88595",
-  "28596": "iso88596",
-  "28597": "iso88597",
-  "28598": "iso88598",
-  "28599": "iso88599",
-  "28600": "iso885910",
-  "28601": "iso885911",
-  "28603": "iso885913",
-  "28604": "iso885914",
-  "28605": "iso885915",
-  "28606": "iso885916",
-  "windows874": {
-    "type": "_sbcs",
-    "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  },
-  "win874": "windows874",
-  "cp874": "windows874",
-  "windows1250": {
-    "type": "_sbcs",
-    "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
-  },
-  "win1250": "windows1250",
-  "cp1250": "windows1250",
-  "windows1251": {
-    "type": "_sbcs",
-    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
-  },
-  "win1251": "windows1251",
-  "cp1251": "windows1251",
-  "windows1252": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "win1252": "windows1252",
-  "cp1252": "windows1252",
-  "windows1253": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
-  },
-  "win1253": "windows1253",
-  "cp1253": "windows1253",
-  "windows1254": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
-  },
-  "win1254": "windows1254",
-  "cp1254": "windows1254",
-  "windows1255": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
-  },
-  "win1255": "windows1255",
-  "cp1255": "windows1255",
-  "windows1256": {
-    "type": "_sbcs",
-    "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"
-  },
-  "win1256": "windows1256",
-  "cp1256": "windows1256",
-  "windows1257": {
-    "type": "_sbcs",
-    "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
-  },
-  "win1257": "windows1257",
-  "cp1257": "windows1257",
-  "windows1258": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
-  },
-  "win1258": "windows1258",
-  "cp1258": "windows1258",
-  "iso88591": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "cp28591": "iso88591",
-  "iso88592": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
-  },
-  "cp28592": "iso88592",
-  "iso88593": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
-  },
-  "cp28593": "iso88593",
-  "iso88594": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
-  },
-  "cp28594": "iso88594",
-  "iso88595": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
-  },
-  "cp28595": "iso88595",
-  "iso88596": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
-  },
-  "cp28596": "iso88596",
-  "iso88597": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
-  },
-  "cp28597": "iso88597",
-  "iso88598": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
-  },
-  "cp28598": "iso88598",
-  "iso88599": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
-  },
-  "cp28599": "iso88599",
-  "iso885910": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
-  },
-  "cp28600": "iso885910",
-  "iso885911": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  },
-  "cp28601": "iso885911",
-  "iso885913": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
-  },
-  "cp28603": "iso885913",
-  "iso885914": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
-  },
-  "cp28604": "iso885914",
-  "iso885915": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "cp28605": "iso885915",
-  "iso885916": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
-  },
-  "cp28606": "iso885916",
-  "cp437": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm437": "cp437",
-  "csibm437": "cp437",
-  "cp737": {
-    "type": "_sbcs",
-    "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
-  },
-  "ibm737": "cp737",
-  "csibm737": "cp737",
-  "cp775": {
-    "type": "_sbcs",
-    "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "
-  },
-  "ibm775": "cp775",
-  "csibm775": "cp775",
-  "cp850": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm850": "cp850",
-  "csibm850": "cp850",
-  "cp852": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "
-  },
-  "ibm852": "cp852",
-  "csibm852": "cp852",
-  "cp855": {
-    "type": "_sbcs",
-    "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "
-  },
-  "ibm855": "cp855",
-  "csibm855": "cp855",
-  "cp856": {
-    "type": "_sbcs",
-    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm856": "cp856",
-  "csibm856": "cp856",
-  "cp857": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm857": "cp857",
-  "csibm857": "cp857",
-  "cp858": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm858": "cp858",
-  "csibm858": "cp858",
-  "cp860": {
-    "type": "_sbcs",
-    "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm860": "cp860",
-  "csibm860": "cp860",
-  "cp861": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm861": "cp861",
-  "csibm861": "cp861",
-  "cp862": {
-    "type": "_sbcs",
-    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm862": "cp862",
-  "csibm862": "cp862",
-  "cp863": {
-    "type": "_sbcs",
-    "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm863": "cp863",
-  "csibm863": "cp863",
-  "cp864": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
-  },
-  "ibm864": "cp864",
-  "csibm864": "cp864",
-  "cp865": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm865": "cp865",
-  "csibm865": "cp865",
-  "cp866": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
-  },
-  "ibm866": "cp866",
-  "csibm866": "cp866",
-  "cp869": {
-    "type": "_sbcs",
-    "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "
-  },
-  "ibm869": "cp869",
-  "csibm869": "cp869",
-  "cp922": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
-  },
-  "ibm922": "cp922",
-  "csibm922": "cp922",
-  "cp1046": {
-    "type": "_sbcs",
-    "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
-  },
-  "ibm1046": "cp1046",
-  "csibm1046": "cp1046",
-  "cp1124": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
-  },
-  "ibm1124": "cp1124",
-  "csibm1124": "cp1124",
-  "cp1125": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
-  },
-  "ibm1125": "cp1125",
-  "csibm1125": "cp1125",
-  "cp1129": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
-  },
-  "ibm1129": "cp1129",
-  "csibm1129": "cp1129",
-  "cp1133": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
-  },
-  "ibm1133": "cp1133",
-  "csibm1133": "cp1133",
-  "cp1161": {
-    "type": "_sbcs",
-    "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
-  },
-  "ibm1161": "cp1161",
-  "csibm1161": "cp1161",
-  "cp1162": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  },
-  "ibm1162": "cp1162",
-  "csibm1162": "cp1162",
-  "cp1163": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
-  },
-  "ibm1163": "cp1163",
-  "csibm1163": "cp1163",
-  "maccroatian": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
-  },
-  "maccyrillic": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
-  },
-  "macgreek": {
-    "type": "_sbcs",
-    "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
-  },
-  "maciceland": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macroman": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macromania": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macthai": {
-    "type": "_sbcs",
-    "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
-  },
-  "macturkish": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macukraine": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
-  },
-  "koi8r": {
-    "type": "_sbcs",
-    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "koi8u": {
-    "type": "_sbcs",
-    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "koi8ru": {
-    "type": "_sbcs",
-    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "koi8t": {
-    "type": "_sbcs",
-    "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "armscii8": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
-  },
-  "rk1048": {
-    "type": "_sbcs",
-    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
-  },
-  "tcvn": {
-    "type": "_sbcs",
-    "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
-  },
-  "georgianacademy": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "georgianps": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "pt154": {
-    "type": "_sbcs",
-    "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
-  },
-  "viscii": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
-  },
-  "iso646cn": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
-  },
-  "iso646jp": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������"
-  },
-  "hproman8": {
-    "type": "_sbcs",
-    "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
-  },
-  "macintosh": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "ascii": {
-    "type": "_sbcs",
-    "chars": "��������������������������������������������������������������������������������������������������������������������������������"
-  },
-  "tis620": {
-    "type": "_sbcs",
-    "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  }
-}
+        if (m !== this) {
+            return m;
+        }
+    };
 
-/***/ }),
+    // Incrementally add a string to this hash
+    //
+    // @param {string} key A UTF-16 or ASCII string
+    // @return {object} this
+    MurmurHash3.prototype.hash = function(key) {
+        var h1, k1, i, top, len;
 
-/***/ 97083:
-/***/ ((module) => {
+        len = key.length;
+        this.len += len;
+
+        k1 = this.k1;
+        i = 0;
+        switch (this.rem) {
+            case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0;
+            case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0;
+            case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0;
+            case 3:
+                k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0;
+                k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0;
+        }
 
-"use strict";
+        this.rem = (len + this.rem) & 3; // & 3 is same as % 4
+        len -= this.rem;
+        if (len > 0) {
+            h1 = this.h1;
+            while (1) {
+                k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff;
+                k1 = (k1 << 15) | (k1 >>> 17);
+                k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff;
 
+                h1 ^= k1;
+                h1 = (h1 << 13) | (h1 >>> 19);
+                h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff;
 
-// Manually added data to be used by sbcs codec in addition to generated one.
+                if (i >= len) {
+                    break;
+                }
 
-module.exports = {
-    // Not supported by iconv, not sure why.
-    "10029": "maccenteuro",
-    "maccenteuro": {
-        "type": "_sbcs",
-        "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
-    },
+                k1 = ((key.charCodeAt(i++) & 0xffff)) ^
+                     ((key.charCodeAt(i++) & 0xffff) << 8) ^
+                     ((key.charCodeAt(i++) & 0xffff) << 16);
+                top = key.charCodeAt(i++);
+                k1 ^= ((top & 0xff) << 24) ^
+                      ((top & 0xff00) >> 8);
+            }
 
-    "808": "cp808",
-    "ibm808": "cp808",
-    "cp808": {
-        "type": "_sbcs",
-        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
-    },
+            k1 = 0;
+            switch (this.rem) {
+                case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16;
+                case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8;
+                case 1: k1 ^= (key.charCodeAt(i) & 0xffff);
+            }
 
-    "mik": {
-        "type": "_sbcs",
-        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-    },
+            this.h1 = h1;
+        }
 
-    "cp720": {
-        "type": "_sbcs",
-        "chars": "\x80\x81éâ\x84à\x86çêëèïî\x8d\x8e\x8f\x90\u0651\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\u064b\u064c\u064d\u064e\u064f\u0650≈°∙·√ⁿ²■\u00a0"
-    },
+        this.k1 = k1;
+        return this;
+    };
 
-    // Aliases of generated encodings.
-    "ascii8bit": "ascii",
-    "usascii": "ascii",
-    "ansix34": "ascii",
-    "ansix341968": "ascii",
-    "ansix341986": "ascii",
-    "csascii": "ascii",
-    "cp367": "ascii",
-    "ibm367": "ascii",
-    "isoir6": "ascii",
-    "iso646us": "ascii",
-    "iso646irv": "ascii",
-    "us": "ascii",
+    // Get the result of this hash
+    //
+    // @return {number} The 32-bit hash
+    MurmurHash3.prototype.result = function() {
+        var k1, h1;
+        
+        k1 = this.k1;
+        h1 = this.h1;
 
-    "latin1": "iso88591",
-    "latin2": "iso88592",
-    "latin3": "iso88593",
-    "latin4": "iso88594",
-    "latin5": "iso88599",
-    "latin6": "iso885910",
-    "latin7": "iso885913",
-    "latin8": "iso885914",
-    "latin9": "iso885915",
-    "latin10": "iso885916",
+        if (k1 > 0) {
+            k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff;
+            k1 = (k1 << 15) | (k1 >>> 17);
+            k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff;
+            h1 ^= k1;
+        }
 
-    "csisolatin1": "iso88591",
-    "csisolatin2": "iso88592",
-    "csisolatin3": "iso88593",
-    "csisolatin4": "iso88594",
-    "csisolatincyrillic": "iso88595",
-    "csisolatinarabic": "iso88596",
-    "csisolatingreek" : "iso88597",
-    "csisolatinhebrew": "iso88598",
-    "csisolatin5": "iso88599",
-    "csisolatin6": "iso885910",
+        h1 ^= this.len;
 
-    "l1": "iso88591",
-    "l2": "iso88592",
-    "l3": "iso88593",
-    "l4": "iso88594",
-    "l5": "iso88599",
-    "l6": "iso885910",
-    "l7": "iso885913",
-    "l8": "iso885914",
-    "l9": "iso885915",
-    "l10": "iso885916",
+        h1 ^= h1 >>> 16;
+        h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff;
+        h1 ^= h1 >>> 13;
+        h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff;
+        h1 ^= h1 >>> 16;
 
-    "isoir14": "iso646jp",
-    "isoir57": "iso646cn",
-    "isoir100": "iso88591",
-    "isoir101": "iso88592",
-    "isoir109": "iso88593",
-    "isoir110": "iso88594",
-    "isoir144": "iso88595",
-    "isoir127": "iso88596",
-    "isoir126": "iso88597",
-    "isoir138": "iso88598",
-    "isoir148": "iso88599",
-    "isoir157": "iso885910",
-    "isoir166": "tis620",
-    "isoir179": "iso885913",
-    "isoir199": "iso885914",
-    "isoir203": "iso885915",
-    "isoir226": "iso885916",
+        return h1 >>> 0;
+    };
 
-    "cp819": "iso88591",
-    "ibm819": "iso88591",
+    // Reset the hash object for reuse
+    //
+    // @param {number} seed An optional positive integer
+    MurmurHash3.prototype.reset = function(seed) {
+        this.h1 = typeof seed === 'number' ? seed : 0;
+        this.rem = this.k1 = this.len = 0;
+        return this;
+    };
 
-    "cyrillic": "iso88595",
+    // A cached object to use. This can be safely used if you're in a single-
+    // threaded environment, otherwise you need to create new hashes to use.
+    cache = new MurmurHash3();
 
-    "arabic": "iso88596",
-    "arabic8": "iso88596",
-    "ecma114": "iso88596",
-    "asmo708": "iso88596",
+    if (true) {
+        module.exports = MurmurHash3;
+    } else {}
+}());
 
-    "greek" : "iso88597",
-    "greek8" : "iso88597",
-    "ecma118" : "iso88597",
-    "elot928" : "iso88597",
 
-    "hebrew": "iso88598",
-    "hebrew8": "iso88598",
+/***/ }),
 
-    "turkish": "iso88599",
-    "turkish8": "iso88599",
+/***/ 68850:
+/***/ ((__unused_webpack_module, exports) => {
 
-    "thai": "iso885911",
-    "thai8": "iso885911",
+"use strict";
 
-    "celtic": "iso885914",
-    "celtic8": "iso885914",
-    "isoceltic": "iso885914",
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AddressError = void 0;
+class AddressError extends Error {
+    constructor(message, parseMessage) {
+        super(message);
+        this.name = 'AddressError';
+        if (parseMessage !== null) {
+            this.parseMessage = parseMessage;
+        }
+    }
+}
+exports.AddressError = AddressError;
+//# sourceMappingURL=address-error.js.map
 
-    "tis6200": "tis620",
-    "tis62025291": "tis620",
-    "tis62025330": "tis620",
+/***/ }),
 
-    "10000": "macroman",
-    "10006": "macgreek",
-    "10007": "maccyrillic",
-    "10079": "maciceland",
-    "10081": "macturkish",
+/***/ 45864:
+/***/ ((__unused_webpack_module, exports) => {
 
-    "cspc8codepage437": "cp437",
-    "cspc775baltic": "cp775",
-    "cspc850multilingual": "cp850",
-    "cspcp852": "cp852",
-    "cspc862latinhebrew": "cp862",
-    "cpgr": "cp869",
+"use strict";
 
-    "msee": "cp1250",
-    "mscyrl": "cp1251",
-    "msansi": "cp1252",
-    "msgreek": "cp1253",
-    "msturk": "cp1254",
-    "mshebr": "cp1255",
-    "msarab": "cp1256",
-    "winbaltrim": "cp1257",
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isCorrect = exports.isInSubnet = void 0;
+function isInSubnet(address) {
+    if (this.subnetMask < address.subnetMask) {
+        return false;
+    }
+    if (this.mask(address.subnetMask) === address.mask()) {
+        return true;
+    }
+    return false;
+}
+exports.isInSubnet = isInSubnet;
+function isCorrect(defaultBits) {
+    return function () {
+        if (this.addressMinusSuffix !== this.correctForm()) {
+            return false;
+        }
+        if (this.subnetMask === defaultBits && !this.parsedSubnet) {
+            return true;
+        }
+        return this.parsedSubnet === String(this.subnetMask);
+    };
+}
+exports.isCorrect = isCorrect;
+//# sourceMappingURL=common.js.map
 
-    "cp20866": "koi8r",
-    "20866": "koi8r",
-    "ibm878": "koi8r",
-    "cskoi8r": "koi8r",
+/***/ }),
 
-    "cp21866": "koi8u",
-    "21866": "koi8u",
-    "ibm1168": "koi8u",
+/***/ 79253:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-    "strk10482002": "rk1048",
+"use strict";
 
-    "tcvn5712": "tcvn",
-    "tcvn57121": "tcvn",
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0;
+const ipv4_1 = __nccwpck_require__(17946);
+Object.defineProperty(exports, "Address4", ({ enumerable: true, get: function () { return ipv4_1.Address4; } }));
+const ipv6_1 = __nccwpck_require__(38096);
+Object.defineProperty(exports, "Address6", ({ enumerable: true, get: function () { return ipv6_1.Address6; } }));
+const address_error_1 = __nccwpck_require__(68850);
+Object.defineProperty(exports, "AddressError", ({ enumerable: true, get: function () { return address_error_1.AddressError; } }));
+const helpers = __importStar(__nccwpck_require__(20339));
+exports.v6 = { helpers };
+//# sourceMappingURL=ip-address.js.map
 
-    "gb198880": "iso646cn",
-    "cn": "iso646cn",
+/***/ }),
 
-    "csiso14jisc6220ro": "iso646jp",
-    "jisc62201969ro": "iso646jp",
-    "jp": "iso646jp",
+/***/ 17946:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-    "cshproman8": "hproman8",
-    "r8": "hproman8",
-    "roman8": "hproman8",
-    "xroman8": "hproman8",
-    "ibm1051": "hproman8",
+"use strict";
 
-    "mac": "macintosh",
-    "csmacintosh": "macintosh",
+/* eslint-disable no-param-reassign */
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
 };
-
-
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Address4 = void 0;
+const common = __importStar(__nccwpck_require__(45864));
+const constants = __importStar(__nccwpck_require__(66437));
+const address_error_1 = __nccwpck_require__(68850);
+const jsbn_1 = __nccwpck_require__(95947);
+const sprintf_js_1 = __nccwpck_require__(72701);
+/**
+ * Represents an IPv4 address
+ * @class Address4
+ * @param {string} address - An IPv4 address string
+ */
+class Address4 {
+    constructor(address) {
+        this.groups = constants.GROUPS;
+        this.parsedAddress = [];
+        this.parsedSubnet = '';
+        this.subnet = '/32';
+        this.subnetMask = 32;
+        this.v4 = true;
+        /**
+         * Returns true if the address is correct, false otherwise
+         * @memberof Address4
+         * @instance
+         * @returns {Boolean}
+         */
+        this.isCorrect = common.isCorrect(constants.BITS);
+        /**
+         * Returns true if the given address is in the subnet of the current address
+         * @memberof Address4
+         * @instance
+         * @returns {boolean}
+         */
+        this.isInSubnet = common.isInSubnet;
+        this.address = address;
+        const subnet = constants.RE_SUBNET_STRING.exec(address);
+        if (subnet) {
+            this.parsedSubnet = subnet[0].replace('/', '');
+            this.subnetMask = parseInt(this.parsedSubnet, 10);
+            this.subnet = `/${this.subnetMask}`;
+            if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
+                throw new address_error_1.AddressError('Invalid subnet mask.');
+            }
+            address = address.replace(constants.RE_SUBNET_STRING, '');
+        }
+        this.addressMinusSuffix = address;
+        this.parsedAddress = this.parse(address);
+    }
+    static isValid(address) {
+        try {
+            // eslint-disable-next-line no-new
+            new Address4(address);
+            return true;
+        }
+        catch (e) {
+            return false;
+        }
+    }
+    /*
+     * Parses a v4 address
+     */
+    parse(address) {
+        const groups = address.split('.');
+        if (!address.match(constants.RE_ADDRESS)) {
+            throw new address_error_1.AddressError('Invalid IPv4 address.');
+        }
+        return groups;
+    }
+    /**
+     * Returns the correct form of an address
+     * @memberof Address4
+     * @instance
+     * @returns {String}
+     */
+    correctForm() {
+        return this.parsedAddress.map((part) => parseInt(part, 10)).join('.');
+    }
+    /**
+     * Converts a hex string to an IPv4 address object
+     * @memberof Address4
+     * @static
+     * @param {string} hex - a hex string to convert
+     * @returns {Address4}
+     */
+    static fromHex(hex) {
+        const padded = hex.replace(/:/g, '').padStart(8, '0');
+        const groups = [];
+        let i;
+        for (i = 0; i < 8; i += 2) {
+            const h = padded.slice(i, i + 2);
+            groups.push(parseInt(h, 16));
+        }
+        return new Address4(groups.join('.'));
+    }
+    /**
+     * Converts an integer into a IPv4 address object
+     * @memberof Address4
+     * @static
+     * @param {integer} integer - a number to convert
+     * @returns {Address4}
+     */
+    static fromInteger(integer) {
+        return Address4.fromHex(integer.toString(16));
+    }
+    /**
+     * Return an address from in-addr.arpa form
+     * @memberof Address4
+     * @static
+     * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
+     * @returns {Adress4}
+     * @example
+     * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
+     * address.correctForm(); // '192.0.2.42'
+     */
+    static fromArpa(arpaFormAddress) {
+        // remove ending ".in-addr.arpa." or just "."
+        const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, '');
+        const address = leader.split('.').reverse().join('.');
+        return new Address4(address);
+    }
+    /**
+     * Converts an IPv4 address object to a hex string
+     * @memberof Address4
+     * @instance
+     * @returns {String}
+     */
+    toHex() {
+        return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':');
+    }
+    /**
+     * Converts an IPv4 address object to an array of bytes
+     * @memberof Address4
+     * @instance
+     * @returns {Array}
+     */
+    toArray() {
+        return this.parsedAddress.map((part) => parseInt(part, 10));
+    }
+    /**
+     * Converts an IPv4 address object to an IPv6 address group
+     * @memberof Address4
+     * @instance
+     * @returns {String}
+     */
+    toGroup6() {
+        const output = [];
+        let i;
+        for (i = 0; i < constants.GROUPS; i += 2) {
+            const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10));
+            output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16)));
+        }
+        return output.join(':');
+    }
+    /**
+     * Returns the address as a BigInteger
+     * @memberof Address4
+     * @instance
+     * @returns {BigInteger}
+     */
+    bigInteger() {
+        return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16);
+    }
+    /**
+     * Helper function getting start address.
+     * @memberof Address4
+     * @instance
+     * @returns {BigInteger}
+     */
+    _startAddress() {
+        return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2);
+    }
+    /**
+     * The first address in the range given by this address' subnet.
+     * Often referred to as the Network Address.
+     * @memberof Address4
+     * @instance
+     * @returns {Address4}
+     */
+    startAddress() {
+        return Address4.fromBigInteger(this._startAddress());
+    }
+    /**
+     * The first host address in the range given by this address's subnet ie
+     * the first address after the Network Address
+     * @memberof Address4
+     * @instance
+     * @returns {Address4}
+     */
+    startAddressExclusive() {
+        const adjust = new jsbn_1.BigInteger('1');
+        return Address4.fromBigInteger(this._startAddress().add(adjust));
+    }
+    /**
+     * Helper function getting end address.
+     * @memberof Address4
+     * @instance
+     * @returns {BigInteger}
+     */
+    _endAddress() {
+        return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2);
+    }
+    /**
+     * The last address in the range given by this address' subnet
+     * Often referred to as the Broadcast
+     * @memberof Address4
+     * @instance
+     * @returns {Address4}
+     */
+    endAddress() {
+        return Address4.fromBigInteger(this._endAddress());
+    }
+    /**
+     * The last host address in the range given by this address's subnet ie
+     * the last address prior to the Broadcast Address
+     * @memberof Address4
+     * @instance
+     * @returns {Address4}
+     */
+    endAddressExclusive() {
+        const adjust = new jsbn_1.BigInteger('1');
+        return Address4.fromBigInteger(this._endAddress().subtract(adjust));
+    }
+    /**
+     * Converts a BigInteger to a v4 address object
+     * @memberof Address4
+     * @static
+     * @param {BigInteger} bigInteger - a BigInteger to convert
+     * @returns {Address4}
+     */
+    static fromBigInteger(bigInteger) {
+        return Address4.fromInteger(parseInt(bigInteger.toString(), 10));
+    }
+    /**
+     * Returns the first n bits of the address, defaulting to the
+     * subnet mask
+     * @memberof Address4
+     * @instance
+     * @returns {String}
+     */
+    mask(mask) {
+        if (mask === undefined) {
+            mask = this.subnetMask;
+        }
+        return this.getBitsBase2(0, mask);
+    }
+    /**
+     * Returns the bits in the given range as a base-2 string
+     * @memberof Address4
+     * @instance
+     * @returns {string}
+     */
+    getBitsBase2(start, end) {
+        return this.binaryZeroPad().slice(start, end);
+    }
+    /**
+     * Return the reversed ip6.arpa form of the address
+     * @memberof Address4
+     * @param {Object} options
+     * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
+     * @instance
+     * @returns {String}
+     */
+    reverseForm(options) {
+        if (!options) {
+            options = {};
+        }
+        const reversed = this.correctForm().split('.').reverse().join('.');
+        if (options.omitSuffix) {
+            return reversed;
+        }
+        return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed);
+    }
+    /**
+     * Returns true if the given address is a multicast address
+     * @memberof Address4
+     * @instance
+     * @returns {boolean}
+     */
+    isMulticast() {
+        return this.isInSubnet(new Address4('224.0.0.0/4'));
+    }
+    /**
+     * Returns a zero-padded base-2 string representation of the address
+     * @memberof Address4
+     * @instance
+     * @returns {string}
+     */
+    binaryZeroPad() {
+        return this.bigInteger().toString(2).padStart(constants.BITS, '0');
+    }
+    /**
+     * Groups an IPv4 address for inclusion at the end of an IPv6 address
+     * @returns {String}
+     */
+    groupForV6() {
+        const segments = this.parsedAddress;
+        return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.')));
+    }
+}
+exports.Address4 = Address4;
+//# sourceMappingURL=ipv4.js.map
 
 /***/ }),
 
-/***/ 8771:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 38096:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
 "use strict";
 
-var Buffer = (__nccwpck_require__(12803).Buffer);
-
-// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js
-
-// == UTF16-BE codec. ==========================================================
-
-exports.utf16be = Utf16BECodec;
-function Utf16BECodec() {
+/* eslint-disable prefer-destructuring */
+/* eslint-disable no-param-reassign */
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
+    }
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Address6 = void 0;
+const common = __importStar(__nccwpck_require__(45864));
+const constants4 = __importStar(__nccwpck_require__(66437));
+const constants6 = __importStar(__nccwpck_require__(75280));
+const helpers = __importStar(__nccwpck_require__(20339));
+const ipv4_1 = __nccwpck_require__(17946);
+const regular_expressions_1 = __nccwpck_require__(72016);
+const address_error_1 = __nccwpck_require__(68850);
+const jsbn_1 = __nccwpck_require__(95947);
+const sprintf_js_1 = __nccwpck_require__(72701);
+function assert(condition) {
+    if (!condition) {
+        throw new Error('Assertion failed.');
+    }
 }
-
-Utf16BECodec.prototype.encoder = Utf16BEEncoder;
-Utf16BECodec.prototype.decoder = Utf16BEDecoder;
-Utf16BECodec.prototype.bomAware = true;
-
-
-// -- Encoding
-
-function Utf16BEEncoder() {
+function addCommas(number) {
+    const r = /(\d+)(\d{3})/;
+    while (r.test(number)) {
+        number = number.replace(r, '$1,$2');
+    }
+    return number;
 }
-
-Utf16BEEncoder.prototype.write = function(str) {
-    var buf = Buffer.from(str, 'ucs2');
-    for (var i = 0; i < buf.length; i += 2) {
-        var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
+function spanLeadingZeroes4(n) {
+    n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2');
+    n = n.replace(/^(0{1,})(0)$/, '$1$2');
+    return n;
+}
+/*
+ * A helper function to compact an array
+ */
+function compact(address, slice) {
+    const s1 = [];
+    const s2 = [];
+    let i;
+    for (i = 0; i < address.length; i++) {
+        if (i < slice[0]) {
+            s1.push(address[i]);
+        }
+        else if (i > slice[1]) {
+            s2.push(address[i]);
+        }
+    }
+    return s1.concat(['compact']).concat(s2);
+}
+function paddedHex(octet) {
+    return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16));
+}
+function unsignByte(b) {
+    // eslint-disable-next-line no-bitwise
+    return b & 0xff;
+}
+/**
+ * Represents an IPv6 address
+ * @class Address6
+ * @param {string} address - An IPv6 address string
+ * @param {number} [groups=8] - How many octets to parse
+ * @example
+ * var address = new Address6('2001::/32');
+ */
+class Address6 {
+    constructor(address, optionalGroups) {
+        this.addressMinusSuffix = '';
+        this.parsedSubnet = '';
+        this.subnet = '/128';
+        this.subnetMask = 128;
+        this.v4 = false;
+        this.zone = '';
+        // #region Attributes
+        /**
+         * Returns true if the given address is in the subnet of the current address
+         * @memberof Address6
+         * @instance
+         * @returns {boolean}
+         */
+        this.isInSubnet = common.isInSubnet;
+        /**
+         * Returns true if the address is correct, false otherwise
+         * @memberof Address6
+         * @instance
+         * @returns {boolean}
+         */
+        this.isCorrect = common.isCorrect(constants6.BITS);
+        if (optionalGroups === undefined) {
+            this.groups = constants6.GROUPS;
+        }
+        else {
+            this.groups = optionalGroups;
+        }
+        this.address = address;
+        const subnet = constants6.RE_SUBNET_STRING.exec(address);
+        if (subnet) {
+            this.parsedSubnet = subnet[0].replace('/', '');
+            this.subnetMask = parseInt(this.parsedSubnet, 10);
+            this.subnet = `/${this.subnetMask}`;
+            if (Number.isNaN(this.subnetMask) ||
+                this.subnetMask < 0 ||
+                this.subnetMask > constants6.BITS) {
+                throw new address_error_1.AddressError('Invalid subnet mask.');
+            }
+            address = address.replace(constants6.RE_SUBNET_STRING, '');
+        }
+        else if (/\//.test(address)) {
+            throw new address_error_1.AddressError('Invalid subnet mask.');
+        }
+        const zone = constants6.RE_ZONE_STRING.exec(address);
+        if (zone) {
+            this.zone = zone[0];
+            address = address.replace(constants6.RE_ZONE_STRING, '');
+        }
+        this.addressMinusSuffix = address;
+        this.parsedAddress = this.parse(this.addressMinusSuffix);
+    }
+    static isValid(address) {
+        try {
+            // eslint-disable-next-line no-new
+            new Address6(address);
+            return true;
+        }
+        catch (e) {
+            return false;
+        }
+    }
+    /**
+     * Convert a BigInteger to a v6 address object
+     * @memberof Address6
+     * @static
+     * @param {BigInteger} bigInteger - a BigInteger to convert
+     * @returns {Address6}
+     * @example
+     * var bigInteger = new BigInteger('1000000000000');
+     * var address = Address6.fromBigInteger(bigInteger);
+     * address.correctForm(); // '::e8:d4a5:1000'
+     */
+    static fromBigInteger(bigInteger) {
+        const hex = bigInteger.toString(16).padStart(32, '0');
+        const groups = [];
+        let i;
+        for (i = 0; i < constants6.GROUPS; i++) {
+            groups.push(hex.slice(i * 4, (i + 1) * 4));
+        }
+        return new Address6(groups.join(':'));
+    }
+    /**
+     * Convert a URL (with optional port number) to an address object
+     * @memberof Address6
+     * @static
+     * @param {string} url - a URL with optional port number
+     * @example
+     * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
+     * addressAndPort.address.correctForm(); // 'ffff::'
+     * addressAndPort.port; // 8080
+     */
+    static fromURL(url) {
+        let host;
+        let port = null;
+        let result;
+        // If we have brackets parse them and find a port
+        if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) {
+            result = constants6.RE_URL_WITH_PORT.exec(url);
+            if (result === null) {
+                return {
+                    error: 'failed to parse address with port',
+                    address: null,
+                    port: null,
+                };
+            }
+            host = result[1];
+            port = result[2];
+            // If there's a URL extract the address
+        }
+        else if (url.indexOf('/') !== -1) {
+            // Remove the protocol prefix
+            url = url.replace(/^[a-z0-9]+:\/\//, '');
+            // Parse the address
+            result = constants6.RE_URL.exec(url);
+            if (result === null) {
+                return {
+                    error: 'failed to parse address from URL',
+                    address: null,
+                    port: null,
+                };
+            }
+            host = result[1];
+            // Otherwise just assign the URL to the host and let the library parse it
+        }
+        else {
+            host = url;
+        }
+        // If there's a port convert it to an integer
+        if (port) {
+            port = parseInt(port, 10);
+            // squelch out of range ports
+            if (port < 0 || port > 65536) {
+                port = null;
+            }
+        }
+        else {
+            // Standardize `undefined` to `null`
+            port = null;
+        }
+        return {
+            address: new Address6(host),
+            port,
+        };
+    }
+    /**
+     * Create an IPv6-mapped address given an IPv4 address
+     * @memberof Address6
+     * @static
+     * @param {string} address - An IPv4 address string
+     * @returns {Address6}
+     * @example
+     * var address = Address6.fromAddress4('192.168.0.1');
+     * address.correctForm(); // '::ffff:c0a8:1'
+     * address.to4in6(); // '::ffff:192.168.0.1'
+     */
+    static fromAddress4(address) {
+        const address4 = new ipv4_1.Address4(address);
+        const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
+        return new Address6(`::ffff:${address4.correctForm()}/${mask6}`);
+    }
+    /**
+     * Return an address from ip6.arpa form
+     * @memberof Address6
+     * @static
+     * @param {string} arpaFormAddress - an 'ip6.arpa' form address
+     * @returns {Adress6}
+     * @example
+     * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
+     * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
+     */
+    static fromArpa(arpaFormAddress) {
+        // remove ending ".ip6.arpa." or just "."
+        let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, '');
+        const semicolonAmount = 7;
+        // correct ip6.arpa form with ending removed will be 63 characters
+        if (address.length !== 63) {
+            throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
+        }
+        const parts = address.split('.').reverse();
+        for (let i = semicolonAmount; i > 0; i--) {
+            const insertIndex = i * 4;
+            parts.splice(insertIndex, 0, ':');
+        }
+        address = parts.join('');
+        return new Address6(address);
+    }
+    /**
+     * Return the Microsoft UNC transcription of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String} the Microsoft UNC transcription of the address
+     */
+    microsoftTranscription() {
+        return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-'));
+    }
+    /**
+     * Return the first n bits of the address, defaulting to the subnet mask
+     * @memberof Address6
+     * @instance
+     * @param {number} [mask=subnet] - the number of bits to mask
+     * @returns {String} the first n bits of the address as a string
+     */
+    mask(mask = this.subnetMask) {
+        return this.getBitsBase2(0, mask);
+    }
+    /**
+     * Return the number of possible subnets of a given size in the address
+     * @memberof Address6
+     * @instance
+     * @param {number} [size=128] - the subnet size
+     * @returns {String}
+     */
+    // TODO: probably useful to have a numeric version of this too
+    possibleSubnets(subnetSize = 128) {
+        const availableBits = constants6.BITS - this.subnetMask;
+        const subnetBits = Math.abs(subnetSize - constants6.BITS);
+        const subnetPowers = availableBits - subnetBits;
+        if (subnetPowers < 0) {
+            return '0';
+        }
+        return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10));
+    }
+    /**
+     * Helper function getting start address.
+     * @memberof Address6
+     * @instance
+     * @returns {BigInteger}
+     */
+    _startAddress() {
+        return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2);
+    }
+    /**
+     * The first address in the range given by this address' subnet
+     * Often referred to as the Network Address.
+     * @memberof Address6
+     * @instance
+     * @returns {Address6}
+     */
+    startAddress() {
+        return Address6.fromBigInteger(this._startAddress());
+    }
+    /**
+     * The first host address in the range given by this address's subnet ie
+     * the first address after the Network Address
+     * @memberof Address6
+     * @instance
+     * @returns {Address6}
+     */
+    startAddressExclusive() {
+        const adjust = new jsbn_1.BigInteger('1');
+        return Address6.fromBigInteger(this._startAddress().add(adjust));
+    }
+    /**
+     * Helper function getting end address.
+     * @memberof Address6
+     * @instance
+     * @returns {BigInteger}
+     */
+    _endAddress() {
+        return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2);
+    }
+    /**
+     * The last address in the range given by this address' subnet
+     * Often referred to as the Broadcast
+     * @memberof Address6
+     * @instance
+     * @returns {Address6}
+     */
+    endAddress() {
+        return Address6.fromBigInteger(this._endAddress());
+    }
+    /**
+     * The last host address in the range given by this address's subnet ie
+     * the last address prior to the Broadcast Address
+     * @memberof Address6
+     * @instance
+     * @returns {Address6}
+     */
+    endAddressExclusive() {
+        const adjust = new jsbn_1.BigInteger('1');
+        return Address6.fromBigInteger(this._endAddress().subtract(adjust));
+    }
+    /**
+     * Return the scope of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    getScope() {
+        let scope = constants6.SCOPES[this.getBits(12, 16).intValue()];
+        if (this.getType() === 'Global unicast' && scope !== 'Link local') {
+            scope = 'Global';
+        }
+        return scope || 'Unknown';
     }
-    return buf;
-}
-
-Utf16BEEncoder.prototype.end = function() {
-}
-
-
-// -- Decoding
-
-function Utf16BEDecoder() {
-    this.overflowByte = -1;
-}
-
-Utf16BEDecoder.prototype.write = function(buf) {
-    if (buf.length == 0)
-        return '';
-
-    var buf2 = Buffer.alloc(buf.length + 1),
-        i = 0, j = 0;
-
-    if (this.overflowByte !== -1) {
-        buf2[0] = buf[0];
-        buf2[1] = this.overflowByte;
-        i = 1; j = 2;
+    /**
+     * Return the type of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    getType() {
+        for (const subnet of Object.keys(constants6.TYPES)) {
+            if (this.isInSubnet(new Address6(subnet))) {
+                return constants6.TYPES[subnet];
+            }
+        }
+        return 'Global unicast';
     }
-
-    for (; i < buf.length-1; i += 2, j+= 2) {
-        buf2[j] = buf[i+1];
-        buf2[j+1] = buf[i];
+    /**
+     * Return the bits in the given range as a BigInteger
+     * @memberof Address6
+     * @instance
+     * @returns {BigInteger}
+     */
+    getBits(start, end) {
+        return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2);
+    }
+    /**
+     * Return the bits in the given range as a base-2 string
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    getBitsBase2(start, end) {
+        return this.binaryZeroPad().slice(start, end);
+    }
+    /**
+     * Return the bits in the given range as a base-16 string
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    getBitsBase16(start, end) {
+        const length = end - start;
+        if (length % 4 !== 0) {
+            throw new Error('Length of bits to retrieve must be divisible by four');
+        }
+        return this.getBits(start, end)
+            .toString(16)
+            .padStart(length / 4, '0');
+    }
+    /**
+     * Return the bits that are set past the subnet mask length
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    getBitsPastSubnet() {
+        return this.getBitsBase2(this.subnetMask, constants6.BITS);
+    }
+    /**
+     * Return the reversed ip6.arpa form of the address
+     * @memberof Address6
+     * @param {Object} options
+     * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
+     * @instance
+     * @returns {String}
+     */
+    reverseForm(options) {
+        if (!options) {
+            options = {};
+        }
+        const characters = Math.floor(this.subnetMask / 4);
+        const reversed = this.canonicalForm()
+            .replace(/:/g, '')
+            .split('')
+            .slice(0, characters)
+            .reverse()
+            .join('.');
+        if (characters > 0) {
+            if (options.omitSuffix) {
+                return reversed;
+            }
+            return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed);
+        }
+        if (options.omitSuffix) {
+            return '';
+        }
+        return 'ip6.arpa.';
+    }
+    /**
+     * Return the correct form of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    correctForm() {
+        let i;
+        let groups = [];
+        let zeroCounter = 0;
+        const zeroes = [];
+        for (i = 0; i < this.parsedAddress.length; i++) {
+            const value = parseInt(this.parsedAddress[i], 16);
+            if (value === 0) {
+                zeroCounter++;
+            }
+            if (value !== 0 && zeroCounter > 0) {
+                if (zeroCounter > 1) {
+                    zeroes.push([i - zeroCounter, i - 1]);
+                }
+                zeroCounter = 0;
+            }
+        }
+        // Do we end with a string of zeroes?
+        if (zeroCounter > 1) {
+            zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
+        }
+        const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
+        if (zeroes.length > 0) {
+            const index = zeroLengths.indexOf(Math.max(...zeroLengths));
+            groups = compact(this.parsedAddress, zeroes[index]);
+        }
+        else {
+            groups = this.parsedAddress;
+        }
+        for (i = 0; i < groups.length; i++) {
+            if (groups[i] !== 'compact') {
+                groups[i] = parseInt(groups[i], 16).toString(16);
+            }
+        }
+        let correct = groups.join(':');
+        correct = correct.replace(/^compact$/, '::');
+        correct = correct.replace(/^compact|compact$/, ':');
+        correct = correct.replace(/compact/, '');
+        return correct;
+    }
+    /**
+     * Return a zero-padded base-2 string representation of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     * @example
+     * var address = new Address6('2001:4860:4001:803::1011');
+     * address.binaryZeroPad();
+     * // '0010000000000001010010000110000001000000000000010000100000000011
+     * //  0000000000000000000000000000000000000000000000000001000000010001'
+     */
+    binaryZeroPad() {
+        return this.bigInteger().toString(2).padStart(constants6.BITS, '0');
+    }
+    // TODO: Improve the semantics of this helper function
+    parse4in6(address) {
+        const groups = address.split(':');
+        const lastGroup = groups.slice(-1)[0];
+        const address4 = lastGroup.match(constants4.RE_ADDRESS);
+        if (address4) {
+            this.parsedAddress4 = address4[0];
+            this.address4 = new ipv4_1.Address4(this.parsedAddress4);
+            for (let i = 0; i < this.address4.groups; i++) {
+                if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
+                    throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.')));
+                }
+            }
+            this.v4 = true;
+            groups[groups.length - 1] = this.address4.toGroup6();
+            address = groups.join(':');
+        }
+        return address;
+    }
+    // TODO: Make private?
+    parse(address) {
+        address = this.parse4in6(address);
+        const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
+        if (badCharacters) {
+            throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '$1'));
+        }
+        const badAddress = address.match(constants6.RE_BAD_ADDRESS);
+        if (badAddress) {
+            throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '$1'));
+        }
+        let groups = [];
+        const halves = address.split('::');
+        if (halves.length === 2) {
+            let first = halves[0].split(':');
+            let last = halves[1].split(':');
+            if (first.length === 1 && first[0] === '') {
+                first = [];
+            }
+            if (last.length === 1 && last[0] === '') {
+                last = [];
+            }
+            const remaining = this.groups - (first.length + last.length);
+            if (!remaining) {
+                throw new address_error_1.AddressError('Error parsing groups');
+            }
+            this.elidedGroups = remaining;
+            this.elisionBegin = first.length;
+            this.elisionEnd = first.length + this.elidedGroups;
+            groups = groups.concat(first);
+            for (let i = 0; i < remaining; i++) {
+                groups.push('0');
+            }
+            groups = groups.concat(last);
+        }
+        else if (halves.length === 1) {
+            groups = address.split(':');
+            this.elidedGroups = 0;
+        }
+        else {
+            throw new address_error_1.AddressError('Too many :: groups found');
+        }
+        groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16)));
+        if (groups.length !== this.groups) {
+            throw new address_error_1.AddressError('Incorrect number of groups found');
+        }
+        return groups;
+    }
+    /**
+     * Return the canonical form of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    canonicalForm() {
+        return this.parsedAddress.map(paddedHex).join(':');
+    }
+    /**
+     * Return the decimal form of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    decimal() {
+        return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':');
+    }
+    /**
+     * Return the address as a BigInteger
+     * @memberof Address6
+     * @instance
+     * @returns {BigInteger}
+     */
+    bigInteger() {
+        return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16);
+    }
+    /**
+     * Return the last two groups of this address as an IPv4 address string
+     * @memberof Address6
+     * @instance
+     * @returns {Address4}
+     * @example
+     * var address = new Address6('2001:4860:4001::1825:bf11');
+     * address.to4().correctForm(); // '24.37.191.17'
+     */
+    to4() {
+        const binary = this.binaryZeroPad().split('');
+        return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16));
+    }
+    /**
+     * Return the v4-in-v6 form of the address
+     * @memberof Address6
+     * @instance
+     * @returns {String}
+     */
+    to4in6() {
+        const address4 = this.to4();
+        const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6);
+        const correct = address6.correctForm();
+        let infix = '';
+        if (!/:$/.test(correct)) {
+            infix = ':';
+        }
+        return correct + infix + address4.address;
+    }
+    /**
+     * Return an object containing the Teredo properties of the address
+     * @memberof Address6
+     * @instance
+     * @returns {Object}
+     */
+    inspectTeredo() {
+        /*
+        - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32).
+        - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that
+          is used.
+        - Bits 64 to 79 can be used to define some flags. Currently only the
+          higher order bit is used; it is set to 1 if the Teredo client is
+          located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista
+          and Windows Server 2008 implementations, more bits are used. In those
+          implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA",
+          where "C" remains the "Cone" flag. The "R" bit is reserved for future
+          use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit
+          is Individual/Group flag (set to 0). The A bits are set to a 12-bit
+          randomly generated number chosen by the Teredo client to introduce
+          additional protection for the Teredo node against IPv6-based scanning
+          attacks.
+        - Bits 80 to 95 contains the obfuscated UDP port number. This is the
+          port number that is mapped by the NAT to the Teredo client with all
+          bits inverted.
+        - Bits 96 to 127 contains the obfuscated IPv4 address. This is the
+          public IPv4 address of the NAT with all bits inverted.
+        */
+        const prefix = this.getBitsBase16(0, 32);
+        const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString();
+        const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
+        const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16));
+        const flags = this.getBits(64, 80);
+        const flagsBase2 = this.getBitsBase2(64, 80);
+        const coneNat = flags.testBit(15);
+        const reserved = flags.testBit(14);
+        const groupIndividual = flags.testBit(8);
+        const universalLocal = flags.testBit(9);
+        const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10);
+        return {
+            prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)),
+            server4: server4.address,
+            client4: client4.address,
+            flags: flagsBase2,
+            coneNat,
+            microsoft: {
+                reserved,
+                universalLocal,
+                groupIndividual,
+                nonce,
+            },
+            udpPort,
+        };
+    }
+    /**
+     * Return an object containing the 6to4 properties of the address
+     * @memberof Address6
+     * @instance
+     * @returns {Object}
+     */
+    inspect6to4() {
+        /*
+        - Bits 0 to 15 are set to the 6to4 prefix (2002::/16).
+        - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used.
+        */
+        const prefix = this.getBitsBase16(0, 16);
+        const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
+        return {
+            prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)),
+            gateway: gateway.address,
+        };
+    }
+    /**
+     * Return a v6 6to4 address from a v6 v4inv6 address
+     * @memberof Address6
+     * @instance
+     * @returns {Address6}
+     */
+    to6to4() {
+        if (!this.is4()) {
+            return null;
+        }
+        const addr6to4 = [
+            '2002',
+            this.getBitsBase16(96, 112),
+            this.getBitsBase16(112, 128),
+            '',
+            '/16',
+        ].join(':');
+        return new Address6(addr6to4);
+    }
+    /**
+     * Return a byte array
+     * @memberof Address6
+     * @instance
+     * @returns {Array}
+     */
+    toByteArray() {
+        const byteArray = this.bigInteger().toByteArray();
+        // work around issue where `toByteArray` returns a leading 0 element
+        if (byteArray.length === 17 && byteArray[0] === 0) {
+            return byteArray.slice(1);
+        }
+        return byteArray;
+    }
+    /**
+     * Return an unsigned byte array
+     * @memberof Address6
+     * @instance
+     * @returns {Array}
+     */
+    toUnsignedByteArray() {
+        return this.toByteArray().map(unsignByte);
+    }
+    /**
+     * Convert a byte array to an Address6 object
+     * @memberof Address6
+     * @static
+     * @returns {Address6}
+     */
+    static fromByteArray(bytes) {
+        return this.fromUnsignedByteArray(bytes.map(unsignByte));
+    }
+    /**
+     * Convert an unsigned byte array to an Address6 object
+     * @memberof Address6
+     * @static
+     * @returns {Address6}
+     */
+    static fromUnsignedByteArray(bytes) {
+        const BYTE_MAX = new jsbn_1.BigInteger('256', 10);
+        let result = new jsbn_1.BigInteger('0', 10);
+        let multiplier = new jsbn_1.BigInteger('1', 10);
+        for (let i = bytes.length - 1; i >= 0; i--) {
+            result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10)));
+            multiplier = multiplier.multiply(BYTE_MAX);
+        }
+        return Address6.fromBigInteger(result);
+    }
+    /**
+     * Returns true if the address is in the canonical form, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    isCanonical() {
+        return this.addressMinusSuffix === this.canonicalForm();
+    }
+    /**
+     * Returns true if the address is a link local address, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    isLinkLocal() {
+        // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10'
+        if (this.getBitsBase2(0, 64) ===
+            '1111111010000000000000000000000000000000000000000000000000000000') {
+            return true;
+        }
+        return false;
+    }
+    /**
+     * Returns true if the address is a multicast address, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    isMulticast() {
+        return this.getType() === 'Multicast';
+    }
+    /**
+     * Returns true if the address is a v4-in-v6 address, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    is4() {
+        return this.v4;
+    }
+    /**
+     * Returns true if the address is a Teredo address, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    isTeredo() {
+        return this.isInSubnet(new Address6('2001::/32'));
+    }
+    /**
+     * Returns true if the address is a 6to4 address, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    is6to4() {
+        return this.isInSubnet(new Address6('2002::/16'));
+    }
+    /**
+     * Returns true if the address is a loopback address, false otherwise
+     * @memberof Address6
+     * @instance
+     * @returns {boolean}
+     */
+    isLoopback() {
+        return this.getType() === 'Loopback';
     }
-
-    this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;
-
-    return buf2.slice(0, j).toString('ucs2');
-}
-
-Utf16BEDecoder.prototype.end = function() {
-    this.overflowByte = -1;
-}
-
-
-// == UTF-16 codec =============================================================
-// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
-// Defaults to UTF-16LE, as it's prevalent and default in Node.
-// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
-// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});
-
-// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).
-
-exports.utf16 = Utf16Codec;
-function Utf16Codec(codecOptions, iconv) {
-    this.iconv = iconv;
-}
-
-Utf16Codec.prototype.encoder = Utf16Encoder;
-Utf16Codec.prototype.decoder = Utf16Decoder;
-
-
-// -- Encoding (pass-through)
-
-function Utf16Encoder(options, codec) {
-    options = options || {};
-    if (options.addBOM === undefined)
-        options.addBOM = true;
-    this.encoder = codec.iconv.getEncoder('utf-16le', options);
-}
-
-Utf16Encoder.prototype.write = function(str) {
-    return this.encoder.write(str);
-}
-
-Utf16Encoder.prototype.end = function() {
-    return this.encoder.end();
-}
-
-
-// -- Decoding
-
-function Utf16Decoder(options, codec) {
-    this.decoder = null;
-    this.initialBufs = [];
-    this.initialBufsLen = 0;
-
-    this.options = options || {};
-    this.iconv = codec.iconv;
-}
-
-Utf16Decoder.prototype.write = function(buf) {
-    if (!this.decoder) {
-        // Codec is not chosen yet. Accumulate initial bytes.
-        this.initialBufs.push(buf);
-        this.initialBufsLen += buf.length;
-        
-        if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below)
-            return '';
-
-        // We have enough bytes -> detect endianness.
-        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
-        this.decoder = this.iconv.getDecoder(encoding, this.options);
-
-        var resStr = '';
-        for (var i = 0; i < this.initialBufs.length; i++)
-            resStr += this.decoder.write(this.initialBufs[i]);
-
-        this.initialBufs.length = this.initialBufsLen = 0;
-        return resStr;
+    // #endregion
+    // #region HTML
+    /**
+     * @returns {String} the address in link form with a default port of 80
+     */
+    href(optionalPort) {
+        if (optionalPort === undefined) {
+            optionalPort = '';
+        }
+        else {
+            optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort);
+        }
+        return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort);
     }
-
-    return this.decoder.write(buf);
-}
-
-Utf16Decoder.prototype.end = function() {
-    if (!this.decoder) {
-        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
-        this.decoder = this.iconv.getDecoder(encoding, this.options);
-
-        var resStr = '';
-        for (var i = 0; i < this.initialBufs.length; i++)
-            resStr += this.decoder.write(this.initialBufs[i]);
-
-        var trail = this.decoder.end();
-        if (trail)
-            resStr += trail;
-
-        this.initialBufs.length = this.initialBufsLen = 0;
-        return resStr;
+    /**
+     * @returns {String} a link suitable for conveying the address via a URL hash
+     */
+    link(options) {
+        if (!options) {
+            options = {};
+        }
+        if (options.className === undefined) {
+            options.className = '';
+        }
+        if (options.prefix === undefined) {
+            options.prefix = '/#address=';
+        }
+        if (options.v4 === undefined) {
+            options.v4 = false;
+        }
+        let formFunction = this.correctForm;
+        if (options.v4) {
+            formFunction = this.to4in6;
+        }
+        if (options.className) {
+            return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className);
+        }
+        return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this));
     }
-    return this.decoder.end();
-}
-
-function detectEncoding(bufs, defaultEncoding) {
-    var b = [];
-    var charsProcessed = 0;
-    var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE.
-
-    outer_loop:
-    for (var i = 0; i < bufs.length; i++) {
-        var buf = bufs[i];
-        for (var j = 0; j < buf.length; j++) {
-            b.push(buf[j]);
-            if (b.length === 2) {
-                if (charsProcessed === 0) {
-                    // Check BOM first.
-                    if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le';
-                    if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be';
-                }
-
-                if (b[0] === 0 && b[1] !== 0) asciiCharsBE++;
-                if (b[0] !== 0 && b[1] === 0) asciiCharsLE++;
-
-                b.length = 0;
-                charsProcessed++;
-
-                if (charsProcessed >= 100) {
-                    break outer_loop;
-                }
+    /**
+     * Groups an address
+     * @returns {String}
+     */
+    group() {
+        if (this.elidedGroups === 0) {
+            // The simple case
+            return helpers.simpleGroup(this.address).join(':');
+        }
+        assert(typeof this.elidedGroups === 'number');
+        assert(typeof this.elisionBegin === 'number');
+        // The elided case
+        const output = [];
+        const [left, right] = this.address.split('::');
+        if (left.length) {
+            output.push(...helpers.simpleGroup(left));
+        }
+        else {
+            output.push('');
+        }
+        const classes = ['hover-group'];
+        for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
+            classes.push((0, sprintf_js_1.sprintf)('group-%d', i));
+        }
+        output.push((0, sprintf_js_1.sprintf)('', classes.join(' ')));
+        if (right.length) {
+            output.push(...helpers.simpleGroup(right, this.elisionEnd));
+        }
+        else {
+            output.push('');
+        }
+        if (this.is4()) {
+            assert(this.address4 instanceof ipv4_1.Address4);
+            output.pop();
+            output.push(this.address4.groupForV6());
+        }
+        return output.join(':');
+    }
+    // #endregion
+    // #region Regular expressions
+    /**
+     * Generate a regular expression string that can be used to find or validate
+     * all variations of this address
+     * @memberof Address6
+     * @instance
+     * @param {boolean} substringSearch
+     * @returns {string}
+     */
+    regularExpressionString(substringSearch = false) {
+        let output = [];
+        // TODO: revisit why this is necessary
+        const address6 = new Address6(this.correctForm());
+        if (address6.elidedGroups === 0) {
+            // The simple case
+            output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
+        }
+        else if (address6.elidedGroups === constants6.GROUPS) {
+            // A completely elided address
+            output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
+        }
+        else {
+            // A partially elided address
+            const halves = address6.address.split('::');
+            if (halves[0].length) {
+                output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':')));
+            }
+            assert(typeof address6.elidedGroups === 'number');
+            output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
+            if (halves[1].length) {
+                output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':')));
             }
+            output = [output.join(':')];
+        }
+        if (!substringSearch) {
+            output = [
+                '(?=^|',
+                regular_expressions_1.ADDRESS_BOUNDARY,
+                '|[^\\w\\:])(',
+                ...output,
+                ')(?=[^\\w\\:]|',
+                regular_expressions_1.ADDRESS_BOUNDARY,
+                '|$)',
+            ];
         }
+        return output.join('');
+    }
+    /**
+     * Generate a regular expression that can be used to find or validate all
+     * variations of this address.
+     * @memberof Address6
+     * @instance
+     * @param {boolean} substringSearch
+     * @returns {RegExp}
+     */
+    regularExpression(substringSearch = false) {
+        return new RegExp(this.regularExpressionString(substringSearch), 'i');
     }
-
-    // Make decisions.
-    // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
-    // So, we count ASCII as if it was LE or BE, and decide from that.
-    if (asciiCharsBE > asciiCharsLE) return 'utf-16be';
-    if (asciiCharsBE < asciiCharsLE) return 'utf-16le';
-
-    // Couldn't decide (likely all zeros or not enough data).
-    return defaultEncoding || 'utf-16le';
 }
-
-
-
+exports.Address6 = Address6;
+//# sourceMappingURL=ipv6.js.map
 
 /***/ }),
 
-/***/ 62021:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 66437:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0;
+exports.BITS = 32;
+exports.GROUPS = 4;
+exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
+exports.RE_SUBNET_STRING = /\/\d{1,2}$/;
+//# sourceMappingURL=constants.js.map
 
-var Buffer = (__nccwpck_require__(12803).Buffer);
-
-// == UTF32-LE/BE codec. ==========================================================
-
-exports._utf32 = Utf32Codec;
-
-function Utf32Codec(codecOptions, iconv) {
-    this.iconv = iconv;
-    this.bomAware = true;
-    this.isLE = codecOptions.isLE;
-}
-
-exports.utf32le = { type: '_utf32', isLE: true };
-exports.utf32be = { type: '_utf32', isLE: false };
-
-// Aliases
-exports.ucs4le = 'utf32le';
-exports.ucs4be = 'utf32be';
-
-Utf32Codec.prototype.encoder = Utf32Encoder;
-Utf32Codec.prototype.decoder = Utf32Decoder;
-
-// -- Encoding
-
-function Utf32Encoder(options, codec) {
-    this.isLE = codec.isLE;
-    this.highSurrogate = 0;
-}
-
-Utf32Encoder.prototype.write = function(str) {
-    var src = Buffer.from(str, 'ucs2');
-    var dst = Buffer.alloc(src.length * 2);
-    var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;
-    var offset = 0;
-
-    for (var i = 0; i < src.length; i += 2) {
-        var code = src.readUInt16LE(i);
-        var isHighSurrogate = (0xD800 <= code && code < 0xDC00);
-        var isLowSurrogate = (0xDC00 <= code && code < 0xE000);
-
-        if (this.highSurrogate) {
-            if (isHighSurrogate || !isLowSurrogate) {
-                // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low
-                // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character
-                // (technically wrong, but expected by some applications, like Windows file names).
-                write32.call(dst, this.highSurrogate, offset);
-                offset += 4;
-            }
-            else {
-                // Create 32-bit value from high and low surrogates;
-                var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;
-
-                write32.call(dst, codepoint, offset);
-                offset += 4;
-                this.highSurrogate = 0;
-
-                continue;
-            }
-        }
+/***/ }),
 
-        if (isHighSurrogate)
-            this.highSurrogate = code;
-        else {
-            // Even if the current character is a low surrogate, with no previous high surrogate, we'll
-            // encode it as a semi-invalid stand-alone character for the same reasons expressed above for
-            // unpaired high surrogates.
-            write32.call(dst, code, offset);
-            offset += 4;
-            this.highSurrogate = 0;
-        }
-    }
+/***/ 75280:
+/***/ ((__unused_webpack_module, exports) => {
 
-    if (offset < dst.length)
-        dst = dst.slice(0, offset);
+"use strict";
 
-    return dst;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0;
+exports.BITS = 128;
+exports.GROUPS = 8;
+/**
+ * Represents IPv6 address scopes
+ * @memberof Address6
+ * @static
+ */
+exports.SCOPES = {
+    0: 'Reserved',
+    1: 'Interface local',
+    2: 'Link local',
+    4: 'Admin local',
+    5: 'Site local',
+    8: 'Organization local',
+    14: 'Global',
+    15: 'Reserved',
 };
-
-Utf32Encoder.prototype.end = function() {
-    // Treat any leftover high surrogate as a semi-valid independent character.
-    if (!this.highSurrogate)
-        return;
-
-    var buf = Buffer.alloc(4);
-
-    if (this.isLE)
-        buf.writeUInt32LE(this.highSurrogate, 0);
-    else
-        buf.writeUInt32BE(this.highSurrogate, 0);
-
-    this.highSurrogate = 0;
-
-    return buf;
+/**
+ * Represents IPv6 address types
+ * @memberof Address6
+ * @static
+ */
+exports.TYPES = {
+    'ff01::1/128': 'Multicast (All nodes on this interface)',
+    'ff01::2/128': 'Multicast (All routers on this interface)',
+    'ff02::1/128': 'Multicast (All nodes on this link)',
+    'ff02::2/128': 'Multicast (All routers on this link)',
+    'ff05::2/128': 'Multicast (All routers in this site)',
+    'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)',
+    'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)',
+    'ff02::9/128': 'Multicast (RIP routers)',
+    'ff02::a/128': 'Multicast (EIGRP routers)',
+    'ff02::d/128': 'Multicast (PIM routers)',
+    'ff02::16/128': 'Multicast (MLDv2 reports)',
+    'ff01::fb/128': 'Multicast (mDNSv6)',
+    'ff02::fb/128': 'Multicast (mDNSv6)',
+    'ff05::fb/128': 'Multicast (mDNSv6)',
+    'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)',
+    'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)',
+    'ff02::1:3/128': 'Multicast (All DHCP servers on this link)',
+    'ff05::1:3/128': 'Multicast (All DHCP servers in this site)',
+    '::/128': 'Unspecified',
+    '::1/128': 'Loopback',
+    'ff00::/8': 'Multicast',
+    'fe80::/10': 'Link-local unicast',
 };
+/**
+ * A regular expression that matches bad characters in an IPv6 address
+ * @memberof Address6
+ * @static
+ */
+exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
+/**
+ * A regular expression that matches an incorrect IPv6 address
+ * @memberof Address6
+ * @static
+ */
+exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
+/**
+ * A regular expression that matches an IPv6 subnet
+ * @memberof Address6
+ * @static
+ */
+exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
+/**
+ * A regular expression that matches an IPv6 zone
+ * @memberof Address6
+ * @static
+ */
+exports.RE_ZONE_STRING = /%.*$/;
+exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/);
+exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
+//# sourceMappingURL=constants.js.map
 
-// -- Decoding
-
-function Utf32Decoder(options, codec) {
-    this.isLE = codec.isLE;
-    this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);
-    this.overflow = [];
-}
-
-Utf32Decoder.prototype.write = function(src) {
-    if (src.length === 0)
-        return '';
-
-    var i = 0;
-    var codepoint = 0;
-    var dst = Buffer.alloc(src.length + 4);
-    var offset = 0;
-    var isLE = this.isLE;
-    var overflow = this.overflow;
-    var badChar = this.badChar;
+/***/ }),
 
-    if (overflow.length > 0) {
-        for (; i < src.length && overflow.length < 4; i++)
-            overflow.push(src[i]);
-        
-        if (overflow.length === 4) {
-            // NOTE: codepoint is a signed int32 and can be negative.
-            // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer).
-            if (isLE) {
-                codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24);
-            } else {
-                codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24);
-            }
-            overflow.length = 0;
+/***/ 20339:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-            offset = _writeCodepoint(dst, offset, codepoint, badChar);
-        }
-    }
+"use strict";
 
-    // Main loop. Should be as optimized as possible.
-    for (; i < src.length - 3; i += 4) {
-        // NOTE: codepoint is a signed int32 and can be negative.
-        if (isLE) {
-            codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24);
-        } else {
-            codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24);
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0;
+const sprintf_js_1 = __nccwpck_require__(72701);
+/**
+ * @returns {String} the string with all zeroes contained in a 
+ */
+function spanAllZeroes(s) {
+    return s.replace(/(0+)/g, '$1');
+}
+exports.spanAllZeroes = spanAllZeroes;
+/**
+ * @returns {String} the string with each character contained in a 
+ */
+function spanAll(s, offset = 0) {
+    const letters = s.split('');
+    return letters
+        .map((n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead?
+    )
+        .join('');
+}
+exports.spanAll = spanAll;
+function spanLeadingZeroesSimple(group) {
+    return group.replace(/^(0+)/, '$1');
+}
+/**
+ * @returns {String} the string with leading zeroes contained in a 
+ */
+function spanLeadingZeroes(address) {
+    const groups = address.split(':');
+    return groups.map((g) => spanLeadingZeroesSimple(g)).join(':');
+}
+exports.spanLeadingZeroes = spanLeadingZeroes;
+/**
+ * Groups an address
+ * @returns {String} a grouped address
+ */
+function simpleGroup(addressString, offset = 0) {
+    const groups = addressString.split(':');
+    return groups.map((g, i) => {
+        if (/group-v4/.test(g)) {
+            return g;
         }
-        offset = _writeCodepoint(dst, offset, codepoint, badChar);
-    }
-
-    // Keep overflowing bytes.
-    for (; i < src.length; i++) {
-        overflow.push(src[i]);
-    }
-
-    return dst.slice(0, offset).toString('ucs2');
-};
+        return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g));
+    });
+}
+exports.simpleGroup = simpleGroup;
+//# sourceMappingURL=helpers.js.map
 
-function _writeCodepoint(dst, offset, codepoint, badChar) {
-    // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations.
-    if (codepoint < 0 || codepoint > 0x10FFFF) {
-        // Not a valid Unicode codepoint
-        codepoint = badChar;
-    } 
+/***/ }),
 
-    // Ephemeral Planes: Write high surrogate.
-    if (codepoint >= 0x10000) {
-        codepoint -= 0x10000;
+/***/ 72016:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 
-        var high = 0xD800 | (codepoint >> 10);
-        dst[offset++] = high & 0xff;
-        dst[offset++] = high >> 8;
+"use strict";
 
-        // Low surrogate is written below.
-        var codepoint = 0xDC00 | (codepoint & 0x3FF);
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    var desc = Object.getOwnPropertyDescriptor(m, k);
+    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+      desc = { enumerable: true, get: function() { return m[k]; } };
     }
-
-    // Write BMP char or low surrogate.
-    dst[offset++] = codepoint & 0xff;
-    dst[offset++] = codepoint >> 8;
-
-    return offset;
-};
-
-Utf32Decoder.prototype.end = function() {
-    this.overflow.length = 0;
+    Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+    if (k2 === undefined) k2 = k;
+    o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+    Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+    o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+    if (mod && mod.__esModule) return mod;
+    var result = {};
+    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+    __setModuleDefault(result, mod);
+    return result;
 };
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0;
+const v6 = __importStar(__nccwpck_require__(75280));
+const sprintf_js_1 = __nccwpck_require__(72701);
+function groupPossibilities(possibilities) {
+    return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|'));
+}
+exports.groupPossibilities = groupPossibilities;
+function padGroup(group) {
+    if (group.length < 4) {
+        return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group);
+    }
+    return group;
+}
+exports.padGroup = padGroup;
+exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]';
+function simpleRegularExpression(groups) {
+    const zeroIndexes = [];
+    groups.forEach((group, i) => {
+        const groupInteger = parseInt(group, 16);
+        if (groupInteger === 0) {
+            zeroIndexes.push(i);
+        }
+    });
+    // You can technically elide a single 0, this creates the regular expressions
+    // to match that eventuality
+    const possibilities = zeroIndexes.map((zeroIndex) => groups
+        .map((group, i) => {
+        if (i === zeroIndex) {
+            const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : '';
+            return groupPossibilities([padGroup(group), elision]);
+        }
+        return padGroup(group);
+    })
+        .join(':'));
+    // The simplest case
+    possibilities.push(groups.map(padGroup).join(':'));
+    return groupPossibilities(possibilities);
+}
+exports.simpleRegularExpression = simpleRegularExpression;
+function possibleElisions(elidedGroups, moreLeft, moreRight) {
+    const left = moreLeft ? '' : ':';
+    const right = moreRight ? '' : ':';
+    const possibilities = [];
+    // 1. elision of everything (::)
+    if (!moreLeft && !moreRight) {
+        possibilities.push('::');
+    }
+    // 2. complete elision of the middle
+    if (moreLeft && moreRight) {
+        possibilities.push('');
+    }
+    if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) {
+        // 3. complete elision of one side
+        possibilities.push(':');
+    }
+    // 4. elision from the left side
+    possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1));
+    // 5. elision from the right side
+    possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right));
+    // 6. no elision
+    possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1));
+    // 7. elision (including sloppy elision) from the middle
+    for (let groups = 1; groups < elidedGroups - 1; groups++) {
+        for (let position = 1; position < elidedGroups - groups; position++) {
+            possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1));
+        }
+    }
+    return groupPossibilities(possibilities);
+}
+exports.possibleElisions = possibleElisions;
+//# sourceMappingURL=regular-expressions.js.map
 
-// == UTF-32 Auto codec =============================================================
-// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.
-// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32
-// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});
-
-// Encoder prepends BOM (which can be overridden with (addBOM: false}).
-
-exports.utf32 = Utf32AutoCodec;
-exports.ucs4 = 'utf32';
+/***/ }),
 
-function Utf32AutoCodec(options, iconv) {
-    this.iconv = iconv;
-}
+/***/ 72701:
+/***/ ((__unused_webpack_module, exports) => {
 
-Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder;
-Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder;
+/* global window, exports, define */
 
-// -- Encoding
+!function() {
+    'use strict'
 
-function Utf32AutoEncoder(options, codec) {
-    options = options || {};
+    var re = {
+        not_string: /[^s]/,
+        not_bool: /[^t]/,
+        not_type: /[^T]/,
+        not_primitive: /[^v]/,
+        number: /[diefg]/,
+        numeric_arg: /[bcdiefguxX]/,
+        json: /[j]/,
+        not_json: /[^j]/,
+        text: /^[^\x25]+/,
+        modulo: /^\x25{2}/,
+        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
+        key: /^([a-z_][a-z_\d]*)/i,
+        key_access: /^\.([a-z_][a-z_\d]*)/i,
+        index_access: /^\[(\d+)\]/,
+        sign: /^[+-]/
+    }
 
-    if (options.addBOM === undefined)
-        options.addBOM = true;
+    function sprintf(key) {
+        // `arguments` is not an array, but should be fine for this call
+        return sprintf_format(sprintf_parse(key), arguments)
+    }
 
-    this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);
-}
+    function vsprintf(fmt, argv) {
+        return sprintf.apply(null, [fmt].concat(argv || []))
+    }
 
-Utf32AutoEncoder.prototype.write = function(str) {
-    return this.encoder.write(str);
-};
+    function sprintf_format(parse_tree, argv) {
+        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
+        for (i = 0; i < tree_length; i++) {
+            if (typeof parse_tree[i] === 'string') {
+                output += parse_tree[i]
+            }
+            else if (typeof parse_tree[i] === 'object') {
+                ph = parse_tree[i] // convenience purposes only
+                if (ph.keys) { // keyword argument
+                    arg = argv[cursor]
+                    for (k = 0; k < ph.keys.length; k++) {
+                        if (arg == undefined) {
+                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
+                        }
+                        arg = arg[ph.keys[k]]
+                    }
+                }
+                else if (ph.param_no) { // positional argument (explicit)
+                    arg = argv[ph.param_no]
+                }
+                else { // positional argument (implicit)
+                    arg = argv[cursor++]
+                }
 
-Utf32AutoEncoder.prototype.end = function() {
-    return this.encoder.end();
-};
+                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
+                    arg = arg()
+                }
 
-// -- Decoding
+                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
+                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
+                }
 
-function Utf32AutoDecoder(options, codec) {
-    this.decoder = null;
-    this.initialBufs = [];
-    this.initialBufsLen = 0;
-    this.options = options || {};
-    this.iconv = codec.iconv;
-}
+                if (re.number.test(ph.type)) {
+                    is_positive = arg >= 0
+                }
 
-Utf32AutoDecoder.prototype.write = function(buf) {
-    if (!this.decoder) { 
-        // Codec is not chosen yet. Accumulate initial bytes.
-        this.initialBufs.push(buf);
-        this.initialBufsLen += buf.length;
+                switch (ph.type) {
+                    case 'b':
+                        arg = parseInt(arg, 10).toString(2)
+                        break
+                    case 'c':
+                        arg = String.fromCharCode(parseInt(arg, 10))
+                        break
+                    case 'd':
+                    case 'i':
+                        arg = parseInt(arg, 10)
+                        break
+                    case 'j':
+                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
+                        break
+                    case 'e':
+                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
+                        break
+                    case 'f':
+                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
+                        break
+                    case 'g':
+                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
+                        break
+                    case 'o':
+                        arg = (parseInt(arg, 10) >>> 0).toString(8)
+                        break
+                    case 's':
+                        arg = String(arg)
+                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
+                        break
+                    case 't':
+                        arg = String(!!arg)
+                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
+                        break
+                    case 'T':
+                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
+                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
+                        break
+                    case 'u':
+                        arg = parseInt(arg, 10) >>> 0
+                        break
+                    case 'v':
+                        arg = arg.valueOf()
+                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
+                        break
+                    case 'x':
+                        arg = (parseInt(arg, 10) >>> 0).toString(16)
+                        break
+                    case 'X':
+                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
+                        break
+                }
+                if (re.json.test(ph.type)) {
+                    output += arg
+                }
+                else {
+                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
+                        sign = is_positive ? '+' : '-'
+                        arg = arg.toString().replace(re.sign, '')
+                    }
+                    else {
+                        sign = ''
+                    }
+                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
+                    pad_length = ph.width - (sign + arg).length
+                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
+                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
+                }
+            }
+        }
+        return output
+    }
 
-        if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below)
-            return '';
+    var sprintf_cache = Object.create(null)
 
-        // We have enough bytes -> detect endianness.
-        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
-        this.decoder = this.iconv.getDecoder(encoding, this.options);
+    function sprintf_parse(fmt) {
+        if (sprintf_cache[fmt]) {
+            return sprintf_cache[fmt]
+        }
 
-        var resStr = '';
-        for (var i = 0; i < this.initialBufs.length; i++)
-            resStr += this.decoder.write(this.initialBufs[i]);
+        var _fmt = fmt, match, parse_tree = [], arg_names = 0
+        while (_fmt) {
+            if ((match = re.text.exec(_fmt)) !== null) {
+                parse_tree.push(match[0])
+            }
+            else if ((match = re.modulo.exec(_fmt)) !== null) {
+                parse_tree.push('%')
+            }
+            else if ((match = re.placeholder.exec(_fmt)) !== null) {
+                if (match[2]) {
+                    arg_names |= 1
+                    var field_list = [], replacement_field = match[2], field_match = []
+                    if ((field_match = re.key.exec(replacement_field)) !== null) {
+                        field_list.push(field_match[1])
+                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
+                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
+                                field_list.push(field_match[1])
+                            }
+                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
+                                field_list.push(field_match[1])
+                            }
+                            else {
+                                throw new SyntaxError('[sprintf] failed to parse named argument key')
+                            }
+                        }
+                    }
+                    else {
+                        throw new SyntaxError('[sprintf] failed to parse named argument key')
+                    }
+                    match[2] = field_list
+                }
+                else {
+                    arg_names |= 2
+                }
+                if (arg_names === 3) {
+                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
+                }
 
-        this.initialBufs.length = this.initialBufsLen = 0;
-        return resStr;
+                parse_tree.push(
+                    {
+                        placeholder: match[0],
+                        param_no:    match[1],
+                        keys:        match[2],
+                        sign:        match[3],
+                        pad_char:    match[4],
+                        align:       match[5],
+                        width:       match[6],
+                        precision:   match[7],
+                        type:        match[8]
+                    }
+                )
+            }
+            else {
+                throw new SyntaxError('[sprintf] unexpected placeholder')
+            }
+            _fmt = _fmt.substring(match[0].length)
+        }
+        return sprintf_cache[fmt] = parse_tree
     }
 
-    return this.decoder.write(buf);
-};
+    /**
+     * export to either browser or node.js
+     */
+    /* eslint-disable quote-props */
+    if (true) {
+        exports.sprintf = sprintf
+        exports.vsprintf = vsprintf
+    }
+    if (typeof window !== 'undefined') {
+        window['sprintf'] = sprintf
+        window['vsprintf'] = vsprintf
 
-Utf32AutoDecoder.prototype.end = function() {
-    if (!this.decoder) {
-        var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);
-        this.decoder = this.iconv.getDecoder(encoding, this.options);
+        if (typeof define === 'function' && define['amd']) {
+            define(function() {
+                return {
+                    'sprintf': sprintf,
+                    'vsprintf': vsprintf
+                }
+            })
+        }
+    }
+    /* eslint-enable quote-props */
+}(); // eslint-disable-line
 
-        var resStr = '';
-        for (var i = 0; i < this.initialBufs.length; i++)
-            resStr += this.decoder.write(this.initialBufs[i]);
 
-        var trail = this.decoder.end();
-        if (trail)
-            resStr += trail;
+/***/ }),
 
-        this.initialBufs.length = this.initialBufsLen = 0;
-        return resStr;
-    }
+/***/ 21608:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-    return this.decoder.end();
-};
+"use strict";
 
-function detectEncoding(bufs, defaultEncoding) {
-    var b = [];
-    var charsProcessed = 0;
-    var invalidLE = 0, invalidBE = 0;   // Number of invalid chars when decoded as LE or BE.
-    var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.experimental_jwksCache = exports.jwksCache = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0;
+var decrypt_js_1 = __nccwpck_require__(14298);
+Object.defineProperty(exports, "compactDecrypt", ({ enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } }));
+var decrypt_js_2 = __nccwpck_require__(59344);
+Object.defineProperty(exports, "flattenedDecrypt", ({ enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } }));
+var decrypt_js_3 = __nccwpck_require__(49783);
+Object.defineProperty(exports, "generalDecrypt", ({ enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } }));
+var encrypt_js_1 = __nccwpck_require__(71907);
+Object.defineProperty(exports, "GeneralEncrypt", ({ enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } }));
+var verify_js_1 = __nccwpck_require__(94212);
+Object.defineProperty(exports, "compactVerify", ({ enumerable: true, get: function () { return verify_js_1.compactVerify; } }));
+var verify_js_2 = __nccwpck_require__(56358);
+Object.defineProperty(exports, "flattenedVerify", ({ enumerable: true, get: function () { return verify_js_2.flattenedVerify; } }));
+var verify_js_3 = __nccwpck_require__(88323);
+Object.defineProperty(exports, "generalVerify", ({ enumerable: true, get: function () { return verify_js_3.generalVerify; } }));
+var verify_js_4 = __nccwpck_require__(35297);
+Object.defineProperty(exports, "jwtVerify", ({ enumerable: true, get: function () { return verify_js_4.jwtVerify; } }));
+var decrypt_js_4 = __nccwpck_require__(95339);
+Object.defineProperty(exports, "jwtDecrypt", ({ enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } }));
+var encrypt_js_2 = __nccwpck_require__(4434);
+Object.defineProperty(exports, "CompactEncrypt", ({ enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } }));
+var encrypt_js_3 = __nccwpck_require__(62372);
+Object.defineProperty(exports, "FlattenedEncrypt", ({ enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } }));
+var sign_js_1 = __nccwpck_require__(21760);
+Object.defineProperty(exports, "CompactSign", ({ enumerable: true, get: function () { return sign_js_1.CompactSign; } }));
+var sign_js_2 = __nccwpck_require__(86170);
+Object.defineProperty(exports, "FlattenedSign", ({ enumerable: true, get: function () { return sign_js_2.FlattenedSign; } }));
+var sign_js_3 = __nccwpck_require__(50443);
+Object.defineProperty(exports, "GeneralSign", ({ enumerable: true, get: function () { return sign_js_3.GeneralSign; } }));
+var sign_js_4 = __nccwpck_require__(22713);
+Object.defineProperty(exports, "SignJWT", ({ enumerable: true, get: function () { return sign_js_4.SignJWT; } }));
+var encrypt_js_4 = __nccwpck_require__(38375);
+Object.defineProperty(exports, "EncryptJWT", ({ enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } }));
+var thumbprint_js_1 = __nccwpck_require__(45396);
+Object.defineProperty(exports, "calculateJwkThumbprint", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } }));
+Object.defineProperty(exports, "calculateJwkThumbprintUri", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } }));
+var embedded_js_1 = __nccwpck_require__(88541);
+Object.defineProperty(exports, "EmbeddedJWK", ({ enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } }));
+var local_js_1 = __nccwpck_require__(25275);
+Object.defineProperty(exports, "createLocalJWKSet", ({ enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } }));
+var remote_js_1 = __nccwpck_require__(69260);
+Object.defineProperty(exports, "createRemoteJWKSet", ({ enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } }));
+Object.defineProperty(exports, "jwksCache", ({ enumerable: true, get: function () { return remote_js_1.jwksCache; } }));
+Object.defineProperty(exports, "experimental_jwksCache", ({ enumerable: true, get: function () { return remote_js_1.experimental_jwksCache; } }));
+var unsecured_js_1 = __nccwpck_require__(40560);
+Object.defineProperty(exports, "UnsecuredJWT", ({ enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } }));
+var export_js_1 = __nccwpck_require__(48108);
+Object.defineProperty(exports, "exportPKCS8", ({ enumerable: true, get: function () { return export_js_1.exportPKCS8; } }));
+Object.defineProperty(exports, "exportSPKI", ({ enumerable: true, get: function () { return export_js_1.exportSPKI; } }));
+Object.defineProperty(exports, "exportJWK", ({ enumerable: true, get: function () { return export_js_1.exportJWK; } }));
+var import_js_1 = __nccwpck_require__(45647);
+Object.defineProperty(exports, "importSPKI", ({ enumerable: true, get: function () { return import_js_1.importSPKI; } }));
+Object.defineProperty(exports, "importPKCS8", ({ enumerable: true, get: function () { return import_js_1.importPKCS8; } }));
+Object.defineProperty(exports, "importX509", ({ enumerable: true, get: function () { return import_js_1.importX509; } }));
+Object.defineProperty(exports, "importJWK", ({ enumerable: true, get: function () { return import_js_1.importJWK; } }));
+var decode_protected_header_js_1 = __nccwpck_require__(14704);
+Object.defineProperty(exports, "decodeProtectedHeader", ({ enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } }));
+var decode_jwt_js_1 = __nccwpck_require__(60002);
+Object.defineProperty(exports, "decodeJwt", ({ enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } }));
+exports.errors = __nccwpck_require__(15974);
+var generate_key_pair_js_1 = __nccwpck_require__(87820);
+Object.defineProperty(exports, "generateKeyPair", ({ enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } }));
+var generate_secret_js_1 = __nccwpck_require__(37152);
+Object.defineProperty(exports, "generateSecret", ({ enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } }));
+exports.base64url = __nccwpck_require__(78305);
+var runtime_js_1 = __nccwpck_require__(25021);
+Object.defineProperty(exports, "cryptoRuntime", ({ enumerable: true, get: function () { return runtime_js_1.default; } }));
 
-    outer_loop:
-    for (var i = 0; i < bufs.length; i++) {
-        var buf = bufs[i];
-        for (var j = 0; j < buf.length; j++) {
-            b.push(buf[j]);
-            if (b.length === 4) {
-                if (charsProcessed === 0) {
-                    // Check BOM first.
-                    if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) {
-                        return 'utf-32le';
-                    }
-                    if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) {
-                        return 'utf-32be';
-                    }
-                }
 
-                if (b[0] !== 0 || b[1] > 0x10) invalidBE++;
-                if (b[3] !== 0 || b[2] > 0x10) invalidLE++;
+/***/ }),
 
-                if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++;
-                if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++;
+/***/ 14298:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-                b.length = 0;
-                charsProcessed++;
+"use strict";
 
-                if (charsProcessed >= 100) {
-                    break outer_loop;
-                }
-            }
-        }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.compactDecrypt = compactDecrypt;
+const decrypt_js_1 = __nccwpck_require__(59344);
+const errors_js_1 = __nccwpck_require__(15974);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+async function compactDecrypt(jwe, key, options) {
+    if (jwe instanceof Uint8Array) {
+        jwe = buffer_utils_js_1.decoder.decode(jwe);
     }
-
-    // Make decisions.
-    if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE)  return 'utf-32be';
-    if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE)  return 'utf-32le';
-
-    // Couldn't decide (likely all zeros or not enough data).
-    return defaultEncoding || 'utf-32le';
+    if (typeof jwe !== 'string') {
+        throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array');
+    }
+    const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');
+    if (length !== 5) {
+        throw new errors_js_1.JWEInvalid('Invalid Compact JWE');
+    }
+    const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({
+        ciphertext,
+        iv: iv || undefined,
+        protected: protectedHeader,
+        tag: tag || undefined,
+        encrypted_key: encryptedKey || undefined,
+    }, key, options);
+    const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
+    if (typeof key === 'function') {
+        return { ...result, key: decrypted.key };
+    }
+    return result;
 }
 
 
 /***/ }),
 
-/***/ 28231:
+/***/ 4434:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var Buffer = (__nccwpck_require__(12803).Buffer);
-
-// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
-// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3
-
-exports.utf7 = Utf7Codec;
-exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
-function Utf7Codec(codecOptions, iconv) {
-    this.iconv = iconv;
-};
-
-Utf7Codec.prototype.encoder = Utf7Encoder;
-Utf7Codec.prototype.decoder = Utf7Decoder;
-Utf7Codec.prototype.bomAware = true;
-
-
-// -- Encoding
-
-var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
-
-function Utf7Encoder(options, codec) {
-    this.iconv = codec.iconv;
-}
-
-Utf7Encoder.prototype.write = function(str) {
-    // Naive implementation.
-    // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-".
-    return Buffer.from(str.replace(nonDirectChars, function(chunk) {
-        return "+" + (chunk === '+' ? '' : 
-            this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) 
-            + "-";
-    }.bind(this)));
-}
-
-Utf7Encoder.prototype.end = function() {
-}
-
-
-// -- Decoding
-
-function Utf7Decoder(options, codec) {
-    this.iconv = codec.iconv;
-    this.inBase64 = false;
-    this.base64Accum = '';
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.CompactEncrypt = void 0;
+const encrypt_js_1 = __nccwpck_require__(62372);
+class CompactEncrypt {
+    _flattened;
+    constructor(plaintext) {
+        this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext);
+    }
+    setContentEncryptionKey(cek) {
+        this._flattened.setContentEncryptionKey(cek);
+        return this;
+    }
+    setInitializationVector(iv) {
+        this._flattened.setInitializationVector(iv);
+        return this;
+    }
+    setProtectedHeader(protectedHeader) {
+        this._flattened.setProtectedHeader(protectedHeader);
+        return this;
+    }
+    setKeyManagementParameters(parameters) {
+        this._flattened.setKeyManagementParameters(parameters);
+        return this;
+    }
+    async encrypt(key, options) {
+        const jwe = await this._flattened.encrypt(key, options);
+        return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');
+    }
 }
+exports.CompactEncrypt = CompactEncrypt;
 
-var base64Regex = /[A-Za-z0-9\/+]/;
-var base64Chars = [];
-for (var i = 0; i < 256; i++)
-    base64Chars[i] = base64Regex.test(String.fromCharCode(i));
-
-var plusChar = '+'.charCodeAt(0), 
-    minusChar = '-'.charCodeAt(0),
-    andChar = '&'.charCodeAt(0);
-
-Utf7Decoder.prototype.write = function(buf) {
-    var res = "", lastI = 0,
-        inBase64 = this.inBase64,
-        base64Accum = this.base64Accum;
 
-    // The decoder is more involved as we must handle chunks in stream.
+/***/ }),
 
-    for (var i = 0; i < buf.length; i++) {
-        if (!inBase64) { // We're in direct mode.
-            // Write direct chars until '+'
-            if (buf[i] == plusChar) {
-                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
-                lastI = i+1;
-                inBase64 = true;
-            }
-        } else { // We decode base64.
-            if (!base64Chars[buf[i]]) { // Base64 ended.
-                if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
-                    res += "+";
-                } else {
-                    var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii");
-                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-                }
+/***/ 59344:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-                if (buf[i] != minusChar) // Minus is absorbed after base64.
-                    i--;
+"use strict";
 
-                lastI = i+1;
-                inBase64 = false;
-                base64Accum = '';
-            }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.flattenedDecrypt = flattenedDecrypt;
+const base64url_js_1 = __nccwpck_require__(12635);
+const decrypt_js_1 = __nccwpck_require__(52806);
+const errors_js_1 = __nccwpck_require__(15974);
+const is_disjoint_js_1 = __nccwpck_require__(21853);
+const is_object_js_1 = __nccwpck_require__(92242);
+const decrypt_key_management_js_1 = __nccwpck_require__(56243);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const cek_js_1 = __nccwpck_require__(87937);
+const validate_crit_js_1 = __nccwpck_require__(15595);
+const validate_algorithms_js_1 = __nccwpck_require__(19917);
+async function flattenedDecrypt(jwe, key, options) {
+    if (!(0, is_object_js_1.default)(jwe)) {
+        throw new errors_js_1.JWEInvalid('Flattened JWE must be an object');
+    }
+    if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
+        throw new errors_js_1.JWEInvalid('JOSE Header missing');
+    }
+    if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
+        throw new errors_js_1.JWEInvalid('JWE Initialization Vector incorrect type');
+    }
+    if (typeof jwe.ciphertext !== 'string') {
+        throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type');
+    }
+    if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
+        throw new errors_js_1.JWEInvalid('JWE Authentication Tag incorrect type');
+    }
+    if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
+        throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type');
+    }
+    if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
+        throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type');
+    }
+    if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
+        throw new errors_js_1.JWEInvalid('JWE AAD incorrect type');
+    }
+    if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) {
+        throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type');
+    }
+    if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) {
+        throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
+    }
+    let parsedProt;
+    if (jwe.protected) {
+        try {
+            const protectedHeader = (0, base64url_js_1.decode)(jwe.protected);
+            parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
+        }
+        catch {
+            throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid');
         }
     }
-
-    if (!inBase64) {
-        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
-    } else {
-        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii");
-
-        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
-        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
-        b64str = b64str.slice(0, canBeDecoded);
-
-        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
+    if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) {
+        throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
     }
-
-    this.inBase64 = inBase64;
-    this.base64Accum = base64Accum;
-
-    return res;
-}
-
-Utf7Decoder.prototype.end = function() {
-    var res = "";
-    if (this.inBase64 && this.base64Accum.length > 0)
-        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
-
-    this.inBase64 = false;
-    this.base64Accum = '';
-    return res;
+    const joseHeader = {
+        ...parsedProt,
+        ...jwe.header,
+        ...jwe.unprotected,
+    };
+    (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
+    if (joseHeader.zip !== undefined) {
+        throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+    }
+    const { alg, enc } = joseHeader;
+    if (typeof alg !== 'string' || !alg) {
+        throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
+    }
+    if (typeof enc !== 'string' || !enc) {
+        throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
+    }
+    const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms);
+    const contentEncryptionAlgorithms = options &&
+        (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
+    if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
+        (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
+        throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+    }
+    if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
+        throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
+    }
+    let encryptedKey;
+    if (jwe.encrypted_key !== undefined) {
+        try {
+            encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key);
+        }
+        catch {
+            throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key');
+        }
+    }
+    let resolvedKey = false;
+    if (typeof key === 'function') {
+        key = await key(parsedProt, jwe);
+        resolvedKey = true;
+    }
+    let cek;
+    try {
+        cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options);
+    }
+    catch (err) {
+        if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) {
+            throw err;
+        }
+        cek = (0, cek_js_1.default)(enc);
+    }
+    let iv;
+    let tag;
+    if (jwe.iv !== undefined) {
+        try {
+            iv = (0, base64url_js_1.decode)(jwe.iv);
+        }
+        catch {
+            throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv');
+        }
+    }
+    if (jwe.tag !== undefined) {
+        try {
+            tag = (0, base64url_js_1.decode)(jwe.tag);
+        }
+        catch {
+            throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag');
+        }
+    }
+    const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? '');
+    let additionalData;
+    if (jwe.aad !== undefined) {
+        additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad));
+    }
+    else {
+        additionalData = protectedHeader;
+    }
+    let ciphertext;
+    try {
+        ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext);
+    }
+    catch {
+        throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext');
+    }
+    const plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData);
+    const result = { plaintext };
+    if (jwe.protected !== undefined) {
+        result.protectedHeader = parsedProt;
+    }
+    if (jwe.aad !== undefined) {
+        try {
+            result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad);
+        }
+        catch {
+            throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad');
+        }
+    }
+    if (jwe.unprotected !== undefined) {
+        result.sharedUnprotectedHeader = jwe.unprotected;
+    }
+    if (jwe.header !== undefined) {
+        result.unprotectedHeader = jwe.header;
+    }
+    if (resolvedKey) {
+        return { ...result, key };
+    }
+    return result;
 }
 
 
-// UTF-7-IMAP codec.
-// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
-// Differences:
-//  * Base64 part is started by "&" instead of "+"
-//  * Direct characters are 0x20-0x7E, except "&" (0x26)
-//  * In Base64, "," is used instead of "/"
-//  * Base64 must not be used to represent direct characters.
-//  * No implicit shift back from Base64 (should always end with '-')
-//  * String must end in non-shifted position.
-//  * "-&" while in base64 is not allowed.
-
-
-exports.utf7imap = Utf7IMAPCodec;
-function Utf7IMAPCodec(codecOptions, iconv) {
-    this.iconv = iconv;
-};
-
-Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
-Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
-Utf7IMAPCodec.prototype.bomAware = true;
-
-
-// -- Encoding
+/***/ }),
 
-function Utf7IMAPEncoder(options, codec) {
-    this.iconv = codec.iconv;
-    this.inBase64 = false;
-    this.base64Accum = Buffer.alloc(6);
-    this.base64AccumIdx = 0;
-}
+/***/ 62372:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-Utf7IMAPEncoder.prototype.write = function(str) {
-    var inBase64 = this.inBase64,
-        base64Accum = this.base64Accum,
-        base64AccumIdx = this.base64AccumIdx,
-        buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;
+"use strict";
 
-    for (var i = 0; i < str.length; i++) {
-        var uChar = str.charCodeAt(i);
-        if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
-            if (inBase64) {
-                if (base64AccumIdx > 0) {
-                    bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
-                    base64AccumIdx = 0;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.FlattenedEncrypt = void 0;
+const base64url_js_1 = __nccwpck_require__(12635);
+const private_symbols_js_1 = __nccwpck_require__(46433);
+const encrypt_js_1 = __nccwpck_require__(36286);
+const encrypt_key_management_js_1 = __nccwpck_require__(96539);
+const errors_js_1 = __nccwpck_require__(15974);
+const is_disjoint_js_1 = __nccwpck_require__(21853);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const validate_crit_js_1 = __nccwpck_require__(15595);
+class FlattenedEncrypt {
+    _plaintext;
+    _protectedHeader;
+    _sharedUnprotectedHeader;
+    _unprotectedHeader;
+    _aad;
+    _cek;
+    _iv;
+    _keyManagementParameters;
+    constructor(plaintext) {
+        if (!(plaintext instanceof Uint8Array)) {
+            throw new TypeError('plaintext must be an instance of Uint8Array');
+        }
+        this._plaintext = plaintext;
+    }
+    setKeyManagementParameters(parameters) {
+        if (this._keyManagementParameters) {
+            throw new TypeError('setKeyManagementParameters can only be called once');
+        }
+        this._keyManagementParameters = parameters;
+        return this;
+    }
+    setProtectedHeader(protectedHeader) {
+        if (this._protectedHeader) {
+            throw new TypeError('setProtectedHeader can only be called once');
+        }
+        this._protectedHeader = protectedHeader;
+        return this;
+    }
+    setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+        if (this._sharedUnprotectedHeader) {
+            throw new TypeError('setSharedUnprotectedHeader can only be called once');
+        }
+        this._sharedUnprotectedHeader = sharedUnprotectedHeader;
+        return this;
+    }
+    setUnprotectedHeader(unprotectedHeader) {
+        if (this._unprotectedHeader) {
+            throw new TypeError('setUnprotectedHeader can only be called once');
+        }
+        this._unprotectedHeader = unprotectedHeader;
+        return this;
+    }
+    setAdditionalAuthenticatedData(aad) {
+        this._aad = aad;
+        return this;
+    }
+    setContentEncryptionKey(cek) {
+        if (this._cek) {
+            throw new TypeError('setContentEncryptionKey can only be called once');
+        }
+        this._cek = cek;
+        return this;
+    }
+    setInitializationVector(iv) {
+        if (this._iv) {
+            throw new TypeError('setInitializationVector can only be called once');
+        }
+        this._iv = iv;
+        return this;
+    }
+    async encrypt(key, options) {
+        if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
+            throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
+        }
+        if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
+            throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
+        }
+        const joseHeader = {
+            ...this._protectedHeader,
+            ...this._unprotectedHeader,
+            ...this._sharedUnprotectedHeader,
+        };
+        (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);
+        if (joseHeader.zip !== undefined) {
+            throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+        }
+        const { alg, enc } = joseHeader;
+        if (typeof alg !== 'string' || !alg) {
+            throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+        }
+        if (typeof enc !== 'string' || !enc) {
+            throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+        }
+        let encryptedKey;
+        if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) {
+            throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
+        }
+        let cek;
+        {
+            let parameters;
+            ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters));
+            if (parameters) {
+                if (options && private_symbols_js_1.unprotected in options) {
+                    if (!this._unprotectedHeader) {
+                        this.setUnprotectedHeader(parameters);
+                    }
+                    else {
+                        this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
+                    }
                 }
-
-                buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
-                inBase64 = false;
-            }
-
-            if (!inBase64) {
-                buf[bufIdx++] = uChar; // Write direct character
-
-                if (uChar === andChar)  // Ampersand -> '&-'
-                    buf[bufIdx++] = minusChar;
-            }
-
-        } else { // Non-direct character
-            if (!inBase64) {
-                buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
-                inBase64 = true;
-            }
-            if (inBase64) {
-                base64Accum[base64AccumIdx++] = uChar >> 8;
-                base64Accum[base64AccumIdx++] = uChar & 0xFF;
-
-                if (base64AccumIdx == base64Accum.length) {
-                    bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
-                    base64AccumIdx = 0;
+                else if (!this._protectedHeader) {
+                    this.setProtectedHeader(parameters);
+                }
+                else {
+                    this._protectedHeader = { ...this._protectedHeader, ...parameters };
                 }
             }
         }
-    }
-
-    this.inBase64 = inBase64;
-    this.base64AccumIdx = base64AccumIdx;
-
-    return buf.slice(0, bufIdx);
-}
-
-Utf7IMAPEncoder.prototype.end = function() {
-    var buf = Buffer.alloc(10), bufIdx = 0;
-    if (this.inBase64) {
-        if (this.base64AccumIdx > 0) {
-            bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
-            this.base64AccumIdx = 0;
+        let additionalData;
+        let protectedHeader;
+        let aadMember;
+        if (this._protectedHeader) {
+            protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
         }
-
-        buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
-        this.inBase64 = false;
-    }
-
-    return buf.slice(0, bufIdx);
-}
-
-
-// -- Decoding
-
-function Utf7IMAPDecoder(options, codec) {
-    this.iconv = codec.iconv;
-    this.inBase64 = false;
-    this.base64Accum = '';
-}
-
-var base64IMAPChars = base64Chars.slice();
-base64IMAPChars[','.charCodeAt(0)] = true;
-
-Utf7IMAPDecoder.prototype.write = function(buf) {
-    var res = "", lastI = 0,
-        inBase64 = this.inBase64,
-        base64Accum = this.base64Accum;
-
-    // The decoder is more involved as we must handle chunks in stream.
-    // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).
-
-    for (var i = 0; i < buf.length; i++) {
-        if (!inBase64) { // We're in direct mode.
-            // Write direct chars until '&'
-            if (buf[i] == andChar) {
-                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
-                lastI = i+1;
-                inBase64 = true;
-            }
-        } else { // We decode base64.
-            if (!base64IMAPChars[buf[i]]) { // Base64 ended.
-                if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
-                    res += "&";
-                } else {
-                    var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), "ascii").replace(/,/g, '/');
-                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-                }
-
-                if (buf[i] != minusChar) // Minus may be absorbed after base64.
-                    i--;
-
-                lastI = i+1;
-                inBase64 = false;
-                base64Accum = '';
-            }
+        else {
+            protectedHeader = buffer_utils_js_1.encoder.encode('');
         }
+        if (this._aad) {
+            aadMember = (0, base64url_js_1.encode)(this._aad);
+            additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember));
+        }
+        else {
+            additionalData = protectedHeader;
+        }
+        const { ciphertext, tag, iv } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData);
+        const jwe = {
+            ciphertext: (0, base64url_js_1.encode)(ciphertext),
+        };
+        if (iv) {
+            jwe.iv = (0, base64url_js_1.encode)(iv);
+        }
+        if (tag) {
+            jwe.tag = (0, base64url_js_1.encode)(tag);
+        }
+        if (encryptedKey) {
+            jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
+        }
+        if (aadMember) {
+            jwe.aad = aadMember;
+        }
+        if (this._protectedHeader) {
+            jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
+        }
+        if (this._sharedUnprotectedHeader) {
+            jwe.unprotected = this._sharedUnprotectedHeader;
+        }
+        if (this._unprotectedHeader) {
+            jwe.header = this._unprotectedHeader;
+        }
+        return jwe;
     }
-
-    if (!inBase64) {
-        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
-    } else {
-        var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), "ascii").replace(/,/g, '/');
-
-        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
-        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
-        b64str = b64str.slice(0, canBeDecoded);
-
-        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-    }
-
-    this.inBase64 = inBase64;
-    this.base64Accum = base64Accum;
-
-    return res;
-}
-
-Utf7IMAPDecoder.prototype.end = function() {
-    var res = "";
-    if (this.inBase64 && this.base64Accum.length > 0)
-        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
-
-    this.inBase64 = false;
-    this.base64Accum = '';
-    return res;
 }
-
-
+exports.FlattenedEncrypt = FlattenedEncrypt;
 
 
 /***/ }),
 
-/***/ 74250:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 49783:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-
-var BOMChar = '\uFEFF';
-
-exports.PrependBOM = PrependBOMWrapper
-function PrependBOMWrapper(encoder, options) {
-    this.encoder = encoder;
-    this.addBOM = true;
-}
-
-PrependBOMWrapper.prototype.write = function(str) {
-    if (this.addBOM) {
-        str = BOMChar + str;
-        this.addBOM = false;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.generalDecrypt = generalDecrypt;
+const decrypt_js_1 = __nccwpck_require__(59344);
+const errors_js_1 = __nccwpck_require__(15974);
+const is_object_js_1 = __nccwpck_require__(92242);
+async function generalDecrypt(jwe, key, options) {
+    if (!(0, is_object_js_1.default)(jwe)) {
+        throw new errors_js_1.JWEInvalid('General JWE must be an object');
     }
-
-    return this.encoder.write(str);
-}
-
-PrependBOMWrapper.prototype.end = function() {
-    return this.encoder.end();
-}
-
-
-//------------------------------------------------------------------------------
-
-exports.StripBOM = StripBOMWrapper;
-function StripBOMWrapper(decoder, options) {
-    this.decoder = decoder;
-    this.pass = false;
-    this.options = options || {};
-}
-
-StripBOMWrapper.prototype.write = function(buf) {
-    var res = this.decoder.write(buf);
-    if (this.pass || !res)
-        return res;
-
-    if (res[0] === BOMChar) {
-        res = res.slice(1);
-        if (typeof this.options.stripBOM === 'function')
-            this.options.stripBOM();
+    if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) {
+        throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type');
     }
-
-    this.pass = true;
-    return res;
-}
-
-StripBOMWrapper.prototype.end = function() {
-    return this.decoder.end();
+    if (!jwe.recipients.length) {
+        throw new errors_js_1.JWEInvalid('JWE Recipients has no members');
+    }
+    for (const recipient of jwe.recipients) {
+        try {
+            return await (0, decrypt_js_1.flattenedDecrypt)({
+                aad: jwe.aad,
+                ciphertext: jwe.ciphertext,
+                encrypted_key: recipient.encrypted_key,
+                header: recipient.header,
+                iv: jwe.iv,
+                protected: jwe.protected,
+                tag: jwe.tag,
+                unprotected: jwe.unprotected,
+            }, key, options);
+        }
+        catch {
+        }
+    }
+    throw new errors_js_1.JWEDecryptionFailed();
 }
 
 
-
 /***/ }),
 
-/***/ 31748:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 71907:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-
-var Buffer = (__nccwpck_require__(12803).Buffer);
-
-var bomHandling = __nccwpck_require__(74250),
-    iconv = module.exports;
-
-// All codecs and aliases are kept here, keyed by encoding name/alias.
-// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
-iconv.encodings = null;
-
-// Characters emitted in case of error.
-iconv.defaultCharUnicode = '�';
-iconv.defaultCharSingleByte = '?';
-
-// Public API.
-iconv.encode = function encode(str, encoding, options) {
-    str = "" + (str || ""); // Ensure string.
-
-    var encoder = iconv.getEncoder(encoding, options);
-
-    var res = encoder.write(str);
-    var trail = encoder.end();
-    
-    return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
-}
-
-iconv.decode = function decode(buf, encoding, options) {
-    if (typeof buf === 'string') {
-        if (!iconv.skipDecodeWarning) {
-            console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
-            iconv.skipDecodeWarning = true;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GeneralEncrypt = void 0;
+const encrypt_js_1 = __nccwpck_require__(62372);
+const private_symbols_js_1 = __nccwpck_require__(46433);
+const errors_js_1 = __nccwpck_require__(15974);
+const cek_js_1 = __nccwpck_require__(87937);
+const is_disjoint_js_1 = __nccwpck_require__(21853);
+const encrypt_key_management_js_1 = __nccwpck_require__(96539);
+const base64url_js_1 = __nccwpck_require__(12635);
+const validate_crit_js_1 = __nccwpck_require__(15595);
+class IndividualRecipient {
+    parent;
+    unprotectedHeader;
+    key;
+    options;
+    constructor(enc, key, options) {
+        this.parent = enc;
+        this.key = key;
+        this.options = options;
+    }
+    setUnprotectedHeader(unprotectedHeader) {
+        if (this.unprotectedHeader) {
+            throw new TypeError('setUnprotectedHeader can only be called once');
         }
-
-        buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
+        this.unprotectedHeader = unprotectedHeader;
+        return this;
     }
-
-    var decoder = iconv.getDecoder(encoding, options);
-
-    var res = decoder.write(buf);
-    var trail = decoder.end();
-
-    return trail ? (res + trail) : res;
-}
-
-iconv.encodingExists = function encodingExists(enc) {
-    try {
-        iconv.getCodec(enc);
-        return true;
-    } catch (e) {
-        return false;
+    addRecipient(...args) {
+        return this.parent.addRecipient(...args);
+    }
+    encrypt(...args) {
+        return this.parent.encrypt(...args);
+    }
+    done() {
+        return this.parent;
     }
 }
-
-// Legacy aliases to convert functions
-iconv.toEncoding = iconv.encode;
-iconv.fromEncoding = iconv.decode;
-
-// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
-iconv._codecDataCache = {};
-iconv.getCodec = function getCodec(encoding) {
-    if (!iconv.encodings)
-        iconv.encodings = __nccwpck_require__(27585); // Lazy load all encoding definitions.
-    
-    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
-    var enc = iconv._canonicalizeEncoding(encoding);
-
-    // Traverse iconv.encodings to find actual codec.
-    var codecOptions = {};
-    while (true) {
-        var codec = iconv._codecDataCache[enc];
-        if (codec)
-            return codec;
-
-        var codecDef = iconv.encodings[enc];
-
-        switch (typeof codecDef) {
-            case "string": // Direct alias to other encoding.
-                enc = codecDef;
-                break;
-
-            case "object": // Alias with options. Can be layered.
-                for (var key in codecDef)
-                    codecOptions[key] = codecDef[key];
-
-                if (!codecOptions.encodingName)
-                    codecOptions.encodingName = enc;
-                
-                enc = codecDef.type;
-                break;
-
-            case "function": // Codec itself.
-                if (!codecOptions.encodingName)
-                    codecOptions.encodingName = enc;
-
-                // The codec function must load all tables and return object with .encoder and .decoder methods.
-                // It'll be called only once (for each different options object).
-                codec = new codecDef(codecOptions, iconv);
-
-                iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
-                return codec;
-
-            default:
-                throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
+class GeneralEncrypt {
+    _plaintext;
+    _recipients = [];
+    _protectedHeader;
+    _unprotectedHeader;
+    _aad;
+    constructor(plaintext) {
+        this._plaintext = plaintext;
+    }
+    addRecipient(key, options) {
+        const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
+        this._recipients.push(recipient);
+        return recipient;
+    }
+    setProtectedHeader(protectedHeader) {
+        if (this._protectedHeader) {
+            throw new TypeError('setProtectedHeader can only be called once');
+        }
+        this._protectedHeader = protectedHeader;
+        return this;
+    }
+    setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+        if (this._unprotectedHeader) {
+            throw new TypeError('setSharedUnprotectedHeader can only be called once');
+        }
+        this._unprotectedHeader = sharedUnprotectedHeader;
+        return this;
+    }
+    setAdditionalAuthenticatedData(aad) {
+        this._aad = aad;
+        return this;
+    }
+    async encrypt() {
+        if (!this._recipients.length) {
+            throw new errors_js_1.JWEInvalid('at least one recipient must be added');
+        }
+        if (this._recipients.length === 1) {
+            const [recipient] = this._recipients;
+            const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext)
+                .setAdditionalAuthenticatedData(this._aad)
+                .setProtectedHeader(this._protectedHeader)
+                .setSharedUnprotectedHeader(this._unprotectedHeader)
+                .setUnprotectedHeader(recipient.unprotectedHeader)
+                .encrypt(recipient.key, { ...recipient.options });
+            const jwe = {
+                ciphertext: flattened.ciphertext,
+                iv: flattened.iv,
+                recipients: [{}],
+                tag: flattened.tag,
+            };
+            if (flattened.aad)
+                jwe.aad = flattened.aad;
+            if (flattened.protected)
+                jwe.protected = flattened.protected;
+            if (flattened.unprotected)
+                jwe.unprotected = flattened.unprotected;
+            if (flattened.encrypted_key)
+                jwe.recipients[0].encrypted_key = flattened.encrypted_key;
+            if (flattened.header)
+                jwe.recipients[0].header = flattened.header;
+            return jwe;
+        }
+        let enc;
+        for (let i = 0; i < this._recipients.length; i++) {
+            const recipient = this._recipients[i];
+            if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
+                throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
+            }
+            const joseHeader = {
+                ...this._protectedHeader,
+                ...this._unprotectedHeader,
+                ...recipient.unprotectedHeader,
+            };
+            const { alg } = joseHeader;
+            if (typeof alg !== 'string' || !alg) {
+                throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+            }
+            if (alg === 'dir' || alg === 'ECDH-ES') {
+                throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
+            }
+            if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
+                throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+            }
+            if (!enc) {
+                enc = joseHeader.enc;
+            }
+            else if (enc !== joseHeader.enc) {
+                throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
+            }
+            (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
+            if (joseHeader.zip !== undefined) {
+                throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+            }
+        }
+        const cek = (0, cek_js_1.default)(enc);
+        const jwe = {
+            ciphertext: '',
+            iv: '',
+            recipients: [],
+            tag: '',
+        };
+        for (let i = 0; i < this._recipients.length; i++) {
+            const recipient = this._recipients[i];
+            const target = {};
+            jwe.recipients.push(target);
+            const joseHeader = {
+                ...this._protectedHeader,
+                ...this._unprotectedHeader,
+                ...recipient.unprotectedHeader,
+            };
+            const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;
+            if (i === 0) {
+                const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext)
+                    .setAdditionalAuthenticatedData(this._aad)
+                    .setContentEncryptionKey(cek)
+                    .setProtectedHeader(this._protectedHeader)
+                    .setSharedUnprotectedHeader(this._unprotectedHeader)
+                    .setUnprotectedHeader(recipient.unprotectedHeader)
+                    .setKeyManagementParameters({ p2c })
+                    .encrypt(recipient.key, {
+                    ...recipient.options,
+                    [private_symbols_js_1.unprotected]: true,
+                });
+                jwe.ciphertext = flattened.ciphertext;
+                jwe.iv = flattened.iv;
+                jwe.tag = flattened.tag;
+                if (flattened.aad)
+                    jwe.aad = flattened.aad;
+                if (flattened.protected)
+                    jwe.protected = flattened.protected;
+                if (flattened.unprotected)
+                    jwe.unprotected = flattened.unprotected;
+                target.encrypted_key = flattened.encrypted_key;
+                if (flattened.header)
+                    target.header = flattened.header;
+                continue;
+            }
+            const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg ||
+                this._protectedHeader?.alg ||
+                this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
+            target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
+            if (recipient.unprotectedHeader || parameters)
+                target.header = { ...recipient.unprotectedHeader, ...parameters };
         }
+        return jwe;
     }
 }
+exports.GeneralEncrypt = GeneralEncrypt;
 
-iconv._canonicalizeEncoding = function(encoding) {
-    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
-    return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
-}
-
-iconv.getEncoder = function getEncoder(encoding, options) {
-    var codec = iconv.getCodec(encoding),
-        encoder = new codec.encoder(options, codec);
-
-    if (codec.bomAware && options && options.addBOM)
-        encoder = new bomHandling.PrependBOM(encoder, options);
-
-    return encoder;
-}
-
-iconv.getDecoder = function getDecoder(encoding, options) {
-    var codec = iconv.getCodec(encoding),
-        decoder = new codec.decoder(options, codec);
-
-    if (codec.bomAware && !(options && options.stripBOM === false))
-        decoder = new bomHandling.StripBOM(decoder, options);
-
-    return decoder;
-}
 
-// Streaming API
-// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add
-// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default.
-// If you would like to enable it explicitly, please add the following code to your app:
-// > iconv.enableStreamingAPI(require('stream'));
-iconv.enableStreamingAPI = function enableStreamingAPI(stream_module) {
-    if (iconv.supportsStreams)
-        return;
+/***/ }),
 
-    // Dependency-inject stream module to create IconvLite stream classes.
-    var streams = __nccwpck_require__(42281)(stream_module);
+/***/ 88541:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-    // Not public API yet, but expose the stream classes.
-    iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream;
-    iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream;
+"use strict";
 
-    // Streaming API.
-    iconv.encodeStream = function encodeStream(encoding, options) {
-        return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.EmbeddedJWK = EmbeddedJWK;
+const import_js_1 = __nccwpck_require__(45647);
+const is_object_js_1 = __nccwpck_require__(92242);
+const errors_js_1 = __nccwpck_require__(15974);
+async function EmbeddedJWK(protectedHeader, token) {
+    const joseHeader = {
+        ...protectedHeader,
+        ...token?.header,
+    };
+    if (!(0, is_object_js_1.default)(joseHeader.jwk)) {
+        throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
     }
-
-    iconv.decodeStream = function decodeStream(encoding, options) {
-        return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
+    const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
+    if (key instanceof Uint8Array || key.type !== 'public') {
+        throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
     }
-
-    iconv.supportsStreams = true;
-}
-
-// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments).
-var stream_module;
-try {
-    stream_module = __nccwpck_require__(2203);
-} catch (e) {}
-
-if (stream_module && stream_module.Transform) {
-    iconv.enableStreamingAPI(stream_module);
-
-} else {
-    // In rare cases where 'stream' module is not available by default, throw a helpful exception.
-    iconv.encodeStream = iconv.decodeStream = function() {
-        throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.");
-    };
+    return key;
 }
 
-if (false) {}
-
 
 /***/ }),
 
-/***/ 42281:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 45396:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-
-var Buffer = (__nccwpck_require__(12803).Buffer);
-
-// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), 
-// we opt to dependency-inject it instead of creating a hard dependency.
-module.exports = function(stream_module) {
-    var Transform = stream_module.Transform;
-
-    // == Encoder stream =======================================================
-
-    function IconvLiteEncoderStream(conv, options) {
-        this.conv = conv;
-        options = options || {};
-        options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
-        Transform.call(this, options);
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.calculateJwkThumbprint = calculateJwkThumbprint;
+exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri;
+const digest_js_1 = __nccwpck_require__(12931);
+const base64url_js_1 = __nccwpck_require__(12635);
+const errors_js_1 = __nccwpck_require__(15974);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const is_object_js_1 = __nccwpck_require__(92242);
+const check = (value, description) => {
+    if (typeof value !== 'string' || !value) {
+        throw new errors_js_1.JWKInvalid(`${description} missing or invalid`);
     }
-
-    IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
-        constructor: { value: IconvLiteEncoderStream }
-    });
-
-    IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
-        if (typeof chunk != 'string')
-            return done(new Error("Iconv encoding stream needs strings as its input."));
-        try {
-            var res = this.conv.write(chunk);
-            if (res && res.length) this.push(res);
-            done();
-        }
-        catch (e) {
-            done(e);
-        }
+};
+async function calculateJwkThumbprint(jwk, digestAlgorithm) {
+    if (!(0, is_object_js_1.default)(jwk)) {
+        throw new TypeError('JWK must be an object');
     }
-
-    IconvLiteEncoderStream.prototype._flush = function(done) {
-        try {
-            var res = this.conv.end();
-            if (res && res.length) this.push(res);
-            done();
-        }
-        catch (e) {
-            done(e);
-        }
+    digestAlgorithm ??= 'sha256';
+    if (digestAlgorithm !== 'sha256' &&
+        digestAlgorithm !== 'sha384' &&
+        digestAlgorithm !== 'sha512') {
+        throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
     }
-
-    IconvLiteEncoderStream.prototype.collect = function(cb) {
-        var chunks = [];
-        this.on('error', cb);
-        this.on('data', function(chunk) { chunks.push(chunk); });
-        this.on('end', function() {
-            cb(null, Buffer.concat(chunks));
-        });
-        return this;
+    let components;
+    switch (jwk.kty) {
+        case 'EC':
+            check(jwk.crv, '"crv" (Curve) Parameter');
+            check(jwk.x, '"x" (X Coordinate) Parameter');
+            check(jwk.y, '"y" (Y Coordinate) Parameter');
+            components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
+            break;
+        case 'OKP':
+            check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
+            check(jwk.x, '"x" (Public Key) Parameter');
+            components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
+            break;
+        case 'RSA':
+            check(jwk.e, '"e" (Exponent) Parameter');
+            check(jwk.n, '"n" (Modulus) Parameter');
+            components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
+            break;
+        case 'oct':
+            check(jwk.k, '"k" (Key Value) Parameter');
+            components = { k: jwk.k, kty: jwk.kty };
+            break;
+        default:
+            throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
     }
+    const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components));
+    return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data));
+}
+async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
+    digestAlgorithm ??= 'sha256';
+    const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
+    return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
+}
 
 
-    // == Decoder stream =======================================================
+/***/ }),
 
-    function IconvLiteDecoderStream(conv, options) {
-        this.conv = conv;
-        options = options || {};
-        options.encoding = this.encoding = 'utf8'; // We output strings.
-        Transform.call(this, options);
-    }
+/***/ 25275:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-    IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
-        constructor: { value: IconvLiteDecoderStream }
-    });
+"use strict";
 
-    IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
-        if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))
-            return done(new Error("Iconv decoding stream needs buffers as its input."));
-        try {
-            var res = this.conv.write(chunk);
-            if (res && res.length) this.push(res, this.encoding);
-            done();
-        }
-        catch (e) {
-            done(e);
-        }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createLocalJWKSet = createLocalJWKSet;
+const import_js_1 = __nccwpck_require__(45647);
+const errors_js_1 = __nccwpck_require__(15974);
+const is_object_js_1 = __nccwpck_require__(92242);
+function getKtyFromAlg(alg) {
+    switch (typeof alg === 'string' && alg.slice(0, 2)) {
+        case 'RS':
+        case 'PS':
+            return 'RSA';
+        case 'ES':
+            return 'EC';
+        case 'Ed':
+            return 'OKP';
+        default:
+            throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
     }
-
-    IconvLiteDecoderStream.prototype._flush = function(done) {
-        try {
-            var res = this.conv.end();
-            if (res && res.length) this.push(res, this.encoding);                
-            done();
-        }
-        catch (e) {
-            done(e);
+}
+function isJWKSLike(jwks) {
+    return (jwks &&
+        typeof jwks === 'object' &&
+        Array.isArray(jwks.keys) &&
+        jwks.keys.every(isJWKLike));
+}
+function isJWKLike(key) {
+    return (0, is_object_js_1.default)(key);
+}
+function clone(obj) {
+    if (typeof structuredClone === 'function') {
+        return structuredClone(obj);
+    }
+    return JSON.parse(JSON.stringify(obj));
+}
+class LocalJWKSet {
+    _jwks;
+    _cached = new WeakMap();
+    constructor(jwks) {
+        if (!isJWKSLike(jwks)) {
+            throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed');
         }
+        this._jwks = clone(jwks);
     }
-
-    IconvLiteDecoderStream.prototype.collect = function(cb) {
-        var res = '';
-        this.on('error', cb);
-        this.on('data', function(chunk) { res += chunk; });
-        this.on('end', function() {
-            cb(null, res);
+    async getKey(protectedHeader, token) {
+        const { alg, kid } = { ...protectedHeader, ...token?.header };
+        const kty = getKtyFromAlg(alg);
+        const candidates = this._jwks.keys.filter((jwk) => {
+            let candidate = kty === jwk.kty;
+            if (candidate && typeof kid === 'string') {
+                candidate = kid === jwk.kid;
+            }
+            if (candidate && typeof jwk.alg === 'string') {
+                candidate = alg === jwk.alg;
+            }
+            if (candidate && typeof jwk.use === 'string') {
+                candidate = jwk.use === 'sig';
+            }
+            if (candidate && Array.isArray(jwk.key_ops)) {
+                candidate = jwk.key_ops.includes('verify');
+            }
+            if (candidate && alg === 'EdDSA') {
+                candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';
+            }
+            if (candidate) {
+                switch (alg) {
+                    case 'ES256':
+                        candidate = jwk.crv === 'P-256';
+                        break;
+                    case 'ES256K':
+                        candidate = jwk.crv === 'secp256k1';
+                        break;
+                    case 'ES384':
+                        candidate = jwk.crv === 'P-384';
+                        break;
+                    case 'ES512':
+                        candidate = jwk.crv === 'P-521';
+                        break;
+                }
+            }
+            return candidate;
         });
-        return this;
-    }
-
-    return {
-        IconvLiteEncoderStream: IconvLiteEncoderStream,
-        IconvLiteDecoderStream: IconvLiteDecoderStream,
-    };
-};
-
-
-/***/ }),
-
-/***/ 72024:
-/***/ ((module) => {
-
-/**
- * @preserve
- * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013)
- *
- * @author Jens Taylor
- * @see http://github.com/homebrewing/brauhaus-diff
- * @author Gary Court
- * @see http://github.com/garycourt/murmurhash-js
- * @author Austin Appleby
- * @see http://sites.google.com/site/murmurhash/
- */
-(function(){
-    var cache;
-
-    // Call this function without `new` to use the cached object (good for
-    // single-threaded environments), or with `new` to create a new object.
-    //
-    // @param {string} key A UTF-16 or ASCII string
-    // @param {number} seed An optional positive integer
-    // @return {object} A MurmurHash3 object for incremental hashing
-    function MurmurHash3(key, seed) {
-        var m = this instanceof MurmurHash3 ? this : cache;
-        m.reset(seed)
-        if (typeof key === 'string' && key.length > 0) {
-            m.hash(key);
-        }
-
-        if (m !== this) {
-            return m;
-        }
-    };
-
-    // Incrementally add a string to this hash
-    //
-    // @param {string} key A UTF-16 or ASCII string
-    // @return {object} this
-    MurmurHash3.prototype.hash = function(key) {
-        var h1, k1, i, top, len;
-
-        len = key.length;
-        this.len += len;
-
-        k1 = this.k1;
-        i = 0;
-        switch (this.rem) {
-            case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0;
-            case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0;
-            case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0;
-            case 3:
-                k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0;
-                k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0;
+        const { 0: jwk, length } = candidates;
+        if (length === 0) {
+            throw new errors_js_1.JWKSNoMatchingKey();
         }
-
-        this.rem = (len + this.rem) & 3; // & 3 is same as % 4
-        len -= this.rem;
-        if (len > 0) {
-            h1 = this.h1;
-            while (1) {
-                k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff;
-                k1 = (k1 << 15) | (k1 >>> 17);
-                k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff;
-
-                h1 ^= k1;
-                h1 = (h1 << 13) | (h1 >>> 19);
-                h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff;
-
-                if (i >= len) {
-                    break;
+        if (length !== 1) {
+            const error = new errors_js_1.JWKSMultipleMatchingKeys();
+            const { _cached } = this;
+            error[Symbol.asyncIterator] = async function* () {
+                for (const jwk of candidates) {
+                    try {
+                        yield await importWithAlgCache(_cached, jwk, alg);
+                    }
+                    catch { }
                 }
-
-                k1 = ((key.charCodeAt(i++) & 0xffff)) ^
-                     ((key.charCodeAt(i++) & 0xffff) << 8) ^
-                     ((key.charCodeAt(i++) & 0xffff) << 16);
-                top = key.charCodeAt(i++);
-                k1 ^= ((top & 0xff) << 24) ^
-                      ((top & 0xff00) >> 8);
-            }
-
-            k1 = 0;
-            switch (this.rem) {
-                case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16;
-                case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8;
-                case 1: k1 ^= (key.charCodeAt(i) & 0xffff);
-            }
-
-            this.h1 = h1;
+            };
+            throw error;
         }
-
-        this.k1 = k1;
-        return this;
-    };
-
-    // Get the result of this hash
-    //
-    // @return {number} The 32-bit hash
-    MurmurHash3.prototype.result = function() {
-        var k1, h1;
-        
-        k1 = this.k1;
-        h1 = this.h1;
-
-        if (k1 > 0) {
-            k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff;
-            k1 = (k1 << 15) | (k1 >>> 17);
-            k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff;
-            h1 ^= k1;
+        return importWithAlgCache(this._cached, jwk, alg);
+    }
+}
+async function importWithAlgCache(cache, jwk, alg) {
+    const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
+    if (cached[alg] === undefined) {
+        const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg);
+        if (key instanceof Uint8Array || key.type !== 'public') {
+            throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys');
         }
-
-        h1 ^= this.len;
-
-        h1 ^= h1 >>> 16;
-        h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff;
-        h1 ^= h1 >>> 13;
-        h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff;
-        h1 ^= h1 >>> 16;
-
-        return h1 >>> 0;
-    };
-
-    // Reset the hash object for reuse
-    //
-    // @param {number} seed An optional positive integer
-    MurmurHash3.prototype.reset = function(seed) {
-        this.h1 = typeof seed === 'number' ? seed : 0;
-        this.rem = this.k1 = this.len = 0;
-        return this;
-    };
-
-    // A cached object to use. This can be safely used if you're in a single-
-    // threaded environment, otherwise you need to create new hashes to use.
-    cache = new MurmurHash3();
-
-    if (true) {
-        module.exports = MurmurHash3;
-    } else {}
-}());
+        cached[alg] = key;
+    }
+    return cached[alg];
+}
+function createLocalJWKSet(jwks) {
+    const set = new LocalJWKSet(jwks);
+    const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+    Object.defineProperties(localJWKSet, {
+        jwks: {
+            value: () => clone(set._jwks),
+            enumerable: true,
+            configurable: false,
+            writable: false,
+        },
+    });
+    return localJWKSet;
+}
 
 
 /***/ }),
 
-/***/ 68850:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 69260:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AddressError = void 0;
-class AddressError extends Error {
-    constructor(message, parseMessage) {
-        super(message);
-        this.name = 'AddressError';
-        if (parseMessage !== null) {
-            this.parseMessage = parseMessage;
+exports.experimental_jwksCache = exports.jwksCache = void 0;
+exports.createRemoteJWKSet = createRemoteJWKSet;
+const fetch_jwks_js_1 = __nccwpck_require__(20311);
+const errors_js_1 = __nccwpck_require__(15974);
+const local_js_1 = __nccwpck_require__(25275);
+const is_object_js_1 = __nccwpck_require__(92242);
+function isCloudflareWorkers() {
+    return (typeof WebSocketPair !== 'undefined' ||
+        (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
+        (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
+}
+let USER_AGENT;
+if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
+    const NAME = 'jose';
+    const VERSION = 'v5.9.6';
+    USER_AGENT = `${NAME}/${VERSION}`;
+}
+exports.jwksCache = Symbol();
+function isFreshJwksCache(input, cacheMaxAge) {
+    if (typeof input !== 'object' || input === null) {
+        return false;
+    }
+    if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {
+        return false;
+    }
+    if (!('jwks' in input) ||
+        !(0, is_object_js_1.default)(input.jwks) ||
+        !Array.isArray(input.jwks.keys) ||
+        !Array.prototype.every.call(input.jwks.keys, is_object_js_1.default)) {
+        return false;
+    }
+    return true;
+}
+class RemoteJWKSet {
+    _url;
+    _timeoutDuration;
+    _cooldownDuration;
+    _cacheMaxAge;
+    _jwksTimestamp;
+    _pendingFetch;
+    _options;
+    _local;
+    _cache;
+    constructor(url, options) {
+        if (!(url instanceof URL)) {
+            throw new TypeError('url must be an instance of URL');
+        }
+        this._url = new URL(url.href);
+        this._options = { agent: options?.agent, headers: options?.headers };
+        this._timeoutDuration =
+            typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
+        this._cooldownDuration =
+            typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
+        this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
+        if (options?.[exports.jwksCache] !== undefined) {
+            this._cache = options?.[exports.jwksCache];
+            if (isFreshJwksCache(options?.[exports.jwksCache], this._cacheMaxAge)) {
+                this._jwksTimestamp = this._cache.uat;
+                this._local = (0, local_js_1.createLocalJWKSet)(this._cache.jwks);
+            }
+        }
+    }
+    coolingDown() {
+        return typeof this._jwksTimestamp === 'number'
+            ? Date.now() < this._jwksTimestamp + this._cooldownDuration
+            : false;
+    }
+    fresh() {
+        return typeof this._jwksTimestamp === 'number'
+            ? Date.now() < this._jwksTimestamp + this._cacheMaxAge
+            : false;
+    }
+    async getKey(protectedHeader, token) {
+        if (!this._local || !this.fresh()) {
+            await this.reload();
+        }
+        try {
+            return await this._local(protectedHeader, token);
+        }
+        catch (err) {
+            if (err instanceof errors_js_1.JWKSNoMatchingKey) {
+                if (this.coolingDown() === false) {
+                    await this.reload();
+                    return this._local(protectedHeader, token);
+                }
+            }
+            throw err;
+        }
+    }
+    async reload() {
+        if (this._pendingFetch && isCloudflareWorkers()) {
+            this._pendingFetch = undefined;
         }
+        const headers = new Headers(this._options.headers);
+        if (USER_AGENT && !headers.has('User-Agent')) {
+            headers.set('User-Agent', USER_AGENT);
+            this._options.headers = Object.fromEntries(headers.entries());
+        }
+        this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options)
+            .then((json) => {
+            this._local = (0, local_js_1.createLocalJWKSet)(json);
+            if (this._cache) {
+                this._cache.uat = Date.now();
+                this._cache.jwks = json;
+            }
+            this._jwksTimestamp = Date.now();
+            this._pendingFetch = undefined;
+        })
+            .catch((err) => {
+            this._pendingFetch = undefined;
+            throw err;
+        });
+        await this._pendingFetch;
     }
 }
-exports.AddressError = AddressError;
-//# sourceMappingURL=address-error.js.map
+function createRemoteJWKSet(url, options) {
+    const set = new RemoteJWKSet(url, options);
+    const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+    Object.defineProperties(remoteJWKSet, {
+        coolingDown: {
+            get: () => set.coolingDown(),
+            enumerable: true,
+            configurable: false,
+        },
+        fresh: {
+            get: () => set.fresh(),
+            enumerable: true,
+            configurable: false,
+        },
+        reload: {
+            value: () => set.reload(),
+            enumerable: true,
+            configurable: false,
+            writable: false,
+        },
+        reloading: {
+            get: () => !!set._pendingFetch,
+            enumerable: true,
+            configurable: false,
+        },
+        jwks: {
+            value: () => set._local?.jwks(),
+            enumerable: true,
+            configurable: false,
+            writable: false,
+        },
+    });
+    return remoteJWKSet;
+}
+exports.experimental_jwksCache = exports.jwksCache;
+
 
 /***/ }),
 
-/***/ 45864:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 21760:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isCorrect = exports.isInSubnet = void 0;
-function isInSubnet(address) {
-    if (this.subnetMask < address.subnetMask) {
-        return false;
+exports.CompactSign = void 0;
+const sign_js_1 = __nccwpck_require__(86170);
+class CompactSign {
+    _flattened;
+    constructor(payload) {
+        this._flattened = new sign_js_1.FlattenedSign(payload);
     }
-    if (this.mask(address.subnetMask) === address.mask()) {
-        return true;
+    setProtectedHeader(protectedHeader) {
+        this._flattened.setProtectedHeader(protectedHeader);
+        return this;
     }
-    return false;
-}
-exports.isInSubnet = isInSubnet;
-function isCorrect(defaultBits) {
-    return function () {
-        if (this.addressMinusSuffix !== this.correctForm()) {
-            return false;
-        }
-        if (this.subnetMask === defaultBits && !this.parsedSubnet) {
-            return true;
+    async sign(key, options) {
+        const jws = await this._flattened.sign(key, options);
+        if (jws.payload === undefined) {
+            throw new TypeError('use the flattened module for creating JWS with b64: false');
         }
-        return this.parsedSubnet === String(this.subnetMask);
-    };
+        return `${jws.protected}.${jws.payload}.${jws.signature}`;
+    }
 }
-exports.isCorrect = isCorrect;
-//# sourceMappingURL=common.js.map
+exports.CompactSign = CompactSign;
+
 
 /***/ }),
 
-/***/ 79253:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 94212:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.compactVerify = compactVerify;
+const verify_js_1 = __nccwpck_require__(56358);
+const errors_js_1 = __nccwpck_require__(15974);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+async function compactVerify(jws, key, options) {
+    if (jws instanceof Uint8Array) {
+        jws = buffer_utils_js_1.decoder.decode(jws);
+    }
+    if (typeof jws !== 'string') {
+        throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array');
+    }
+    const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
+    if (length !== 3) {
+        throw new errors_js_1.JWSInvalid('Invalid Compact JWS');
+    }
+    const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options);
+    const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
+    if (typeof key === 'function') {
+        return { ...result, key: verified.key };
     }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
     return result;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.v6 = exports.AddressError = exports.Address6 = exports.Address4 = void 0;
-const ipv4_1 = __nccwpck_require__(17946);
-Object.defineProperty(exports, "Address4", ({ enumerable: true, get: function () { return ipv4_1.Address4; } }));
-const ipv6_1 = __nccwpck_require__(38096);
-Object.defineProperty(exports, "Address6", ({ enumerable: true, get: function () { return ipv6_1.Address6; } }));
-const address_error_1 = __nccwpck_require__(68850);
-Object.defineProperty(exports, "AddressError", ({ enumerable: true, get: function () { return address_error_1.AddressError; } }));
-const helpers = __importStar(__nccwpck_require__(20339));
-exports.v6 = { helpers };
-//# sourceMappingURL=ip-address.js.map
+}
+
 
 /***/ }),
 
-/***/ 17946:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 86170:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-/* eslint-disable no-param-reassign */
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Address4 = void 0;
-const common = __importStar(__nccwpck_require__(45864));
-const constants = __importStar(__nccwpck_require__(66437));
-const address_error_1 = __nccwpck_require__(68850);
-const jsbn_1 = __nccwpck_require__(95947);
-const sprintf_js_1 = __nccwpck_require__(19973);
-/**
- * Represents an IPv4 address
- * @class Address4
- * @param {string} address - An IPv4 address string
- */
-class Address4 {
-    constructor(address) {
-        this.groups = constants.GROUPS;
-        this.parsedAddress = [];
-        this.parsedSubnet = '';
-        this.subnet = '/32';
-        this.subnetMask = 32;
-        this.v4 = true;
-        /**
-         * Returns true if the address is correct, false otherwise
-         * @memberof Address4
-         * @instance
-         * @returns {Boolean}
-         */
-        this.isCorrect = common.isCorrect(constants.BITS);
-        /**
-         * Returns true if the given address is in the subnet of the current address
-         * @memberof Address4
-         * @instance
-         * @returns {boolean}
-         */
-        this.isInSubnet = common.isInSubnet;
-        this.address = address;
-        const subnet = constants.RE_SUBNET_STRING.exec(address);
-        if (subnet) {
-            this.parsedSubnet = subnet[0].replace('/', '');
-            this.subnetMask = parseInt(this.parsedSubnet, 10);
-            this.subnet = `/${this.subnetMask}`;
-            if (this.subnetMask < 0 || this.subnetMask > constants.BITS) {
-                throw new address_error_1.AddressError('Invalid subnet mask.');
-            }
-            address = address.replace(constants.RE_SUBNET_STRING, '');
+exports.FlattenedSign = void 0;
+const base64url_js_1 = __nccwpck_require__(12635);
+const sign_js_1 = __nccwpck_require__(26966);
+const is_disjoint_js_1 = __nccwpck_require__(21853);
+const errors_js_1 = __nccwpck_require__(15974);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const check_key_type_js_1 = __nccwpck_require__(29555);
+const validate_crit_js_1 = __nccwpck_require__(15595);
+class FlattenedSign {
+    _payload;
+    _protectedHeader;
+    _unprotectedHeader;
+    constructor(payload) {
+        if (!(payload instanceof Uint8Array)) {
+            throw new TypeError('payload must be an instance of Uint8Array');
         }
-        this.addressMinusSuffix = address;
-        this.parsedAddress = this.parse(address);
+        this._payload = payload;
     }
-    static isValid(address) {
-        try {
-            // eslint-disable-next-line no-new
-            new Address4(address);
-            return true;
-        }
-        catch (e) {
-            return false;
+    setProtectedHeader(protectedHeader) {
+        if (this._protectedHeader) {
+            throw new TypeError('setProtectedHeader can only be called once');
         }
+        this._protectedHeader = protectedHeader;
+        return this;
     }
-    /*
-     * Parses a v4 address
-     */
-    parse(address) {
-        const groups = address.split('.');
-        if (!address.match(constants.RE_ADDRESS)) {
-            throw new address_error_1.AddressError('Invalid IPv4 address.');
+    setUnprotectedHeader(unprotectedHeader) {
+        if (this._unprotectedHeader) {
+            throw new TypeError('setUnprotectedHeader can only be called once');
         }
-        return groups;
-    }
-    /**
-     * Returns the correct form of an address
-     * @memberof Address4
-     * @instance
-     * @returns {String}
-     */
-    correctForm() {
-        return this.parsedAddress.map((part) => parseInt(part, 10)).join('.');
+        this._unprotectedHeader = unprotectedHeader;
+        return this;
     }
-    /**
-     * Converts a hex string to an IPv4 address object
-     * @memberof Address4
-     * @static
-     * @param {string} hex - a hex string to convert
-     * @returns {Address4}
-     */
-    static fromHex(hex) {
-        const padded = hex.replace(/:/g, '').padStart(8, '0');
-        const groups = [];
-        let i;
-        for (i = 0; i < 8; i += 2) {
-            const h = padded.slice(i, i + 2);
-            groups.push(parseInt(h, 16));
+    async sign(key, options) {
+        if (!this._protectedHeader && !this._unprotectedHeader) {
+            throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
         }
-        return new Address4(groups.join('.'));
+        if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) {
+            throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
+        }
+        const joseHeader = {
+            ...this._protectedHeader,
+            ...this._unprotectedHeader,
+        };
+        const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
+        let b64 = true;
+        if (extensions.has('b64')) {
+            b64 = this._protectedHeader.b64;
+            if (typeof b64 !== 'boolean') {
+                throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+            }
+        }
+        const { alg } = joseHeader;
+        if (typeof alg !== 'string' || !alg) {
+            throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+        }
+        (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'sign');
+        let payload = this._payload;
+        if (b64) {
+            payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload));
+        }
+        let protectedHeader;
+        if (this._protectedHeader) {
+            protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
+        }
+        else {
+            protectedHeader = buffer_utils_js_1.encoder.encode('');
+        }
+        const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload);
+        const signature = await (0, sign_js_1.default)(alg, key, data);
+        const jws = {
+            signature: (0, base64url_js_1.encode)(signature),
+            payload: '',
+        };
+        if (b64) {
+            jws.payload = buffer_utils_js_1.decoder.decode(payload);
+        }
+        if (this._unprotectedHeader) {
+            jws.header = this._unprotectedHeader;
+        }
+        if (this._protectedHeader) {
+            jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
+        }
+        return jws;
     }
-    /**
-     * Converts an integer into a IPv4 address object
-     * @memberof Address4
-     * @static
-     * @param {integer} integer - a number to convert
-     * @returns {Address4}
-     */
-    static fromInteger(integer) {
-        return Address4.fromHex(integer.toString(16));
+}
+exports.FlattenedSign = FlattenedSign;
+
+
+/***/ }),
+
+/***/ 56358:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.flattenedVerify = flattenedVerify;
+const base64url_js_1 = __nccwpck_require__(12635);
+const verify_js_1 = __nccwpck_require__(11242);
+const errors_js_1 = __nccwpck_require__(15974);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const is_disjoint_js_1 = __nccwpck_require__(21853);
+const is_object_js_1 = __nccwpck_require__(92242);
+const check_key_type_js_1 = __nccwpck_require__(29555);
+const validate_crit_js_1 = __nccwpck_require__(15595);
+const validate_algorithms_js_1 = __nccwpck_require__(19917);
+const is_jwk_js_1 = __nccwpck_require__(91229);
+const import_js_1 = __nccwpck_require__(45647);
+async function flattenedVerify(jws, key, options) {
+    if (!(0, is_object_js_1.default)(jws)) {
+        throw new errors_js_1.JWSInvalid('Flattened JWS must be an object');
     }
-    /**
-     * Return an address from in-addr.arpa form
-     * @memberof Address4
-     * @static
-     * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
-     * @returns {Adress4}
-     * @example
-     * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
-     * address.correctForm(); // '192.0.2.42'
-     */
-    static fromArpa(arpaFormAddress) {
-        // remove ending ".in-addr.arpa." or just "."
-        const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, '');
-        const address = leader.split('.').reverse().join('.');
-        return new Address4(address);
+    if (jws.protected === undefined && jws.header === undefined) {
+        throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
+    }
+    if (jws.protected !== undefined && typeof jws.protected !== 'string') {
+        throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type');
     }
-    /**
-     * Converts an IPv4 address object to a hex string
-     * @memberof Address4
-     * @instance
-     * @returns {String}
-     */
-    toHex() {
-        return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)('%02x', parseInt(part, 10))).join(':');
+    if (jws.payload === undefined) {
+        throw new errors_js_1.JWSInvalid('JWS Payload missing');
     }
-    /**
-     * Converts an IPv4 address object to an array of bytes
-     * @memberof Address4
-     * @instance
-     * @returns {Array}
-     */
-    toArray() {
-        return this.parsedAddress.map((part) => parseInt(part, 10));
+    if (typeof jws.signature !== 'string') {
+        throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type');
     }
-    /**
-     * Converts an IPv4 address object to an IPv6 address group
-     * @memberof Address4
-     * @instance
-     * @returns {String}
-     */
-    toGroup6() {
-        const output = [];
-        let i;
-        for (i = 0; i < constants.GROUPS; i += 2) {
-            const hex = (0, sprintf_js_1.sprintf)('%02x%02x', parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10));
-            output.push((0, sprintf_js_1.sprintf)('%x', parseInt(hex, 16)));
+    if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) {
+        throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type');
+    }
+    let parsedProt = {};
+    if (jws.protected) {
+        try {
+            const protectedHeader = (0, base64url_js_1.decode)(jws.protected);
+            parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
+        }
+        catch {
+            throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid');
         }
-        return output.join(':');
     }
-    /**
-     * Returns the address as a BigInteger
-     * @memberof Address4
-     * @instance
-     * @returns {BigInteger}
-     */
-    bigInteger() {
-        return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%02x', parseInt(n, 10))).join(''), 16);
+    if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) {
+        throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
     }
-    /**
-     * Helper function getting start address.
-     * @memberof Address4
-     * @instance
-     * @returns {BigInteger}
-     */
-    _startAddress() {
-        return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants.BITS - this.subnetMask), 2);
+    const joseHeader = {
+        ...parsedProt,
+        ...jws.header,
+    };
+    const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
+    let b64 = true;
+    if (extensions.has('b64')) {
+        b64 = parsedProt.b64;
+        if (typeof b64 !== 'boolean') {
+            throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+        }
     }
-    /**
-     * The first address in the range given by this address' subnet.
-     * Often referred to as the Network Address.
-     * @memberof Address4
-     * @instance
-     * @returns {Address4}
-     */
-    startAddress() {
-        return Address4.fromBigInteger(this._startAddress());
+    const { alg } = joseHeader;
+    if (typeof alg !== 'string' || !alg) {
+        throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
     }
-    /**
-     * The first host address in the range given by this address's subnet ie
-     * the first address after the Network Address
-     * @memberof Address4
-     * @instance
-     * @returns {Address4}
-     */
-    startAddressExclusive() {
-        const adjust = new jsbn_1.BigInteger('1');
-        return Address4.fromBigInteger(this._startAddress().add(adjust));
+    const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms);
+    if (algorithms && !algorithms.has(alg)) {
+        throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
     }
-    /**
-     * Helper function getting end address.
-     * @memberof Address4
-     * @instance
-     * @returns {BigInteger}
-     */
-    _endAddress() {
-        return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants.BITS - this.subnetMask), 2);
+    if (b64) {
+        if (typeof jws.payload !== 'string') {
+            throw new errors_js_1.JWSInvalid('JWS Payload must be a string');
+        }
     }
-    /**
-     * The last address in the range given by this address' subnet
-     * Often referred to as the Broadcast
-     * @memberof Address4
-     * @instance
-     * @returns {Address4}
-     */
-    endAddress() {
-        return Address4.fromBigInteger(this._endAddress());
+    else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
+        throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
     }
-    /**
-     * The last host address in the range given by this address's subnet ie
-     * the last address prior to the Broadcast Address
-     * @memberof Address4
-     * @instance
-     * @returns {Address4}
-     */
-    endAddressExclusive() {
-        const adjust = new jsbn_1.BigInteger('1');
-        return Address4.fromBigInteger(this._endAddress().subtract(adjust));
+    let resolvedKey = false;
+    if (typeof key === 'function') {
+        key = await key(parsedProt, jws);
+        resolvedKey = true;
+        (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify');
+        if ((0, is_jwk_js_1.isJWK)(key)) {
+            key = await (0, import_js_1.importJWK)(key, alg);
+        }
     }
-    /**
-     * Converts a BigInteger to a v4 address object
-     * @memberof Address4
-     * @static
-     * @param {BigInteger} bigInteger - a BigInteger to convert
-     * @returns {Address4}
-     */
-    static fromBigInteger(bigInteger) {
-        return Address4.fromInteger(parseInt(bigInteger.toString(), 10));
+    else {
+        (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify');
     }
-    /**
-     * Returns the first n bits of the address, defaulting to the
-     * subnet mask
-     * @memberof Address4
-     * @instance
-     * @returns {String}
-     */
-    mask(mask) {
-        if (mask === undefined) {
-            mask = this.subnetMask;
-        }
-        return this.getBitsBase2(0, mask);
+    const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload);
+    let signature;
+    try {
+        signature = (0, base64url_js_1.decode)(jws.signature);
     }
-    /**
-     * Returns the bits in the given range as a base-2 string
-     * @memberof Address4
-     * @instance
-     * @returns {string}
-     */
-    getBitsBase2(start, end) {
-        return this.binaryZeroPad().slice(start, end);
+    catch {
+        throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature');
     }
-    /**
-     * Return the reversed ip6.arpa form of the address
-     * @memberof Address4
-     * @param {Object} options
-     * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
-     * @instance
-     * @returns {String}
-     */
-    reverseForm(options) {
-        if (!options) {
-            options = {};
+    const verified = await (0, verify_js_1.default)(alg, key, signature, data);
+    if (!verified) {
+        throw new errors_js_1.JWSSignatureVerificationFailed();
+    }
+    let payload;
+    if (b64) {
+        try {
+            payload = (0, base64url_js_1.decode)(jws.payload);
         }
-        const reversed = this.correctForm().split('.').reverse().join('.');
-        if (options.omitSuffix) {
-            return reversed;
+        catch {
+            throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload');
         }
-        return (0, sprintf_js_1.sprintf)('%s.in-addr.arpa.', reversed);
     }
-    /**
-     * Returns true if the given address is a multicast address
-     * @memberof Address4
-     * @instance
-     * @returns {boolean}
-     */
-    isMulticast() {
-        return this.isInSubnet(new Address4('224.0.0.0/4'));
+    else if (typeof jws.payload === 'string') {
+        payload = buffer_utils_js_1.encoder.encode(jws.payload);
     }
-    /**
-     * Returns a zero-padded base-2 string representation of the address
-     * @memberof Address4
-     * @instance
-     * @returns {string}
-     */
-    binaryZeroPad() {
-        return this.bigInteger().toString(2).padStart(constants.BITS, '0');
+    else {
+        payload = jws.payload;
     }
-    /**
-     * Groups an IPv4 address for inclusion at the end of an IPv6 address
-     * @returns {String}
-     */
-    groupForV6() {
-        const segments = this.parsedAddress;
-        return this.address.replace(constants.RE_ADDRESS, (0, sprintf_js_1.sprintf)('%s.%s', segments.slice(0, 2).join('.'), segments.slice(2, 4).join('.')));
+    const result = { payload };
+    if (jws.protected !== undefined) {
+        result.protectedHeader = parsedProt;
     }
+    if (jws.header !== undefined) {
+        result.unprotectedHeader = jws.header;
+    }
+    if (resolvedKey) {
+        return { ...result, key };
+    }
+    return result;
 }
-exports.Address4 = Address4;
-//# sourceMappingURL=ipv4.js.map
+
 
 /***/ }),
 
-/***/ 38096:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 50443:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-/* eslint-disable prefer-destructuring */
-/* eslint-disable no-param-reassign */
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Address6 = void 0;
-const common = __importStar(__nccwpck_require__(45864));
-const constants4 = __importStar(__nccwpck_require__(66437));
-const constants6 = __importStar(__nccwpck_require__(75280));
-const helpers = __importStar(__nccwpck_require__(20339));
-const ipv4_1 = __nccwpck_require__(17946);
-const regular_expressions_1 = __nccwpck_require__(72016);
-const address_error_1 = __nccwpck_require__(68850);
-const jsbn_1 = __nccwpck_require__(95947);
-const sprintf_js_1 = __nccwpck_require__(19973);
-function assert(condition) {
-    if (!condition) {
-        throw new Error('Assertion failed.');
-    }
-}
-function addCommas(number) {
-    const r = /(\d+)(\d{3})/;
-    while (r.test(number)) {
-        number = number.replace(r, '$1,$2');
+exports.GeneralSign = void 0;
+const sign_js_1 = __nccwpck_require__(86170);
+const errors_js_1 = __nccwpck_require__(15974);
+class IndividualSignature {
+    parent;
+    protectedHeader;
+    unprotectedHeader;
+    options;
+    key;
+    constructor(sig, key, options) {
+        this.parent = sig;
+        this.key = key;
+        this.options = options;
     }
-    return number;
-}
-function spanLeadingZeroes4(n) {
-    n = n.replace(/^(0{1,})([1-9]+)$/, '$1$2');
-    n = n.replace(/^(0{1,})(0)$/, '$1$2');
-    return n;
-}
-/*
- * A helper function to compact an array
- */
-function compact(address, slice) {
-    const s1 = [];
-    const s2 = [];
-    let i;
-    for (i = 0; i < address.length; i++) {
-        if (i < slice[0]) {
-            s1.push(address[i]);
-        }
-        else if (i > slice[1]) {
-            s2.push(address[i]);
+    setProtectedHeader(protectedHeader) {
+        if (this.protectedHeader) {
+            throw new TypeError('setProtectedHeader can only be called once');
         }
+        this.protectedHeader = protectedHeader;
+        return this;
     }
-    return s1.concat(['compact']).concat(s2);
-}
-function paddedHex(octet) {
-    return (0, sprintf_js_1.sprintf)('%04x', parseInt(octet, 16));
-}
-function unsignByte(b) {
-    // eslint-disable-next-line no-bitwise
-    return b & 0xff;
-}
-/**
- * Represents an IPv6 address
- * @class Address6
- * @param {string} address - An IPv6 address string
- * @param {number} [groups=8] - How many octets to parse
- * @example
- * var address = new Address6('2001::/32');
- */
-class Address6 {
-    constructor(address, optionalGroups) {
-        this.addressMinusSuffix = '';
-        this.parsedSubnet = '';
-        this.subnet = '/128';
-        this.subnetMask = 128;
-        this.v4 = false;
-        this.zone = '';
-        // #region Attributes
-        /**
-         * Returns true if the given address is in the subnet of the current address
-         * @memberof Address6
-         * @instance
-         * @returns {boolean}
-         */
-        this.isInSubnet = common.isInSubnet;
-        /**
-         * Returns true if the address is correct, false otherwise
-         * @memberof Address6
-         * @instance
-         * @returns {boolean}
-         */
-        this.isCorrect = common.isCorrect(constants6.BITS);
-        if (optionalGroups === undefined) {
-            this.groups = constants6.GROUPS;
-        }
-        else {
-            this.groups = optionalGroups;
-        }
-        this.address = address;
-        const subnet = constants6.RE_SUBNET_STRING.exec(address);
-        if (subnet) {
-            this.parsedSubnet = subnet[0].replace('/', '');
-            this.subnetMask = parseInt(this.parsedSubnet, 10);
-            this.subnet = `/${this.subnetMask}`;
-            if (Number.isNaN(this.subnetMask) ||
-                this.subnetMask < 0 ||
-                this.subnetMask > constants6.BITS) {
-                throw new address_error_1.AddressError('Invalid subnet mask.');
-            }
-            address = address.replace(constants6.RE_SUBNET_STRING, '');
-        }
-        else if (/\//.test(address)) {
-            throw new address_error_1.AddressError('Invalid subnet mask.');
-        }
-        const zone = constants6.RE_ZONE_STRING.exec(address);
-        if (zone) {
-            this.zone = zone[0];
-            address = address.replace(constants6.RE_ZONE_STRING, '');
+    setUnprotectedHeader(unprotectedHeader) {
+        if (this.unprotectedHeader) {
+            throw new TypeError('setUnprotectedHeader can only be called once');
         }
-        this.addressMinusSuffix = address;
-        this.parsedAddress = this.parse(this.addressMinusSuffix);
+        this.unprotectedHeader = unprotectedHeader;
+        return this;
     }
-    static isValid(address) {
-        try {
-            // eslint-disable-next-line no-new
-            new Address6(address);
-            return true;
-        }
-        catch (e) {
-            return false;
-        }
+    addSignature(...args) {
+        return this.parent.addSignature(...args);
     }
-    /**
-     * Convert a BigInteger to a v6 address object
-     * @memberof Address6
-     * @static
-     * @param {BigInteger} bigInteger - a BigInteger to convert
-     * @returns {Address6}
-     * @example
-     * var bigInteger = new BigInteger('1000000000000');
-     * var address = Address6.fromBigInteger(bigInteger);
-     * address.correctForm(); // '::e8:d4a5:1000'
-     */
-    static fromBigInteger(bigInteger) {
-        const hex = bigInteger.toString(16).padStart(32, '0');
-        const groups = [];
-        let i;
-        for (i = 0; i < constants6.GROUPS; i++) {
-            groups.push(hex.slice(i * 4, (i + 1) * 4));
-        }
-        return new Address6(groups.join(':'));
+    sign(...args) {
+        return this.parent.sign(...args);
     }
-    /**
-     * Convert a URL (with optional port number) to an address object
-     * @memberof Address6
-     * @static
-     * @param {string} url - a URL with optional port number
-     * @example
-     * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
-     * addressAndPort.address.correctForm(); // 'ffff::'
-     * addressAndPort.port; // 8080
-     */
-    static fromURL(url) {
-        let host;
-        let port = null;
-        let result;
-        // If we have brackets parse them and find a port
-        if (url.indexOf('[') !== -1 && url.indexOf(']:') !== -1) {
-            result = constants6.RE_URL_WITH_PORT.exec(url);
-            if (result === null) {
-                return {
-                    error: 'failed to parse address with port',
-                    address: null,
-                    port: null,
-                };
-            }
-            host = result[1];
-            port = result[2];
-            // If there's a URL extract the address
-        }
-        else if (url.indexOf('/') !== -1) {
-            // Remove the protocol prefix
-            url = url.replace(/^[a-z0-9]+:\/\//, '');
-            // Parse the address
-            result = constants6.RE_URL.exec(url);
-            if (result === null) {
-                return {
-                    error: 'failed to parse address from URL',
-                    address: null,
-                    port: null,
-                };
-            }
-            host = result[1];
-            // Otherwise just assign the URL to the host and let the library parse it
-        }
-        else {
-            host = url;
+    done() {
+        return this.parent;
+    }
+}
+class GeneralSign {
+    _payload;
+    _signatures = [];
+    constructor(payload) {
+        this._payload = payload;
+    }
+    addSignature(key, options) {
+        const signature = new IndividualSignature(this, key, options);
+        this._signatures.push(signature);
+        return signature;
+    }
+    async sign() {
+        if (!this._signatures.length) {
+            throw new errors_js_1.JWSInvalid('at least one signature must be added');
         }
-        // If there's a port convert it to an integer
-        if (port) {
-            port = parseInt(port, 10);
-            // squelch out of range ports
-            if (port < 0 || port > 65536) {
-                port = null;
+        const jws = {
+            signatures: [],
+            payload: '',
+        };
+        for (let i = 0; i < this._signatures.length; i++) {
+            const signature = this._signatures[i];
+            const flattened = new sign_js_1.FlattenedSign(this._payload);
+            flattened.setProtectedHeader(signature.protectedHeader);
+            flattened.setUnprotectedHeader(signature.unprotectedHeader);
+            const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
+            if (i === 0) {
+                jws.payload = payload;
             }
+            else if (jws.payload !== payload) {
+                throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');
+            }
+            jws.signatures.push(rest);
         }
-        else {
-            // Standardize `undefined` to `null`
-            port = null;
-        }
-        return {
-            address: new Address6(host),
-            port,
-        };
+        return jws;
     }
-    /**
-     * Create an IPv6-mapped address given an IPv4 address
-     * @memberof Address6
-     * @static
-     * @param {string} address - An IPv4 address string
-     * @returns {Address6}
-     * @example
-     * var address = Address6.fromAddress4('192.168.0.1');
-     * address.correctForm(); // '::ffff:c0a8:1'
-     * address.to4in6(); // '::ffff:192.168.0.1'
-     */
-    static fromAddress4(address) {
-        const address4 = new ipv4_1.Address4(address);
-        const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
-        return new Address6(`::ffff:${address4.correctForm()}/${mask6}`);
+}
+exports.GeneralSign = GeneralSign;
+
+
+/***/ }),
+
+/***/ 88323:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.generalVerify = generalVerify;
+const verify_js_1 = __nccwpck_require__(56358);
+const errors_js_1 = __nccwpck_require__(15974);
+const is_object_js_1 = __nccwpck_require__(92242);
+async function generalVerify(jws, key, options) {
+    if (!(0, is_object_js_1.default)(jws)) {
+        throw new errors_js_1.JWSInvalid('General JWS must be an object');
     }
-    /**
-     * Return an address from ip6.arpa form
-     * @memberof Address6
-     * @static
-     * @param {string} arpaFormAddress - an 'ip6.arpa' form address
-     * @returns {Adress6}
-     * @example
-     * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
-     * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
-     */
-    static fromArpa(arpaFormAddress) {
-        // remove ending ".ip6.arpa." or just "."
-        let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, '');
-        const semicolonAmount = 7;
-        // correct ip6.arpa form with ending removed will be 63 characters
-        if (address.length !== 63) {
-            throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
+    if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) {
+        throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type');
+    }
+    for (const signature of jws.signatures) {
+        try {
+            return await (0, verify_js_1.flattenedVerify)({
+                header: signature.header,
+                payload: jws.payload,
+                protected: signature.protected,
+                signature: signature.signature,
+            }, key, options);
         }
-        const parts = address.split('.').reverse();
-        for (let i = semicolonAmount; i > 0; i--) {
-            const insertIndex = i * 4;
-            parts.splice(insertIndex, 0, ':');
+        catch {
         }
-        address = parts.join('');
-        return new Address6(address);
     }
-    /**
-     * Return the Microsoft UNC transcription of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String} the Microsoft UNC transcription of the address
-     */
-    microsoftTranscription() {
-        return (0, sprintf_js_1.sprintf)('%s.ipv6-literal.net', this.correctForm().replace(/:/g, '-'));
+    throw new errors_js_1.JWSSignatureVerificationFailed();
+}
+
+
+/***/ }),
+
+/***/ 95339:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.jwtDecrypt = jwtDecrypt;
+const decrypt_js_1 = __nccwpck_require__(14298);
+const jwt_claims_set_js_1 = __nccwpck_require__(13354);
+const errors_js_1 = __nccwpck_require__(15974);
+async function jwtDecrypt(jwt, key, options) {
+    const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options);
+    const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options);
+    const { protectedHeader } = decrypted;
+    if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
+        throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch');
     }
-    /**
-     * Return the first n bits of the address, defaulting to the subnet mask
-     * @memberof Address6
-     * @instance
-     * @param {number} [mask=subnet] - the number of bits to mask
-     * @returns {String} the first n bits of the address as a string
-     */
-    mask(mask = this.subnetMask) {
-        return this.getBitsBase2(0, mask);
+    if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
+        throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch');
     }
-    /**
-     * Return the number of possible subnets of a given size in the address
-     * @memberof Address6
-     * @instance
-     * @param {number} [size=128] - the subnet size
-     * @returns {String}
-     */
-    // TODO: probably useful to have a numeric version of this too
-    possibleSubnets(subnetSize = 128) {
-        const availableBits = constants6.BITS - this.subnetMask;
-        const subnetBits = Math.abs(subnetSize - constants6.BITS);
-        const subnetPowers = availableBits - subnetBits;
-        if (subnetPowers < 0) {
-            return '0';
+    if (protectedHeader.aud !== undefined &&
+        JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
+        throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch');
+    }
+    const result = { payload, protectedHeader };
+    if (typeof key === 'function') {
+        return { ...result, key: decrypted.key };
+    }
+    return result;
+}
+
+
+/***/ }),
+
+/***/ 38375:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.EncryptJWT = void 0;
+const encrypt_js_1 = __nccwpck_require__(4434);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const produce_js_1 = __nccwpck_require__(37318);
+class EncryptJWT extends produce_js_1.ProduceJWT {
+    _cek;
+    _iv;
+    _keyManagementParameters;
+    _protectedHeader;
+    _replicateIssuerAsHeader;
+    _replicateSubjectAsHeader;
+    _replicateAudienceAsHeader;
+    setProtectedHeader(protectedHeader) {
+        if (this._protectedHeader) {
+            throw new TypeError('setProtectedHeader can only be called once');
         }
-        return addCommas(new jsbn_1.BigInteger('2', 10).pow(subnetPowers).toString(10));
+        this._protectedHeader = protectedHeader;
+        return this;
     }
-    /**
-     * Helper function getting start address.
-     * @memberof Address6
-     * @instance
-     * @returns {BigInteger}
-     */
-    _startAddress() {
-        return new jsbn_1.BigInteger(this.mask() + '0'.repeat(constants6.BITS - this.subnetMask), 2);
+    setKeyManagementParameters(parameters) {
+        if (this._keyManagementParameters) {
+            throw new TypeError('setKeyManagementParameters can only be called once');
+        }
+        this._keyManagementParameters = parameters;
+        return this;
     }
-    /**
-     * The first address in the range given by this address' subnet
-     * Often referred to as the Network Address.
-     * @memberof Address6
-     * @instance
-     * @returns {Address6}
-     */
-    startAddress() {
-        return Address6.fromBigInteger(this._startAddress());
+    setContentEncryptionKey(cek) {
+        if (this._cek) {
+            throw new TypeError('setContentEncryptionKey can only be called once');
+        }
+        this._cek = cek;
+        return this;
     }
-    /**
-     * The first host address in the range given by this address's subnet ie
-     * the first address after the Network Address
-     * @memberof Address6
-     * @instance
-     * @returns {Address6}
-     */
-    startAddressExclusive() {
-        const adjust = new jsbn_1.BigInteger('1');
-        return Address6.fromBigInteger(this._startAddress().add(adjust));
+    setInitializationVector(iv) {
+        if (this._iv) {
+            throw new TypeError('setInitializationVector can only be called once');
+        }
+        this._iv = iv;
+        return this;
     }
-    /**
-     * Helper function getting end address.
-     * @memberof Address6
-     * @instance
-     * @returns {BigInteger}
-     */
-    _endAddress() {
-        return new jsbn_1.BigInteger(this.mask() + '1'.repeat(constants6.BITS - this.subnetMask), 2);
+    replicateIssuerAsHeader() {
+        this._replicateIssuerAsHeader = true;
+        return this;
     }
-    /**
-     * The last address in the range given by this address' subnet
-     * Often referred to as the Broadcast
-     * @memberof Address6
-     * @instance
-     * @returns {Address6}
-     */
-    endAddress() {
-        return Address6.fromBigInteger(this._endAddress());
+    replicateSubjectAsHeader() {
+        this._replicateSubjectAsHeader = true;
+        return this;
     }
-    /**
-     * The last host address in the range given by this address's subnet ie
-     * the last address prior to the Broadcast Address
-     * @memberof Address6
-     * @instance
-     * @returns {Address6}
-     */
-    endAddressExclusive() {
-        const adjust = new jsbn_1.BigInteger('1');
-        return Address6.fromBigInteger(this._endAddress().subtract(adjust));
+    replicateAudienceAsHeader() {
+        this._replicateAudienceAsHeader = true;
+        return this;
     }
-    /**
-     * Return the scope of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    getScope() {
-        let scope = constants6.SCOPES[this.getBits(12, 16).intValue()];
-        if (this.getType() === 'Global unicast' && scope !== 'Link local') {
-            scope = 'Global';
+    async encrypt(key, options) {
+        const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
+        if (this._replicateIssuerAsHeader) {
+            this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };
         }
-        return scope || 'Unknown';
+        if (this._replicateSubjectAsHeader) {
+            this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };
+        }
+        if (this._replicateAudienceAsHeader) {
+            this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };
+        }
+        enc.setProtectedHeader(this._protectedHeader);
+        if (this._iv) {
+            enc.setInitializationVector(this._iv);
+        }
+        if (this._cek) {
+            enc.setContentEncryptionKey(this._cek);
+        }
+        if (this._keyManagementParameters) {
+            enc.setKeyManagementParameters(this._keyManagementParameters);
+        }
+        return enc.encrypt(key, options);
     }
-    /**
-     * Return the type of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    getType() {
-        for (const subnet of Object.keys(constants6.TYPES)) {
-            if (this.isInSubnet(new Address6(subnet))) {
-                return constants6.TYPES[subnet];
-            }
+}
+exports.EncryptJWT = EncryptJWT;
+
+
+/***/ }),
+
+/***/ 37318:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ProduceJWT = void 0;
+const epoch_js_1 = __nccwpck_require__(40485);
+const is_object_js_1 = __nccwpck_require__(92242);
+const secs_js_1 = __nccwpck_require__(40556);
+function validateInput(label, input) {
+    if (!Number.isFinite(input)) {
+        throw new TypeError(`Invalid ${label} input`);
+    }
+    return input;
+}
+class ProduceJWT {
+    _payload;
+    constructor(payload = {}) {
+        if (!(0, is_object_js_1.default)(payload)) {
+            throw new TypeError('JWT Claims Set MUST be an object');
         }
-        return 'Global unicast';
+        this._payload = payload;
     }
-    /**
-     * Return the bits in the given range as a BigInteger
-     * @memberof Address6
-     * @instance
-     * @returns {BigInteger}
-     */
-    getBits(start, end) {
-        return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2);
+    setIssuer(issuer) {
+        this._payload = { ...this._payload, iss: issuer };
+        return this;
     }
-    /**
-     * Return the bits in the given range as a base-2 string
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    getBitsBase2(start, end) {
-        return this.binaryZeroPad().slice(start, end);
+    setSubject(subject) {
+        this._payload = { ...this._payload, sub: subject };
+        return this;
     }
-    /**
-     * Return the bits in the given range as a base-16 string
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    getBitsBase16(start, end) {
-        const length = end - start;
-        if (length % 4 !== 0) {
-            throw new Error('Length of bits to retrieve must be divisible by four');
+    setAudience(audience) {
+        this._payload = { ...this._payload, aud: audience };
+        return this;
+    }
+    setJti(jwtId) {
+        this._payload = { ...this._payload, jti: jwtId };
+        return this;
+    }
+    setNotBefore(input) {
+        if (typeof input === 'number') {
+            this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
         }
-        return this.getBits(start, end)
-            .toString(16)
-            .padStart(length / 4, '0');
+        else if (input instanceof Date) {
+            this._payload = { ...this._payload, nbf: validateInput('setNotBefore', (0, epoch_js_1.default)(input)) };
+        }
+        else {
+            this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) };
+        }
+        return this;
     }
-    /**
-     * Return the bits that are set past the subnet mask length
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    getBitsPastSubnet() {
-        return this.getBitsBase2(this.subnetMask, constants6.BITS);
+    setExpirationTime(input) {
+        if (typeof input === 'number') {
+            this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
+        }
+        else if (input instanceof Date) {
+            this._payload = { ...this._payload, exp: validateInput('setExpirationTime', (0, epoch_js_1.default)(input)) };
+        }
+        else {
+            this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) };
+        }
+        return this;
     }
-    /**
-     * Return the reversed ip6.arpa form of the address
-     * @memberof Address6
-     * @param {Object} options
-     * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
-     * @instance
-     * @returns {String}
-     */
-    reverseForm(options) {
-        if (!options) {
-            options = {};
+    setIssuedAt(input) {
+        if (typeof input === 'undefined') {
+            this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) };
         }
-        const characters = Math.floor(this.subnetMask / 4);
-        const reversed = this.canonicalForm()
-            .replace(/:/g, '')
-            .split('')
-            .slice(0, characters)
-            .reverse()
-            .join('.');
-        if (characters > 0) {
-            if (options.omitSuffix) {
-                return reversed;
-            }
-            return (0, sprintf_js_1.sprintf)('%s.ip6.arpa.', reversed);
+        else if (input instanceof Date) {
+            this._payload = { ...this._payload, iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(input)) };
         }
-        if (options.omitSuffix) {
-            return '';
+        else if (typeof input === 'string') {
+            this._payload = {
+                ...this._payload,
+                iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input)),
+            };
         }
-        return 'ip6.arpa.';
+        else {
+            this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
+        }
+        return this;
     }
-    /**
-     * Return the correct form of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    correctForm() {
-        let i;
-        let groups = [];
-        let zeroCounter = 0;
-        const zeroes = [];
-        for (i = 0; i < this.parsedAddress.length; i++) {
-            const value = parseInt(this.parsedAddress[i], 16);
-            if (value === 0) {
-                zeroCounter++;
-            }
-            if (value !== 0 && zeroCounter > 0) {
-                if (zeroCounter > 1) {
-                    zeroes.push([i - zeroCounter, i - 1]);
-                }
-                zeroCounter = 0;
-            }
+}
+exports.ProduceJWT = ProduceJWT;
+
+
+/***/ }),
+
+/***/ 22713:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SignJWT = void 0;
+const sign_js_1 = __nccwpck_require__(21760);
+const errors_js_1 = __nccwpck_require__(15974);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const produce_js_1 = __nccwpck_require__(37318);
+class SignJWT extends produce_js_1.ProduceJWT {
+    _protectedHeader;
+    setProtectedHeader(protectedHeader) {
+        this._protectedHeader = protectedHeader;
+        return this;
+    }
+    async sign(key, options) {
+        const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
+        sig.setProtectedHeader(this._protectedHeader);
+        if (Array.isArray(this._protectedHeader?.crit) &&
+            this._protectedHeader.crit.includes('b64') &&
+            this._protectedHeader.b64 === false) {
+            throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload');
         }
-        // Do we end with a string of zeroes?
-        if (zeroCounter > 1) {
-            zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
+        return sig.sign(key, options);
+    }
+}
+exports.SignJWT = SignJWT;
+
+
+/***/ }),
+
+/***/ 40560:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.UnsecuredJWT = void 0;
+const base64url = __nccwpck_require__(12635);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const errors_js_1 = __nccwpck_require__(15974);
+const jwt_claims_set_js_1 = __nccwpck_require__(13354);
+const produce_js_1 = __nccwpck_require__(37318);
+class UnsecuredJWT extends produce_js_1.ProduceJWT {
+    encode() {
+        const header = base64url.encode(JSON.stringify({ alg: 'none' }));
+        const payload = base64url.encode(JSON.stringify(this._payload));
+        return `${header}.${payload}.`;
+    }
+    static decode(jwt, options) {
+        if (typeof jwt !== 'string') {
+            throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string');
         }
-        const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
-        if (zeroes.length > 0) {
-            const index = zeroLengths.indexOf(Math.max(...zeroLengths));
-            groups = compact(this.parsedAddress, zeroes[index]);
+        const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');
+        if (length !== 3 || signature !== '') {
+            throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT');
         }
-        else {
-            groups = this.parsedAddress;
+        let header;
+        try {
+            header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader)));
+            if (header.alg !== 'none')
+                throw new Error();
         }
-        for (i = 0; i < groups.length; i++) {
-            if (groups[i] !== 'compact') {
-                groups[i] = parseInt(groups[i], 16).toString(16);
-            }
+        catch {
+            throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT');
         }
-        let correct = groups.join(':');
-        correct = correct.replace(/^compact$/, '::');
-        correct = correct.replace(/^compact|compact$/, ':');
-        correct = correct.replace(/compact/, '');
-        return correct;
+        const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options);
+        return { payload, header };
     }
-    /**
-     * Return a zero-padded base-2 string representation of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     * @example
-     * var address = new Address6('2001:4860:4001:803::1011');
-     * address.binaryZeroPad();
-     * // '0010000000000001010010000110000001000000000000010000100000000011
-     * //  0000000000000000000000000000000000000000000000000001000000010001'
-     */
-    binaryZeroPad() {
-        return this.bigInteger().toString(2).padStart(constants6.BITS, '0');
+}
+exports.UnsecuredJWT = UnsecuredJWT;
+
+
+/***/ }),
+
+/***/ 35297:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.jwtVerify = jwtVerify;
+const verify_js_1 = __nccwpck_require__(94212);
+const jwt_claims_set_js_1 = __nccwpck_require__(13354);
+const errors_js_1 = __nccwpck_require__(15974);
+async function jwtVerify(jwt, key, options) {
+    const verified = await (0, verify_js_1.compactVerify)(jwt, key, options);
+    if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
+        throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload');
     }
-    // TODO: Improve the semantics of this helper function
-    parse4in6(address) {
-        const groups = address.split(':');
-        const lastGroup = groups.slice(-1)[0];
-        const address4 = lastGroup.match(constants4.RE_ADDRESS);
-        if (address4) {
-            this.parsedAddress4 = address4[0];
-            this.address4 = new ipv4_1.Address4(this.parsedAddress4);
-            for (let i = 0; i < this.address4.groups; i++) {
-                if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
-                    throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join('.')));
-                }
-            }
-            this.v4 = true;
-            groups[groups.length - 1] = this.address4.toGroup6();
-            address = groups.join(':');
-        }
-        return address;
+    const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options);
+    const result = { payload, protectedHeader: verified.protectedHeader };
+    if (typeof key === 'function') {
+        return { ...result, key: verified.key };
     }
-    // TODO: Make private?
-    parse(address) {
-        address = this.parse4in6(address);
-        const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
-        if (badCharacters) {
-            throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Bad character%s detected in address: %s', badCharacters.length > 1 ? 's' : '', badCharacters.join('')), address.replace(constants6.RE_BAD_CHARACTERS, '$1'));
-        }
-        const badAddress = address.match(constants6.RE_BAD_ADDRESS);
-        if (badAddress) {
-            throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)('Address failed regex: %s', badAddress.join('')), address.replace(constants6.RE_BAD_ADDRESS, '$1'));
-        }
-        let groups = [];
-        const halves = address.split('::');
-        if (halves.length === 2) {
-            let first = halves[0].split(':');
-            let last = halves[1].split(':');
-            if (first.length === 1 && first[0] === '') {
-                first = [];
-            }
-            if (last.length === 1 && last[0] === '') {
-                last = [];
-            }
-            const remaining = this.groups - (first.length + last.length);
-            if (!remaining) {
-                throw new address_error_1.AddressError('Error parsing groups');
+    return result;
+}
+
+
+/***/ }),
+
+/***/ 48108:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exportSPKI = exportSPKI;
+exports.exportPKCS8 = exportPKCS8;
+exports.exportJWK = exportJWK;
+const asn1_js_1 = __nccwpck_require__(12774);
+const asn1_js_2 = __nccwpck_require__(12774);
+const key_to_jwk_js_1 = __nccwpck_require__(9041);
+async function exportSPKI(key) {
+    return (0, asn1_js_1.toSPKI)(key);
+}
+async function exportPKCS8(key) {
+    return (0, asn1_js_2.toPKCS8)(key);
+}
+async function exportJWK(key) {
+    return (0, key_to_jwk_js_1.default)(key);
+}
+
+
+/***/ }),
+
+/***/ 87820:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.generateKeyPair = generateKeyPair;
+const generate_js_1 = __nccwpck_require__(10088);
+async function generateKeyPair(alg, options) {
+    return (0, generate_js_1.generateKeyPair)(alg, options);
+}
+
+
+/***/ }),
+
+/***/ 37152:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.generateSecret = generateSecret;
+const generate_js_1 = __nccwpck_require__(10088);
+async function generateSecret(alg, options) {
+    return (0, generate_js_1.generateSecret)(alg, options);
+}
+
+
+/***/ }),
+
+/***/ 45647:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.importSPKI = importSPKI;
+exports.importX509 = importX509;
+exports.importPKCS8 = importPKCS8;
+exports.importJWK = importJWK;
+const base64url_js_1 = __nccwpck_require__(12635);
+const asn1_js_1 = __nccwpck_require__(12774);
+const jwk_to_key_js_1 = __nccwpck_require__(80939);
+const errors_js_1 = __nccwpck_require__(15974);
+const is_object_js_1 = __nccwpck_require__(92242);
+async function importSPKI(spki, alg, options) {
+    if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
+        throw new TypeError('"spki" must be SPKI formatted string');
+    }
+    return (0, asn1_js_1.fromSPKI)(spki, alg, options);
+}
+async function importX509(x509, alg, options) {
+    if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {
+        throw new TypeError('"x509" must be X.509 formatted string');
+    }
+    return (0, asn1_js_1.fromX509)(x509, alg, options);
+}
+async function importPKCS8(pkcs8, alg, options) {
+    if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {
+        throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
+    }
+    return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options);
+}
+async function importJWK(jwk, alg) {
+    if (!(0, is_object_js_1.default)(jwk)) {
+        throw new TypeError('JWK must be an object');
+    }
+    alg ||= jwk.alg;
+    switch (jwk.kty) {
+        case 'oct':
+            if (typeof jwk.k !== 'string' || !jwk.k) {
+                throw new TypeError('missing "k" (Key Value) Parameter value');
             }
-            this.elidedGroups = remaining;
-            this.elisionBegin = first.length;
-            this.elisionEnd = first.length + this.elidedGroups;
-            groups = groups.concat(first);
-            for (let i = 0; i < remaining; i++) {
-                groups.push('0');
+            return (0, base64url_js_1.decode)(jwk.k);
+        case 'RSA':
+            if (jwk.oth !== undefined) {
+                throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
             }
-            groups = groups.concat(last);
-        }
-        else if (halves.length === 1) {
-            groups = address.split(':');
-            this.elidedGroups = 0;
-        }
-        else {
-            throw new address_error_1.AddressError('Too many :: groups found');
-        }
-        groups = groups.map((group) => (0, sprintf_js_1.sprintf)('%x', parseInt(group, 16)));
-        if (groups.length !== this.groups) {
-            throw new address_error_1.AddressError('Incorrect number of groups found');
-        }
-        return groups;
+        case 'EC':
+        case 'OKP':
+            return (0, jwk_to_key_js_1.default)({ ...jwk, alg });
+        default:
+            throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
     }
-    /**
-     * Return the canonical form of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    canonicalForm() {
-        return this.parsedAddress.map(paddedHex).join(':');
+}
+
+
+/***/ }),
+
+/***/ 95864:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.wrap = wrap;
+exports.unwrap = unwrap;
+const encrypt_js_1 = __nccwpck_require__(36286);
+const decrypt_js_1 = __nccwpck_require__(52806);
+const base64url_js_1 = __nccwpck_require__(12635);
+async function wrap(alg, key, cek, iv) {
+    const jweAlgorithm = alg.slice(0, 7);
+    const wrapped = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0));
+    return {
+        encryptedKey: wrapped.ciphertext,
+        iv: (0, base64url_js_1.encode)(wrapped.iv),
+        tag: (0, base64url_js_1.encode)(wrapped.tag),
+    };
+}
+async function unwrap(alg, key, encryptedKey, iv, tag) {
+    const jweAlgorithm = alg.slice(0, 7);
+    return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));
+}
+
+
+/***/ }),
+
+/***/ 45734:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decoder = exports.encoder = void 0;
+exports.concat = concat;
+exports.p2s = p2s;
+exports.uint64be = uint64be;
+exports.uint32be = uint32be;
+exports.lengthAndInput = lengthAndInput;
+exports.concatKdf = concatKdf;
+const digest_js_1 = __nccwpck_require__(12931);
+exports.encoder = new TextEncoder();
+exports.decoder = new TextDecoder();
+const MAX_INT32 = 2 ** 32;
+function concat(...buffers) {
+    const size = buffers.reduce((acc, { length }) => acc + length, 0);
+    const buf = new Uint8Array(size);
+    let i = 0;
+    for (const buffer of buffers) {
+        buf.set(buffer, i);
+        i += buffer.length;
     }
-    /**
-     * Return the decimal form of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    decimal() {
-        return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)('%05d', parseInt(n, 16))).join(':');
+    return buf;
+}
+function p2s(alg, p2sInput) {
+    return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput);
+}
+function writeUInt32BE(buf, value, offset) {
+    if (value < 0 || value >= MAX_INT32) {
+        throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
     }
-    /**
-     * Return the address as a BigInteger
-     * @memberof Address6
-     * @instance
-     * @returns {BigInteger}
-     */
-    bigInteger() {
-        return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(''), 16);
+    buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);
+}
+function uint64be(value) {
+    const high = Math.floor(value / MAX_INT32);
+    const low = value % MAX_INT32;
+    const buf = new Uint8Array(8);
+    writeUInt32BE(buf, high, 0);
+    writeUInt32BE(buf, low, 4);
+    return buf;
+}
+function uint32be(value) {
+    const buf = new Uint8Array(4);
+    writeUInt32BE(buf, value);
+    return buf;
+}
+function lengthAndInput(input) {
+    return concat(uint32be(input.length), input);
+}
+async function concatKdf(secret, bits, value) {
+    const iterations = Math.ceil((bits >> 3) / 32);
+    const res = new Uint8Array(iterations * 32);
+    for (let iter = 0; iter < iterations; iter++) {
+        const buf = new Uint8Array(4 + secret.length + value.length);
+        buf.set(uint32be(iter + 1));
+        buf.set(secret, 4);
+        buf.set(value, 4 + secret.length);
+        res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32);
     }
-    /**
-     * Return the last two groups of this address as an IPv4 address string
-     * @memberof Address6
-     * @instance
-     * @returns {Address4}
-     * @example
-     * var address = new Address6('2001:4860:4001::1825:bf11');
-     * address.to4().correctForm(); // '24.37.191.17'
-     */
-    to4() {
-        const binary = this.binaryZeroPad().split('');
-        return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(''), 2).toString(16));
+    return res.slice(0, bits >> 3);
+}
+
+
+/***/ }),
+
+/***/ 87937:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.bitLength = bitLength;
+const errors_js_1 = __nccwpck_require__(15974);
+const random_js_1 = __nccwpck_require__(23376);
+function bitLength(alg) {
+    switch (alg) {
+        case 'A128GCM':
+            return 128;
+        case 'A192GCM':
+            return 192;
+        case 'A256GCM':
+        case 'A128CBC-HS256':
+            return 256;
+        case 'A192CBC-HS384':
+            return 384;
+        case 'A256CBC-HS512':
+            return 512;
+        default:
+            throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
     }
-    /**
-     * Return the v4-in-v6 form of the address
-     * @memberof Address6
-     * @instance
-     * @returns {String}
-     */
-    to4in6() {
-        const address4 = this.to4();
-        const address6 = new Address6(this.parsedAddress.slice(0, 6).join(':'), 6);
-        const correct = address6.correctForm();
-        let infix = '';
-        if (!/:$/.test(correct)) {
-            infix = ':';
-        }
-        return correct + infix + address4.address;
+}
+exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3));
+
+
+/***/ }),
+
+/***/ 63351:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const errors_js_1 = __nccwpck_require__(15974);
+const iv_js_1 = __nccwpck_require__(56565);
+const checkIvLength = (enc, iv) => {
+    if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) {
+        throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length');
     }
-    /**
-     * Return an object containing the Teredo properties of the address
-     * @memberof Address6
-     * @instance
-     * @returns {Object}
-     */
-    inspectTeredo() {
-        /*
-        - Bits 0 to 31 are set to the Teredo prefix (normally 2001:0000::/32).
-        - Bits 32 to 63 embed the primary IPv4 address of the Teredo server that
-          is used.
-        - Bits 64 to 79 can be used to define some flags. Currently only the
-          higher order bit is used; it is set to 1 if the Teredo client is
-          located behind a cone NAT, 0 otherwise. For Microsoft's Windows Vista
-          and Windows Server 2008 implementations, more bits are used. In those
-          implementations, the format for these 16 bits is "CRAAAAUG AAAAAAAA",
-          where "C" remains the "Cone" flag. The "R" bit is reserved for future
-          use. The "U" bit is for the Universal/Local flag (set to 0). The "G" bit
-          is Individual/Group flag (set to 0). The A bits are set to a 12-bit
-          randomly generated number chosen by the Teredo client to introduce
-          additional protection for the Teredo node against IPv6-based scanning
-          attacks.
-        - Bits 80 to 95 contains the obfuscated UDP port number. This is the
-          port number that is mapped by the NAT to the Teredo client with all
-          bits inverted.
-        - Bits 96 to 127 contains the obfuscated IPv4 address. This is the
-          public IPv4 address of the NAT with all bits inverted.
-        */
-        const prefix = this.getBitsBase16(0, 32);
-        const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger('ffff', 16)).toString();
-        const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
-        const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger('ffffffff', 16)).toString(16));
-        const flags = this.getBits(64, 80);
-        const flagsBase2 = this.getBitsBase2(64, 80);
-        const coneNat = flags.testBit(15);
-        const reserved = flags.testBit(14);
-        const groupIndividual = flags.testBit(8);
-        const universalLocal = flags.testBit(9);
-        const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10);
-        return {
-            prefix: (0, sprintf_js_1.sprintf)('%s:%s', prefix.slice(0, 4), prefix.slice(4, 8)),
-            server4: server4.address,
-            client4: client4.address,
-            flags: flagsBase2,
-            coneNat,
-            microsoft: {
-                reserved,
-                universalLocal,
-                groupIndividual,
-                nonce,
-            },
-            udpPort,
-        };
+};
+exports["default"] = checkIvLength;
+
+
+/***/ }),
+
+/***/ 29555:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.checkKeyTypeWithJwk = void 0;
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const jwk = __nccwpck_require__(91229);
+const tag = (key) => key?.[Symbol.toStringTag];
+const jwkMatchesOp = (alg, key, usage) => {
+    if (key.use !== undefined && key.use !== 'sig') {
+        throw new TypeError('Invalid key for this operation, when present its use must be sig');
     }
-    /**
-     * Return an object containing the 6to4 properties of the address
-     * @memberof Address6
-     * @instance
-     * @returns {Object}
-     */
-    inspect6to4() {
-        /*
-        - Bits 0 to 15 are set to the 6to4 prefix (2002::/16).
-        - Bits 16 to 48 embed the IPv4 address of the 6to4 gateway that is used.
-        */
-        const prefix = this.getBitsBase16(0, 16);
-        const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
-        return {
-            prefix: (0, sprintf_js_1.sprintf)('%s', prefix.slice(0, 4)),
-            gateway: gateway.address,
-        };
+    if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {
+        throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);
     }
-    /**
-     * Return a v6 6to4 address from a v6 v4inv6 address
-     * @memberof Address6
-     * @instance
-     * @returns {Address6}
-     */
-    to6to4() {
-        if (!this.is4()) {
-            return null;
-        }
-        const addr6to4 = [
-            '2002',
-            this.getBitsBase16(96, 112),
-            this.getBitsBase16(112, 128),
-            '',
-            '/16',
-        ].join(':');
-        return new Address6(addr6to4);
+    if (key.alg !== undefined && key.alg !== alg) {
+        throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);
     }
-    /**
-     * Return a byte array
-     * @memberof Address6
-     * @instance
-     * @returns {Array}
-     */
-    toByteArray() {
-        const byteArray = this.bigInteger().toByteArray();
-        // work around issue where `toByteArray` returns a leading 0 element
-        if (byteArray.length === 17 && byteArray[0] === 0) {
-            return byteArray.slice(1);
-        }
-        return byteArray;
+    return true;
+};
+const symmetricTypeCheck = (alg, key, usage, allowJwk) => {
+    if (key instanceof Uint8Array)
+        return;
+    if (allowJwk && jwk.isJWK(key)) {
+        if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
+            return;
+        throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
     }
-    /**
-     * Return an unsigned byte array
-     * @memberof Address6
-     * @instance
-     * @returns {Array}
-     */
-    toUnsignedByteArray() {
-        return this.toByteArray().map(unsignByte);
+    if (!(0, is_key_like_js_1.default)(key)) {
+        throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));
     }
-    /**
-     * Convert a byte array to an Address6 object
-     * @memberof Address6
-     * @static
-     * @returns {Address6}
-     */
-    static fromByteArray(bytes) {
-        return this.fromUnsignedByteArray(bytes.map(unsignByte));
+    if (key.type !== 'secret') {
+        throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
     }
-    /**
-     * Convert an unsigned byte array to an Address6 object
-     * @memberof Address6
-     * @static
-     * @returns {Address6}
-     */
-    static fromUnsignedByteArray(bytes) {
-        const BYTE_MAX = new jsbn_1.BigInteger('256', 10);
-        let result = new jsbn_1.BigInteger('0', 10);
-        let multiplier = new jsbn_1.BigInteger('1', 10);
-        for (let i = bytes.length - 1; i >= 0; i--) {
-            result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10)));
-            multiplier = multiplier.multiply(BYTE_MAX);
+};
+const asymmetricTypeCheck = (alg, key, usage, allowJwk) => {
+    if (allowJwk && jwk.isJWK(key)) {
+        switch (usage) {
+            case 'sign':
+                if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
+                    return;
+                throw new TypeError(`JSON Web Key for this operation be a private JWK`);
+            case 'verify':
+                if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
+                    return;
+                throw new TypeError(`JSON Web Key for this operation be a public JWK`);
         }
-        return Address6.fromBigInteger(result);
     }
-    /**
-     * Returns true if the address is in the canonical form, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    isCanonical() {
-        return this.addressMinusSuffix === this.canonicalForm();
+    if (!(0, is_key_like_js_1.default)(key)) {
+        throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, allowJwk ? 'JSON Web Key' : null));
     }
-    /**
-     * Returns true if the address is a link local address, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    isLinkLocal() {
-        // Zeroes are required, i.e. we can't check isInSubnet with 'fe80::/10'
-        if (this.getBitsBase2(0, 64) ===
-            '1111111010000000000000000000000000000000000000000000000000000000') {
-            return true;
-        }
-        return false;
+    if (key.type === 'secret') {
+        throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
     }
-    /**
-     * Returns true if the address is a multicast address, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    isMulticast() {
-        return this.getType() === 'Multicast';
+    if (usage === 'sign' && key.type === 'public') {
+        throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
     }
-    /**
-     * Returns true if the address is a v4-in-v6 address, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    is4() {
-        return this.v4;
+    if (usage === 'decrypt' && key.type === 'public') {
+        throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
     }
-    /**
-     * Returns true if the address is a Teredo address, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    isTeredo() {
-        return this.isInSubnet(new Address6('2001::/32'));
+    if (key.algorithm && usage === 'verify' && key.type === 'private') {
+        throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
     }
-    /**
-     * Returns true if the address is a 6to4 address, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    is6to4() {
-        return this.isInSubnet(new Address6('2002::/16'));
+    if (key.algorithm && usage === 'encrypt' && key.type === 'private') {
+        throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
     }
-    /**
-     * Returns true if the address is a loopback address, false otherwise
-     * @memberof Address6
-     * @instance
-     * @returns {boolean}
-     */
-    isLoopback() {
-        return this.getType() === 'Loopback';
+};
+function checkKeyType(allowJwk, alg, key, usage) {
+    const symmetric = alg.startsWith('HS') ||
+        alg === 'dir' ||
+        alg.startsWith('PBES2') ||
+        /^A\d{3}(?:GCM)?KW$/.test(alg);
+    if (symmetric) {
+        symmetricTypeCheck(alg, key, usage, allowJwk);
     }
-    // #endregion
-    // #region HTML
-    /**
-     * @returns {String} the address in link form with a default port of 80
-     */
-    href(optionalPort) {
-        if (optionalPort === undefined) {
-            optionalPort = '';
+    else {
+        asymmetricTypeCheck(alg, key, usage, allowJwk);
+    }
+}
+exports["default"] = checkKeyType.bind(undefined, false);
+exports.checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);
+
+
+/***/ }),
+
+/***/ 88040:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = checkP2s;
+const errors_js_1 = __nccwpck_require__(15974);
+function checkP2s(p2s) {
+    if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
+        throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets');
+    }
+}
+
+
+/***/ }),
+
+/***/ 26319:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.checkSigCryptoKey = checkSigCryptoKey;
+exports.checkEncCryptoKey = checkEncCryptoKey;
+function unusable(name, prop = 'algorithm.name') {
+    return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
+}
+function isAlgorithm(algorithm, name) {
+    return algorithm.name === name;
+}
+function getHashLength(hash) {
+    return parseInt(hash.name.slice(4), 10);
+}
+function getNamedCurve(alg) {
+    switch (alg) {
+        case 'ES256':
+            return 'P-256';
+        case 'ES384':
+            return 'P-384';
+        case 'ES512':
+            return 'P-521';
+        default:
+            throw new Error('unreachable');
+    }
+}
+function checkUsage(key, usages) {
+    if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
+        let msg = 'CryptoKey does not support this operation, its usages must include ';
+        if (usages.length > 2) {
+            const last = usages.pop();
+            msg += `one of ${usages.join(', ')}, or ${last}.`;
+        }
+        else if (usages.length === 2) {
+            msg += `one of ${usages[0]} or ${usages[1]}.`;
         }
         else {
-            optionalPort = (0, sprintf_js_1.sprintf)(':%s', optionalPort);
+            msg += `${usages[0]}.`;
         }
-        return (0, sprintf_js_1.sprintf)('http://[%s]%s/', this.correctForm(), optionalPort);
+        throw new TypeError(msg);
     }
-    /**
-     * @returns {String} a link suitable for conveying the address via a URL hash
-     */
-    link(options) {
-        if (!options) {
-            options = {};
-        }
-        if (options.className === undefined) {
-            options.className = '';
+}
+function checkSigCryptoKey(key, alg, ...usages) {
+    switch (alg) {
+        case 'HS256':
+        case 'HS384':
+        case 'HS512': {
+            if (!isAlgorithm(key.algorithm, 'HMAC'))
+                throw unusable('HMAC');
+            const expected = parseInt(alg.slice(2), 10);
+            const actual = getHashLength(key.algorithm.hash);
+            if (actual !== expected)
+                throw unusable(`SHA-${expected}`, 'algorithm.hash');
+            break;
         }
-        if (options.prefix === undefined) {
-            options.prefix = '/#address=';
+        case 'RS256':
+        case 'RS384':
+        case 'RS512': {
+            if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
+                throw unusable('RSASSA-PKCS1-v1_5');
+            const expected = parseInt(alg.slice(2), 10);
+            const actual = getHashLength(key.algorithm.hash);
+            if (actual !== expected)
+                throw unusable(`SHA-${expected}`, 'algorithm.hash');
+            break;
         }
-        if (options.v4 === undefined) {
-            options.v4 = false;
+        case 'PS256':
+        case 'PS384':
+        case 'PS512': {
+            if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
+                throw unusable('RSA-PSS');
+            const expected = parseInt(alg.slice(2), 10);
+            const actual = getHashLength(key.algorithm.hash);
+            if (actual !== expected)
+                throw unusable(`SHA-${expected}`, 'algorithm.hash');
+            break;
         }
-        let formFunction = this.correctForm;
-        if (options.v4) {
-            formFunction = this.to4in6;
+        case 'EdDSA': {
+            if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
+                throw unusable('Ed25519 or Ed448');
+            }
+            break;
         }
-        if (options.className) {
-            return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this), options.className);
+        case 'ES256':
+        case 'ES384':
+        case 'ES512': {
+            if (!isAlgorithm(key.algorithm, 'ECDSA'))
+                throw unusable('ECDSA');
+            const expected = getNamedCurve(alg);
+            const actual = key.algorithm.namedCurve;
+            if (actual !== expected)
+                throw unusable(expected, 'algorithm.namedCurve');
+            break;
         }
-        return (0, sprintf_js_1.sprintf)('%2$s', options.prefix, formFunction.call(this));
+        default:
+            throw new TypeError('CryptoKey does not support this operation');
     }
-    /**
-     * Groups an address
-     * @returns {String}
-     */
-    group() {
-        if (this.elidedGroups === 0) {
-            // The simple case
-            return helpers.simpleGroup(this.address).join(':');
-        }
-        assert(typeof this.elidedGroups === 'number');
-        assert(typeof this.elisionBegin === 'number');
-        // The elided case
-        const output = [];
-        const [left, right] = this.address.split('::');
-        if (left.length) {
-            output.push(...helpers.simpleGroup(left));
-        }
-        else {
-            output.push('');
-        }
-        const classes = ['hover-group'];
-        for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
-            classes.push((0, sprintf_js_1.sprintf)('group-%d', i));
+    checkUsage(key, usages);
+}
+function checkEncCryptoKey(key, alg, ...usages) {
+    switch (alg) {
+        case 'A128GCM':
+        case 'A192GCM':
+        case 'A256GCM': {
+            if (!isAlgorithm(key.algorithm, 'AES-GCM'))
+                throw unusable('AES-GCM');
+            const expected = parseInt(alg.slice(1, 4), 10);
+            const actual = key.algorithm.length;
+            if (actual !== expected)
+                throw unusable(expected, 'algorithm.length');
+            break;
         }
-        output.push((0, sprintf_js_1.sprintf)('', classes.join(' ')));
-        if (right.length) {
-            output.push(...helpers.simpleGroup(right, this.elisionEnd));
+        case 'A128KW':
+        case 'A192KW':
+        case 'A256KW': {
+            if (!isAlgorithm(key.algorithm, 'AES-KW'))
+                throw unusable('AES-KW');
+            const expected = parseInt(alg.slice(1, 4), 10);
+            const actual = key.algorithm.length;
+            if (actual !== expected)
+                throw unusable(expected, 'algorithm.length');
+            break;
         }
-        else {
-            output.push('');
+        case 'ECDH': {
+            switch (key.algorithm.name) {
+                case 'ECDH':
+                case 'X25519':
+                case 'X448':
+                    break;
+                default:
+                    throw unusable('ECDH, X25519, or X448');
+            }
+            break;
         }
-        if (this.is4()) {
-            assert(this.address4 instanceof ipv4_1.Address4);
-            output.pop();
-            output.push(this.address4.groupForV6());
+        case 'PBES2-HS256+A128KW':
+        case 'PBES2-HS384+A192KW':
+        case 'PBES2-HS512+A256KW':
+            if (!isAlgorithm(key.algorithm, 'PBKDF2'))
+                throw unusable('PBKDF2');
+            break;
+        case 'RSA-OAEP':
+        case 'RSA-OAEP-256':
+        case 'RSA-OAEP-384':
+        case 'RSA-OAEP-512': {
+            if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))
+                throw unusable('RSA-OAEP');
+            const expected = parseInt(alg.slice(9), 10) || 1;
+            const actual = getHashLength(key.algorithm.hash);
+            if (actual !== expected)
+                throw unusable(`SHA-${expected}`, 'algorithm.hash');
+            break;
         }
-        return output.join(':');
+        default:
+            throw new TypeError('CryptoKey does not support this operation');
     }
-    // #endregion
-    // #region Regular expressions
-    /**
-     * Generate a regular expression string that can be used to find or validate
-     * all variations of this address
-     * @memberof Address6
-     * @instance
-     * @param {boolean} substringSearch
-     * @returns {string}
-     */
-    regularExpressionString(substringSearch = false) {
-        let output = [];
-        // TODO: revisit why this is necessary
-        const address6 = new Address6(this.correctForm());
-        if (address6.elidedGroups === 0) {
-            // The simple case
-            output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
+    checkUsage(key, usages);
+}
+
+
+/***/ }),
+
+/***/ 56243:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const aeskw_js_1 = __nccwpck_require__(76202);
+const ECDH = __nccwpck_require__(43359);
+const pbes2kw_js_1 = __nccwpck_require__(52741);
+const rsaes_js_1 = __nccwpck_require__(61129);
+const base64url_js_1 = __nccwpck_require__(12635);
+const normalize_key_js_1 = __nccwpck_require__(51276);
+const errors_js_1 = __nccwpck_require__(15974);
+const cek_js_1 = __nccwpck_require__(87937);
+const import_js_1 = __nccwpck_require__(45647);
+const check_key_type_js_1 = __nccwpck_require__(29555);
+const is_object_js_1 = __nccwpck_require__(92242);
+const aesgcmkw_js_1 = __nccwpck_require__(95864);
+async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
+    (0, check_key_type_js_1.default)(alg, key, 'decrypt');
+    key = (await normalize_key_js_1.default.normalizePrivateKey?.(key, alg)) || key;
+    switch (alg) {
+        case 'dir': {
+            if (encryptedKey !== undefined)
+                throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key');
+            return key;
+        }
+        case 'ECDH-ES':
+            if (encryptedKey !== undefined)
+                throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key');
+        case 'ECDH-ES+A128KW':
+        case 'ECDH-ES+A192KW':
+        case 'ECDH-ES+A256KW': {
+            if (!(0, is_object_js_1.default)(joseHeader.epk))
+                throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
+            if (!ECDH.ecdhAllowed(key))
+                throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
+            const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg);
+            let partyUInfo;
+            let partyVInfo;
+            if (joseHeader.apu !== undefined) {
+                if (typeof joseHeader.apu !== 'string')
+                    throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
+                try {
+                    partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu);
+                }
+                catch {
+                    throw new errors_js_1.JWEInvalid('Failed to base64url decode the apu');
+                }
+            }
+            if (joseHeader.apv !== undefined) {
+                if (typeof joseHeader.apv !== 'string')
+                    throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
+                try {
+                    partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv);
+                }
+                catch {
+                    throw new errors_js_1.JWEInvalid('Failed to base64url decode the apv');
+                }
+            }
+            const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
+            if (alg === 'ECDH-ES')
+                return sharedSecret;
+            if (encryptedKey === undefined)
+                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
+            return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey);
         }
-        else if (address6.elidedGroups === constants6.GROUPS) {
-            // A completely elided address
-            output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
+        case 'RSA1_5':
+        case 'RSA-OAEP':
+        case 'RSA-OAEP-256':
+        case 'RSA-OAEP-384':
+        case 'RSA-OAEP-512': {
+            if (encryptedKey === undefined)
+                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
+            return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey);
         }
-        else {
-            // A partially elided address
-            const halves = address6.address.split('::');
-            if (halves[0].length) {
-                output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(':')));
+        case 'PBES2-HS256+A128KW':
+        case 'PBES2-HS384+A192KW':
+        case 'PBES2-HS512+A256KW': {
+            if (encryptedKey === undefined)
+                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
+            if (typeof joseHeader.p2c !== 'number')
+                throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
+            const p2cLimit = options?.maxPBES2Count || 10_000;
+            if (joseHeader.p2c > p2cLimit)
+                throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
+            if (typeof joseHeader.p2s !== 'string')
+                throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
+            let p2s;
+            try {
+                p2s = (0, base64url_js_1.decode)(joseHeader.p2s);
             }
-            assert(typeof address6.elidedGroups === 'number');
-            output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
-            if (halves[1].length) {
-                output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(':')));
+            catch {
+                throw new errors_js_1.JWEInvalid('Failed to base64url decode the p2s');
             }
-            output = [output.join(':')];
+            return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s);
         }
-        if (!substringSearch) {
-            output = [
-                '(?=^|',
-                regular_expressions_1.ADDRESS_BOUNDARY,
-                '|[^\\w\\:])(',
-                ...output,
-                ')(?=[^\\w\\:]|',
-                regular_expressions_1.ADDRESS_BOUNDARY,
-                '|$)',
-            ];
+        case 'A128KW':
+        case 'A192KW':
+        case 'A256KW': {
+            if (encryptedKey === undefined)
+                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
+            return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey);
+        }
+        case 'A128GCMKW':
+        case 'A192GCMKW':
+        case 'A256GCMKW': {
+            if (encryptedKey === undefined)
+                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
+            if (typeof joseHeader.iv !== 'string')
+                throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
+            if (typeof joseHeader.tag !== 'string')
+                throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
+            let iv;
+            try {
+                iv = (0, base64url_js_1.decode)(joseHeader.iv);
+            }
+            catch {
+                throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv');
+            }
+            let tag;
+            try {
+                tag = (0, base64url_js_1.decode)(joseHeader.tag);
+            }
+            catch {
+                throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag');
+            }
+            return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag);
+        }
+        default: {
+            throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
         }
-        return output.join('');
-    }
-    /**
-     * Generate a regular expression that can be used to find or validate all
-     * variations of this address.
-     * @memberof Address6
-     * @instance
-     * @param {boolean} substringSearch
-     * @returns {RegExp}
-     */
-    regularExpression(substringSearch = false) {
-        return new RegExp(this.regularExpressionString(substringSearch), 'i');
     }
 }
-exports.Address6 = Address6;
-//# sourceMappingURL=ipv6.js.map
+exports["default"] = decryptKeyManagement;
+
 
 /***/ }),
 
-/***/ 66437:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 96539:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RE_SUBNET_STRING = exports.RE_ADDRESS = exports.GROUPS = exports.BITS = void 0;
-exports.BITS = 32;
-exports.GROUPS = 4;
-exports.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
-exports.RE_SUBNET_STRING = /\/\d{1,2}$/;
-//# sourceMappingURL=constants.js.map
+const aeskw_js_1 = __nccwpck_require__(76202);
+const ECDH = __nccwpck_require__(43359);
+const pbes2kw_js_1 = __nccwpck_require__(52741);
+const rsaes_js_1 = __nccwpck_require__(61129);
+const base64url_js_1 = __nccwpck_require__(12635);
+const normalize_key_js_1 = __nccwpck_require__(51276);
+const cek_js_1 = __nccwpck_require__(87937);
+const errors_js_1 = __nccwpck_require__(15974);
+const export_js_1 = __nccwpck_require__(48108);
+const check_key_type_js_1 = __nccwpck_require__(29555);
+const aesgcmkw_js_1 = __nccwpck_require__(95864);
+async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
+    let encryptedKey;
+    let parameters;
+    let cek;
+    (0, check_key_type_js_1.default)(alg, key, 'encrypt');
+    key = (await normalize_key_js_1.default.normalizePublicKey?.(key, alg)) || key;
+    switch (alg) {
+        case 'dir': {
+            cek = key;
+            break;
+        }
+        case 'ECDH-ES':
+        case 'ECDH-ES+A128KW':
+        case 'ECDH-ES+A192KW':
+        case 'ECDH-ES+A256KW': {
+            if (!ECDH.ecdhAllowed(key)) {
+                throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
+            }
+            const { apu, apv } = providedParameters;
+            let { epk: ephemeralKey } = providedParameters;
+            ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey;
+            const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey);
+            const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
+            parameters = { epk: { x, crv, kty } };
+            if (kty === 'EC')
+                parameters.epk.y = y;
+            if (apu)
+                parameters.apu = (0, base64url_js_1.encode)(apu);
+            if (apv)
+                parameters.apv = (0, base64url_js_1.encode)(apv);
+            if (alg === 'ECDH-ES') {
+                cek = sharedSecret;
+                break;
+            }
+            cek = providedCek || (0, cek_js_1.default)(enc);
+            const kwAlg = alg.slice(-6);
+            encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek);
+            break;
+        }
+        case 'RSA1_5':
+        case 'RSA-OAEP':
+        case 'RSA-OAEP-256':
+        case 'RSA-OAEP-384':
+        case 'RSA-OAEP-512': {
+            cek = providedCek || (0, cek_js_1.default)(enc);
+            encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek);
+            break;
+        }
+        case 'PBES2-HS256+A128KW':
+        case 'PBES2-HS384+A192KW':
+        case 'PBES2-HS512+A256KW': {
+            cek = providedCek || (0, cek_js_1.default)(enc);
+            const { p2c, p2s } = providedParameters;
+            ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s));
+            break;
+        }
+        case 'A128KW':
+        case 'A192KW':
+        case 'A256KW': {
+            cek = providedCek || (0, cek_js_1.default)(enc);
+            encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek);
+            break;
+        }
+        case 'A128GCMKW':
+        case 'A192GCMKW':
+        case 'A256GCMKW': {
+            cek = providedCek || (0, cek_js_1.default)(enc);
+            const { iv } = providedParameters;
+            ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv));
+            break;
+        }
+        default: {
+            throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+        }
+    }
+    return { cek, encryptedKey, parameters };
+}
+exports["default"] = encryptKeyManagement;
+
 
 /***/ }),
 
-/***/ 75280:
+/***/ 40485:
 /***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RE_URL_WITH_PORT = exports.RE_URL = exports.RE_ZONE_STRING = exports.RE_SUBNET_STRING = exports.RE_BAD_ADDRESS = exports.RE_BAD_CHARACTERS = exports.TYPES = exports.SCOPES = exports.GROUPS = exports.BITS = void 0;
-exports.BITS = 128;
-exports.GROUPS = 8;
-/**
- * Represents IPv6 address scopes
- * @memberof Address6
- * @static
- */
-exports.SCOPES = {
-    0: 'Reserved',
-    1: 'Interface local',
-    2: 'Link local',
-    4: 'Admin local',
-    5: 'Site local',
-    8: 'Organization local',
-    14: 'Global',
-    15: 'Reserved',
-};
-/**
- * Represents IPv6 address types
- * @memberof Address6
- * @static
- */
-exports.TYPES = {
-    'ff01::1/128': 'Multicast (All nodes on this interface)',
-    'ff01::2/128': 'Multicast (All routers on this interface)',
-    'ff02::1/128': 'Multicast (All nodes on this link)',
-    'ff02::2/128': 'Multicast (All routers on this link)',
-    'ff05::2/128': 'Multicast (All routers in this site)',
-    'ff02::5/128': 'Multicast (OSPFv3 AllSPF routers)',
-    'ff02::6/128': 'Multicast (OSPFv3 AllDR routers)',
-    'ff02::9/128': 'Multicast (RIP routers)',
-    'ff02::a/128': 'Multicast (EIGRP routers)',
-    'ff02::d/128': 'Multicast (PIM routers)',
-    'ff02::16/128': 'Multicast (MLDv2 reports)',
-    'ff01::fb/128': 'Multicast (mDNSv6)',
-    'ff02::fb/128': 'Multicast (mDNSv6)',
-    'ff05::fb/128': 'Multicast (mDNSv6)',
-    'ff02::1:2/128': 'Multicast (All DHCP servers and relay agents on this link)',
-    'ff05::1:2/128': 'Multicast (All DHCP servers and relay agents in this site)',
-    'ff02::1:3/128': 'Multicast (All DHCP servers on this link)',
-    'ff05::1:3/128': 'Multicast (All DHCP servers in this site)',
-    '::/128': 'Unspecified',
-    '::1/128': 'Loopback',
-    'ff00::/8': 'Multicast',
-    'fe80::/10': 'Link-local unicast',
-};
-/**
- * A regular expression that matches bad characters in an IPv6 address
- * @memberof Address6
- * @static
- */
-exports.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
-/**
- * A regular expression that matches an incorrect IPv6 address
- * @memberof Address6
- * @static
- */
-exports.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
-/**
- * A regular expression that matches an IPv6 subnet
- * @memberof Address6
- * @static
- */
-exports.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
-/**
- * A regular expression that matches an IPv6 zone
- * @memberof Address6
- * @static
- */
-exports.RE_ZONE_STRING = /%.*$/;
-exports.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/);
-exports.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
-//# sourceMappingURL=constants.js.map
-
-/***/ }),
-
-/***/ 20339:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+exports["default"] = (date) => Math.floor(date.getTime() / 1000);
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.simpleGroup = exports.spanLeadingZeroes = exports.spanAll = exports.spanAllZeroes = void 0;
-const sprintf_js_1 = __nccwpck_require__(19973);
-/**
- * @returns {String} the string with all zeroes contained in a 
- */
-function spanAllZeroes(s) {
-    return s.replace(/(0+)/g, '$1');
-}
-exports.spanAllZeroes = spanAllZeroes;
-/**
- * @returns {String} the string with each character contained in a 
- */
-function spanAll(s, offset = 0) {
-    const letters = s.split('');
-    return letters
-        .map((n, i) => (0, sprintf_js_1.sprintf)('%s', n, i + offset, spanAllZeroes(n)) // XXX Use #base-2 .value-0 instead?
-    )
-        .join('');
-}
-exports.spanAll = spanAll;
-function spanLeadingZeroesSimple(group) {
-    return group.replace(/^(0+)/, '$1');
-}
-/**
- * @returns {String} the string with leading zeroes contained in a 
- */
-function spanLeadingZeroes(address) {
-    const groups = address.split(':');
-    return groups.map((g) => spanLeadingZeroesSimple(g)).join(':');
-}
-exports.spanLeadingZeroes = spanLeadingZeroes;
-/**
- * Groups an address
- * @returns {String} a grouped address
- */
-function simpleGroup(addressString, offset = 0) {
-    const groups = addressString.split(':');
-    return groups.map((g, i) => {
-        if (/group-v4/.test(g)) {
-            return g;
-        }
-        return (0, sprintf_js_1.sprintf)('%s', i + offset, spanLeadingZeroesSimple(g));
-    });
-}
-exports.simpleGroup = simpleGroup;
-//# sourceMappingURL=helpers.js.map
 
 /***/ }),
 
-/***/ 72016:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 16632:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    var desc = Object.getOwnPropertyDescriptor(m, k);
-    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
-      desc = { enumerable: true, get: function() { return m[k]; } };
-    }
-    Object.defineProperty(o, k2, desc);
-}) : (function(o, m, k, k2) {
-    if (k2 === undefined) k2 = k;
-    o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
-    Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
-    o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.possibleElisions = exports.simpleRegularExpression = exports.ADDRESS_BOUNDARY = exports.padGroup = exports.groupPossibilities = void 0;
-const v6 = __importStar(__nccwpck_require__(75280));
-const sprintf_js_1 = __nccwpck_require__(19973);
-function groupPossibilities(possibilities) {
-    return (0, sprintf_js_1.sprintf)('(%s)', possibilities.join('|'));
-}
-exports.groupPossibilities = groupPossibilities;
-function padGroup(group) {
-    if (group.length < 4) {
-        return (0, sprintf_js_1.sprintf)('0{0,%d}%s', 4 - group.length, group);
-    }
-    return group;
-}
-exports.padGroup = padGroup;
-exports.ADDRESS_BOUNDARY = '[^A-Fa-f0-9:]';
-function simpleRegularExpression(groups) {
-    const zeroIndexes = [];
-    groups.forEach((group, i) => {
-        const groupInteger = parseInt(group, 16);
-        if (groupInteger === 0) {
-            zeroIndexes.push(i);
-        }
-    });
-    // You can technically elide a single 0, this creates the regular expressions
-    // to match that eventuality
-    const possibilities = zeroIndexes.map((zeroIndex) => groups
-        .map((group, i) => {
-        if (i === zeroIndex) {
-            const elision = i === 0 || i === v6.GROUPS - 1 ? ':' : '';
-            return groupPossibilities([padGroup(group), elision]);
-        }
-        return padGroup(group);
-    })
-        .join(':'));
-    // The simplest case
-    possibilities.push(groups.map(padGroup).join(':'));
-    return groupPossibilities(possibilities);
-}
-exports.simpleRegularExpression = simpleRegularExpression;
-function possibleElisions(elidedGroups, moreLeft, moreRight) {
-    const left = moreLeft ? '' : ':';
-    const right = moreRight ? '' : ':';
-    const possibilities = [];
-    // 1. elision of everything (::)
-    if (!moreLeft && !moreRight) {
-        possibilities.push('::');
+exports.withAlg = withAlg;
+function message(msg, actual, ...types) {
+    types = types.filter(Boolean);
+    if (types.length > 2) {
+        const last = types.pop();
+        msg += `one of type ${types.join(', ')}, or ${last}.`;
     }
-    // 2. complete elision of the middle
-    if (moreLeft && moreRight) {
-        possibilities.push('');
+    else if (types.length === 2) {
+        msg += `one of type ${types[0]} or ${types[1]}.`;
     }
-    if ((moreRight && !moreLeft) || (!moreRight && moreLeft)) {
-        // 3. complete elision of one side
-        possibilities.push(':');
+    else {
+        msg += `of type ${types[0]}.`;
     }
-    // 4. elision from the left side
-    possibilities.push((0, sprintf_js_1.sprintf)('%s(:0{1,4}){1,%d}', left, elidedGroups - 1));
-    // 5. elision from the right side
-    possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){1,%d}%s', elidedGroups - 1, right));
-    // 6. no elision
-    possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}0{1,4}', elidedGroups - 1));
-    // 7. elision (including sloppy elision) from the middle
-    for (let groups = 1; groups < elidedGroups - 1; groups++) {
-        for (let position = 1; position < elidedGroups - groups; position++) {
-            possibilities.push((0, sprintf_js_1.sprintf)('(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}', position, elidedGroups - position - groups - 1));
-        }
+    if (actual == null) {
+        msg += ` Received ${actual}`;
     }
-    return groupPossibilities(possibilities);
-}
-exports.possibleElisions = possibleElisions;
-//# sourceMappingURL=regular-expressions.js.map
-
-/***/ }),
-
-/***/ 21608:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.experimental_jwksCache = exports.jwksCache = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0;
-var decrypt_js_1 = __nccwpck_require__(14298);
-Object.defineProperty(exports, "compactDecrypt", ({ enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } }));
-var decrypt_js_2 = __nccwpck_require__(59344);
-Object.defineProperty(exports, "flattenedDecrypt", ({ enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } }));
-var decrypt_js_3 = __nccwpck_require__(49783);
-Object.defineProperty(exports, "generalDecrypt", ({ enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } }));
-var encrypt_js_1 = __nccwpck_require__(71907);
-Object.defineProperty(exports, "GeneralEncrypt", ({ enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } }));
-var verify_js_1 = __nccwpck_require__(94212);
-Object.defineProperty(exports, "compactVerify", ({ enumerable: true, get: function () { return verify_js_1.compactVerify; } }));
-var verify_js_2 = __nccwpck_require__(56358);
-Object.defineProperty(exports, "flattenedVerify", ({ enumerable: true, get: function () { return verify_js_2.flattenedVerify; } }));
-var verify_js_3 = __nccwpck_require__(88323);
-Object.defineProperty(exports, "generalVerify", ({ enumerable: true, get: function () { return verify_js_3.generalVerify; } }));
-var verify_js_4 = __nccwpck_require__(35297);
-Object.defineProperty(exports, "jwtVerify", ({ enumerable: true, get: function () { return verify_js_4.jwtVerify; } }));
-var decrypt_js_4 = __nccwpck_require__(95339);
-Object.defineProperty(exports, "jwtDecrypt", ({ enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } }));
-var encrypt_js_2 = __nccwpck_require__(4434);
-Object.defineProperty(exports, "CompactEncrypt", ({ enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } }));
-var encrypt_js_3 = __nccwpck_require__(62372);
-Object.defineProperty(exports, "FlattenedEncrypt", ({ enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } }));
-var sign_js_1 = __nccwpck_require__(21760);
-Object.defineProperty(exports, "CompactSign", ({ enumerable: true, get: function () { return sign_js_1.CompactSign; } }));
-var sign_js_2 = __nccwpck_require__(86170);
-Object.defineProperty(exports, "FlattenedSign", ({ enumerable: true, get: function () { return sign_js_2.FlattenedSign; } }));
-var sign_js_3 = __nccwpck_require__(50443);
-Object.defineProperty(exports, "GeneralSign", ({ enumerable: true, get: function () { return sign_js_3.GeneralSign; } }));
-var sign_js_4 = __nccwpck_require__(22713);
-Object.defineProperty(exports, "SignJWT", ({ enumerable: true, get: function () { return sign_js_4.SignJWT; } }));
-var encrypt_js_4 = __nccwpck_require__(38375);
-Object.defineProperty(exports, "EncryptJWT", ({ enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } }));
-var thumbprint_js_1 = __nccwpck_require__(45396);
-Object.defineProperty(exports, "calculateJwkThumbprint", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } }));
-Object.defineProperty(exports, "calculateJwkThumbprintUri", ({ enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } }));
-var embedded_js_1 = __nccwpck_require__(88541);
-Object.defineProperty(exports, "EmbeddedJWK", ({ enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } }));
-var local_js_1 = __nccwpck_require__(25275);
-Object.defineProperty(exports, "createLocalJWKSet", ({ enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } }));
-var remote_js_1 = __nccwpck_require__(69260);
-Object.defineProperty(exports, "createRemoteJWKSet", ({ enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } }));
-Object.defineProperty(exports, "jwksCache", ({ enumerable: true, get: function () { return remote_js_1.jwksCache; } }));
-Object.defineProperty(exports, "experimental_jwksCache", ({ enumerable: true, get: function () { return remote_js_1.experimental_jwksCache; } }));
-var unsecured_js_1 = __nccwpck_require__(40560);
-Object.defineProperty(exports, "UnsecuredJWT", ({ enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } }));
-var export_js_1 = __nccwpck_require__(48108);
-Object.defineProperty(exports, "exportPKCS8", ({ enumerable: true, get: function () { return export_js_1.exportPKCS8; } }));
-Object.defineProperty(exports, "exportSPKI", ({ enumerable: true, get: function () { return export_js_1.exportSPKI; } }));
-Object.defineProperty(exports, "exportJWK", ({ enumerable: true, get: function () { return export_js_1.exportJWK; } }));
-var import_js_1 = __nccwpck_require__(45647);
-Object.defineProperty(exports, "importSPKI", ({ enumerable: true, get: function () { return import_js_1.importSPKI; } }));
-Object.defineProperty(exports, "importPKCS8", ({ enumerable: true, get: function () { return import_js_1.importPKCS8; } }));
-Object.defineProperty(exports, "importX509", ({ enumerable: true, get: function () { return import_js_1.importX509; } }));
-Object.defineProperty(exports, "importJWK", ({ enumerable: true, get: function () { return import_js_1.importJWK; } }));
-var decode_protected_header_js_1 = __nccwpck_require__(14704);
-Object.defineProperty(exports, "decodeProtectedHeader", ({ enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } }));
-var decode_jwt_js_1 = __nccwpck_require__(60002);
-Object.defineProperty(exports, "decodeJwt", ({ enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } }));
-exports.errors = __nccwpck_require__(15974);
-var generate_key_pair_js_1 = __nccwpck_require__(87820);
-Object.defineProperty(exports, "generateKeyPair", ({ enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } }));
-var generate_secret_js_1 = __nccwpck_require__(37152);
-Object.defineProperty(exports, "generateSecret", ({ enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } }));
-exports.base64url = __nccwpck_require__(78305);
-var runtime_js_1 = __nccwpck_require__(25021);
-Object.defineProperty(exports, "cryptoRuntime", ({ enumerable: true, get: function () { return runtime_js_1.default; } }));
+    else if (typeof actual === 'function' && actual.name) {
+        msg += ` Received function ${actual.name}`;
+    }
+    else if (typeof actual === 'object' && actual != null) {
+        if (actual.constructor?.name) {
+            msg += ` Received an instance of ${actual.constructor.name}`;
+        }
+    }
+    return msg;
+}
+exports["default"] = (actual, ...types) => {
+    return message('Key must be ', actual, ...types);
+};
+function withAlg(alg, actual, ...types) {
+    return message(`Key for the ${alg} algorithm must be `, actual, ...types);
+}
 
 
 /***/ }),
 
-/***/ 14298:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 21853:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.compactDecrypt = compactDecrypt;
-const decrypt_js_1 = __nccwpck_require__(59344);
-const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-async function compactDecrypt(jwe, key, options) {
-    if (jwe instanceof Uint8Array) {
-        jwe = buffer_utils_js_1.decoder.decode(jwe);
-    }
-    if (typeof jwe !== 'string') {
-        throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array');
-    }
-    const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');
-    if (length !== 5) {
-        throw new errors_js_1.JWEInvalid('Invalid Compact JWE');
+const isDisjoint = (...headers) => {
+    const sources = headers.filter(Boolean);
+    if (sources.length === 0 || sources.length === 1) {
+        return true;
     }
-    const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({
-        ciphertext,
-        iv: iv || undefined,
-        protected: protectedHeader,
-        tag: tag || undefined,
-        encrypted_key: encryptedKey || undefined,
-    }, key, options);
-    const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
-    if (typeof key === 'function') {
-        return { ...result, key: decrypted.key };
+    let acc;
+    for (const header of sources) {
+        const parameters = Object.keys(header);
+        if (!acc || acc.size === 0) {
+            acc = new Set(parameters);
+            continue;
+        }
+        for (const parameter of parameters) {
+            if (acc.has(parameter)) {
+                return false;
+            }
+            acc.add(parameter);
+        }
     }
-    return result;
-}
+    return true;
+};
+exports["default"] = isDisjoint;
 
 
 /***/ }),
 
-/***/ 4434:
+/***/ 91229:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.CompactEncrypt = void 0;
-const encrypt_js_1 = __nccwpck_require__(62372);
-class CompactEncrypt {
-    _flattened;
-    constructor(plaintext) {
-        this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext);
-    }
-    setContentEncryptionKey(cek) {
-        this._flattened.setContentEncryptionKey(cek);
-        return this;
-    }
-    setInitializationVector(iv) {
-        this._flattened.setInitializationVector(iv);
-        return this;
-    }
-    setProtectedHeader(protectedHeader) {
-        this._flattened.setProtectedHeader(protectedHeader);
-        return this;
+exports.isJWK = isJWK;
+exports.isPrivateJWK = isPrivateJWK;
+exports.isPublicJWK = isPublicJWK;
+exports.isSecretJWK = isSecretJWK;
+const is_object_js_1 = __nccwpck_require__(92242);
+function isJWK(key) {
+    return (0, is_object_js_1.default)(key) && typeof key.kty === 'string';
+}
+function isPrivateJWK(key) {
+    return key.kty !== 'oct' && typeof key.d === 'string';
+}
+function isPublicJWK(key) {
+    return key.kty !== 'oct' && typeof key.d === 'undefined';
+}
+function isSecretJWK(key) {
+    return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';
+}
+
+
+/***/ }),
+
+/***/ 92242:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = isObject;
+function isObjectLike(value) {
+    return typeof value === 'object' && value !== null;
+}
+function isObject(input) {
+    if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
+        return false;
     }
-    setKeyManagementParameters(parameters) {
-        this._flattened.setKeyManagementParameters(parameters);
-        return this;
+    if (Object.getPrototypeOf(input) === null) {
+        return true;
     }
-    async encrypt(key, options) {
-        const jwe = await this._flattened.encrypt(key, options);
-        return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');
+    let proto = input;
+    while (Object.getPrototypeOf(proto) !== null) {
+        proto = Object.getPrototypeOf(proto);
     }
+    return Object.getPrototypeOf(input) === proto;
 }
-exports.CompactEncrypt = CompactEncrypt;
 
 
 /***/ }),
 
-/***/ 59344:
+/***/ 56565:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.flattenedDecrypt = flattenedDecrypt;
-const base64url_js_1 = __nccwpck_require__(12635);
-const decrypt_js_1 = __nccwpck_require__(52806);
+exports.bitLength = bitLength;
 const errors_js_1 = __nccwpck_require__(15974);
-const is_disjoint_js_1 = __nccwpck_require__(21853);
-const is_object_js_1 = __nccwpck_require__(92242);
-const decrypt_key_management_js_1 = __nccwpck_require__(56243);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const cek_js_1 = __nccwpck_require__(87937);
-const validate_crit_js_1 = __nccwpck_require__(15595);
-const validate_algorithms_js_1 = __nccwpck_require__(19917);
-async function flattenedDecrypt(jwe, key, options) {
-    if (!(0, is_object_js_1.default)(jwe)) {
-        throw new errors_js_1.JWEInvalid('Flattened JWE must be an object');
-    }
-    if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
-        throw new errors_js_1.JWEInvalid('JOSE Header missing');
-    }
-    if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
-        throw new errors_js_1.JWEInvalid('JWE Initialization Vector incorrect type');
-    }
-    if (typeof jwe.ciphertext !== 'string') {
-        throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type');
-    }
-    if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
-        throw new errors_js_1.JWEInvalid('JWE Authentication Tag incorrect type');
-    }
-    if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
-        throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type');
-    }
-    if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
-        throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type');
-    }
-    if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
-        throw new errors_js_1.JWEInvalid('JWE AAD incorrect type');
-    }
-    if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) {
-        throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type');
-    }
-    if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) {
-        throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
-    }
-    let parsedProt;
-    if (jwe.protected) {
-        try {
-            const protectedHeader = (0, base64url_js_1.decode)(jwe.protected);
-            parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
-        }
-        catch {
-            throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid');
-        }
-    }
-    if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) {
-        throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
-    }
-    const joseHeader = {
-        ...parsedProt,
-        ...jwe.header,
-        ...jwe.unprotected,
-    };
-    (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
-    if (joseHeader.zip !== undefined) {
-        throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
-    }
-    const { alg, enc } = joseHeader;
-    if (typeof alg !== 'string' || !alg) {
-        throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
-    }
-    if (typeof enc !== 'string' || !enc) {
-        throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
-    }
-    const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms);
-    const contentEncryptionAlgorithms = options &&
-        (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
-    if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
-        (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
-        throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
-    }
-    if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
-        throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
-    }
-    let encryptedKey;
-    if (jwe.encrypted_key !== undefined) {
-        try {
-            encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key);
-        }
-        catch {
-            throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key');
-        }
-    }
-    let resolvedKey = false;
-    if (typeof key === 'function') {
-        key = await key(parsedProt, jwe);
-        resolvedKey = true;
-    }
-    let cek;
-    try {
-        cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options);
-    }
-    catch (err) {
-        if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) {
-            throw err;
-        }
-        cek = (0, cek_js_1.default)(enc);
-    }
-    let iv;
-    let tag;
-    if (jwe.iv !== undefined) {
-        try {
-            iv = (0, base64url_js_1.decode)(jwe.iv);
-        }
-        catch {
-            throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv');
-        }
-    }
-    if (jwe.tag !== undefined) {
-        try {
-            tag = (0, base64url_js_1.decode)(jwe.tag);
-        }
-        catch {
-            throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag');
-        }
-    }
-    const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? '');
-    let additionalData;
-    if (jwe.aad !== undefined) {
-        additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad));
-    }
-    else {
-        additionalData = protectedHeader;
-    }
-    let ciphertext;
-    try {
-        ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext);
-    }
-    catch {
-        throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext');
-    }
-    const plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData);
-    const result = { plaintext };
-    if (jwe.protected !== undefined) {
-        result.protectedHeader = parsedProt;
-    }
-    if (jwe.aad !== undefined) {
-        try {
-            result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad);
-        }
-        catch {
-            throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad');
-        }
-    }
-    if (jwe.unprotected !== undefined) {
-        result.sharedUnprotectedHeader = jwe.unprotected;
-    }
-    if (jwe.header !== undefined) {
-        result.unprotectedHeader = jwe.header;
-    }
-    if (resolvedKey) {
-        return { ...result, key };
+const random_js_1 = __nccwpck_require__(23376);
+function bitLength(alg) {
+    switch (alg) {
+        case 'A128GCM':
+        case 'A128GCMKW':
+        case 'A192GCM':
+        case 'A192GCMKW':
+        case 'A256GCM':
+        case 'A256GCMKW':
+            return 96;
+        case 'A128CBC-HS256':
+        case 'A192CBC-HS384':
+        case 'A256CBC-HS512':
+            return 128;
+        default:
+            throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
     }
-    return result;
 }
+exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3));
 
 
 /***/ }),
 
-/***/ 62372:
+/***/ 13354:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.FlattenedEncrypt = void 0;
-const base64url_js_1 = __nccwpck_require__(12635);
-const private_symbols_js_1 = __nccwpck_require__(46433);
-const encrypt_js_1 = __nccwpck_require__(36286);
-const encrypt_key_management_js_1 = __nccwpck_require__(96539);
 const errors_js_1 = __nccwpck_require__(15974);
-const is_disjoint_js_1 = __nccwpck_require__(21853);
 const buffer_utils_js_1 = __nccwpck_require__(45734);
-const validate_crit_js_1 = __nccwpck_require__(15595);
-class FlattenedEncrypt {
-    _plaintext;
-    _protectedHeader;
-    _sharedUnprotectedHeader;
-    _unprotectedHeader;
-    _aad;
-    _cek;
-    _iv;
-    _keyManagementParameters;
-    constructor(plaintext) {
-        if (!(plaintext instanceof Uint8Array)) {
-            throw new TypeError('plaintext must be an instance of Uint8Array');
-        }
-        this._plaintext = plaintext;
+const epoch_js_1 = __nccwpck_require__(40485);
+const secs_js_1 = __nccwpck_require__(40556);
+const is_object_js_1 = __nccwpck_require__(92242);
+const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '');
+const checkAudiencePresence = (audPayload, audOption) => {
+    if (typeof audPayload === 'string') {
+        return audOption.includes(audPayload);
     }
-    setKeyManagementParameters(parameters) {
-        if (this._keyManagementParameters) {
-            throw new TypeError('setKeyManagementParameters can only be called once');
-        }
-        this._keyManagementParameters = parameters;
-        return this;
+    if (Array.isArray(audPayload)) {
+        return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
     }
-    setProtectedHeader(protectedHeader) {
-        if (this._protectedHeader) {
-            throw new TypeError('setProtectedHeader can only be called once');
-        }
-        this._protectedHeader = protectedHeader;
-        return this;
+    return false;
+};
+exports["default"] = (protectedHeader, encodedPayload, options = {}) => {
+    let payload;
+    try {
+        payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload));
     }
-    setSharedUnprotectedHeader(sharedUnprotectedHeader) {
-        if (this._sharedUnprotectedHeader) {
-            throw new TypeError('setSharedUnprotectedHeader can only be called once');
-        }
-        this._sharedUnprotectedHeader = sharedUnprotectedHeader;
-        return this;
+    catch {
     }
-    setUnprotectedHeader(unprotectedHeader) {
-        if (this._unprotectedHeader) {
-            throw new TypeError('setUnprotectedHeader can only be called once');
-        }
-        this._unprotectedHeader = unprotectedHeader;
-        return this;
+    if (!(0, is_object_js_1.default)(payload)) {
+        throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object');
     }
-    setAdditionalAuthenticatedData(aad) {
-        this._aad = aad;
-        return this;
+    const { typ } = options;
+    if (typ &&
+        (typeof protectedHeader.typ !== 'string' ||
+            normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
+        throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
     }
-    setContentEncryptionKey(cek) {
-        if (this._cek) {
-            throw new TypeError('setContentEncryptionKey can only be called once');
+    const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
+    const presenceCheck = [...requiredClaims];
+    if (maxTokenAge !== undefined)
+        presenceCheck.push('iat');
+    if (audience !== undefined)
+        presenceCheck.push('aud');
+    if (subject !== undefined)
+        presenceCheck.push('sub');
+    if (issuer !== undefined)
+        presenceCheck.push('iss');
+    for (const claim of new Set(presenceCheck.reverse())) {
+        if (!(claim in payload)) {
+            throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
         }
-        this._cek = cek;
-        return this;
     }
-    setInitializationVector(iv) {
-        if (this._iv) {
-            throw new TypeError('setInitializationVector can only be called once');
-        }
-        this._iv = iv;
-        return this;
+    if (issuer &&
+        !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
+        throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
     }
-    async encrypt(key, options) {
-        if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
-            throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
-        }
-        if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
-            throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
-        }
-        const joseHeader = {
-            ...this._protectedHeader,
-            ...this._unprotectedHeader,
-            ...this._sharedUnprotectedHeader,
-        };
-        (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);
-        if (joseHeader.zip !== undefined) {
-            throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
-        }
-        const { alg, enc } = joseHeader;
-        if (typeof alg !== 'string' || !alg) {
-            throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
-        }
-        if (typeof enc !== 'string' || !enc) {
-            throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
-        }
-        let encryptedKey;
-        if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) {
-            throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
-        }
-        let cek;
-        {
-            let parameters;
-            ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters));
-            if (parameters) {
-                if (options && private_symbols_js_1.unprotected in options) {
-                    if (!this._unprotectedHeader) {
-                        this.setUnprotectedHeader(parameters);
-                    }
-                    else {
-                        this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
-                    }
-                }
-                else if (!this._protectedHeader) {
-                    this.setProtectedHeader(parameters);
-                }
-                else {
-                    this._protectedHeader = { ...this._protectedHeader, ...parameters };
-                }
-            }
-        }
-        let additionalData;
-        let protectedHeader;
-        let aadMember;
-        if (this._protectedHeader) {
-            protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
-        }
-        else {
-            protectedHeader = buffer_utils_js_1.encoder.encode('');
-        }
-        if (this._aad) {
-            aadMember = (0, base64url_js_1.encode)(this._aad);
-            additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember));
-        }
-        else {
-            additionalData = protectedHeader;
-        }
-        const { ciphertext, tag, iv } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData);
-        const jwe = {
-            ciphertext: (0, base64url_js_1.encode)(ciphertext),
-        };
-        if (iv) {
-            jwe.iv = (0, base64url_js_1.encode)(iv);
-        }
-        if (tag) {
-            jwe.tag = (0, base64url_js_1.encode)(tag);
+    if (subject && payload.sub !== subject) {
+        throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
+    }
+    if (audience &&
+        !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
+        throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
+    }
+    let tolerance;
+    switch (typeof options.clockTolerance) {
+        case 'string':
+            tolerance = (0, secs_js_1.default)(options.clockTolerance);
+            break;
+        case 'number':
+            tolerance = options.clockTolerance;
+            break;
+        case 'undefined':
+            tolerance = 0;
+            break;
+        default:
+            throw new TypeError('Invalid clockTolerance option type');
+    }
+    const { currentDate } = options;
+    const now = (0, epoch_js_1.default)(currentDate || new Date());
+    if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
+        throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
+    }
+    if (payload.nbf !== undefined) {
+        if (typeof payload.nbf !== 'number') {
+            throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
         }
-        if (encryptedKey) {
-            jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
+        if (payload.nbf > now + tolerance) {
+            throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
         }
-        if (aadMember) {
-            jwe.aad = aadMember;
+    }
+    if (payload.exp !== undefined) {
+        if (typeof payload.exp !== 'number') {
+            throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
         }
-        if (this._protectedHeader) {
-            jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
+        if (payload.exp <= now - tolerance) {
+            throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
         }
-        if (this._sharedUnprotectedHeader) {
-            jwe.unprotected = this._sharedUnprotectedHeader;
+    }
+    if (maxTokenAge) {
+        const age = now - payload.iat;
+        const max = typeof maxTokenAge === 'number' ? maxTokenAge : (0, secs_js_1.default)(maxTokenAge);
+        if (age - tolerance > max) {
+            throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
         }
-        if (this._unprotectedHeader) {
-            jwe.header = this._unprotectedHeader;
+        if (age < 0 - tolerance) {
+            throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
         }
-        return jwe;
     }
-}
-exports.FlattenedEncrypt = FlattenedEncrypt;
+    return payload;
+};
 
 
 /***/ }),
 
-/***/ 49783:
+/***/ 46433:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.unprotected = void 0;
+exports.unprotected = Symbol();
+
+
+/***/ }),
+
+/***/ 40556:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const minute = 60;
+const hour = minute * 60;
+const day = hour * 24;
+const week = day * 7;
+const year = day * 365.25;
+const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
+exports["default"] = (str) => {
+    const matched = REGEX.exec(str);
+    if (!matched || (matched[4] && matched[1])) {
+        throw new TypeError('Invalid time period format');
+    }
+    const value = parseFloat(matched[2]);
+    const unit = matched[3].toLowerCase();
+    let numericDate;
+    switch (unit) {
+        case 'sec':
+        case 'secs':
+        case 'second':
+        case 'seconds':
+        case 's':
+            numericDate = Math.round(value);
+            break;
+        case 'minute':
+        case 'minutes':
+        case 'min':
+        case 'mins':
+        case 'm':
+            numericDate = Math.round(value * minute);
+            break;
+        case 'hour':
+        case 'hours':
+        case 'hr':
+        case 'hrs':
+        case 'h':
+            numericDate = Math.round(value * hour);
+            break;
+        case 'day':
+        case 'days':
+        case 'd':
+            numericDate = Math.round(value * day);
+            break;
+        case 'week':
+        case 'weeks':
+        case 'w':
+            numericDate = Math.round(value * week);
+            break;
+        default:
+            numericDate = Math.round(value * year);
+            break;
+    }
+    if (matched[1] === '-' || matched[4] === 'ago') {
+        return -numericDate;
+    }
+    return numericDate;
+};
+
+
+/***/ }),
+
+/***/ 19917:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const validateAlgorithms = (option, algorithms) => {
+    if (algorithms !== undefined &&
+        (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {
+        throw new TypeError(`"${option}" option must be an array of strings`);
+    }
+    if (!algorithms) {
+        return undefined;
+    }
+    return new Set(algorithms);
+};
+exports["default"] = validateAlgorithms;
+
+
+/***/ }),
+
+/***/ 15595:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.generalDecrypt = generalDecrypt;
-const decrypt_js_1 = __nccwpck_require__(59344);
 const errors_js_1 = __nccwpck_require__(15974);
-const is_object_js_1 = __nccwpck_require__(92242);
-async function generalDecrypt(jwe, key, options) {
-    if (!(0, is_object_js_1.default)(jwe)) {
-        throw new errors_js_1.JWEInvalid('General JWE must be an object');
+function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
+    if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
+        throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
     }
-    if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) {
-        throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type');
+    if (!protectedHeader || protectedHeader.crit === undefined) {
+        return new Set();
     }
-    if (!jwe.recipients.length) {
-        throw new errors_js_1.JWEInvalid('JWE Recipients has no members');
+    if (!Array.isArray(protectedHeader.crit) ||
+        protectedHeader.crit.length === 0 ||
+        protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {
+        throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
     }
-    for (const recipient of jwe.recipients) {
-        try {
-            return await (0, decrypt_js_1.flattenedDecrypt)({
-                aad: jwe.aad,
-                ciphertext: jwe.ciphertext,
-                encrypted_key: recipient.encrypted_key,
-                header: recipient.header,
-                iv: jwe.iv,
-                protected: jwe.protected,
-                tag: jwe.tag,
-                unprotected: jwe.unprotected,
-            }, key, options);
+    let recognized;
+    if (recognizedOption !== undefined) {
+        recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
+    }
+    else {
+        recognized = recognizedDefault;
+    }
+    for (const parameter of protectedHeader.crit) {
+        if (!recognized.has(parameter)) {
+            throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
         }
-        catch {
+        if (joseHeader[parameter] === undefined) {
+            throw new Err(`Extension Header Parameter "${parameter}" is missing`);
+        }
+        if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
+            throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
         }
     }
-    throw new errors_js_1.JWEDecryptionFailed();
+    return new Set(protectedHeader.crit);
 }
+exports["default"] = validateCrit;
 
 
 /***/ }),
 
-/***/ 71907:
+/***/ 76202:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GeneralEncrypt = void 0;
-const encrypt_js_1 = __nccwpck_require__(62372);
-const private_symbols_js_1 = __nccwpck_require__(46433);
+exports.unwrap = exports.wrap = void 0;
+const node_buffer_1 = __nccwpck_require__(4573);
+const node_crypto_1 = __nccwpck_require__(77598);
 const errors_js_1 = __nccwpck_require__(15974);
-const cek_js_1 = __nccwpck_require__(87937);
-const is_disjoint_js_1 = __nccwpck_require__(21853);
-const encrypt_key_management_js_1 = __nccwpck_require__(96539);
-const base64url_js_1 = __nccwpck_require__(12635);
-const validate_crit_js_1 = __nccwpck_require__(15595);
-class IndividualRecipient {
-    parent;
-    unprotectedHeader;
-    key;
-    options;
-    constructor(enc, key, options) {
-        this.parent = enc;
-        this.key = key;
-        this.options = options;
-    }
-    setUnprotectedHeader(unprotectedHeader) {
-        if (this.unprotectedHeader) {
-            throw new TypeError('setUnprotectedHeader can only be called once');
-        }
-        this.unprotectedHeader = unprotectedHeader;
-        return this;
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const ciphers_js_1 = __nccwpck_require__(99271);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+function checkKeySize(key, alg) {
+    if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) {
+        throw new TypeError(`Invalid key size for alg: ${alg}`);
     }
-    addRecipient(...args) {
-        return this.parent.addRecipient(...args);
+}
+function ensureKeyObject(key, alg, usage) {
+    if ((0, is_key_object_js_1.default)(key)) {
+        return key;
     }
-    encrypt(...args) {
-        return this.parent.encrypt(...args);
+    if (key instanceof Uint8Array) {
+        return (0, node_crypto_1.createSecretKey)(key);
     }
-    done() {
-        return this.parent;
+    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage);
+        return node_crypto_1.KeyObject.from(key);
     }
+    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));
 }
-class GeneralEncrypt {
-    _plaintext;
-    _recipients = [];
-    _protectedHeader;
-    _unprotectedHeader;
-    _aad;
-    constructor(plaintext) {
-        this._plaintext = plaintext;
+const wrap = (alg, key, cek) => {
+    const size = parseInt(alg.slice(1, 4), 10);
+    const algorithm = `aes${size}-wrap`;
+    if (!(0, ciphers_js_1.default)(algorithm)) {
+        throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
     }
-    addRecipient(key, options) {
-        const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
-        this._recipients.push(recipient);
-        return recipient;
+    const keyObject = ensureKeyObject(key, alg, 'wrapKey');
+    checkKeySize(keyObject, alg);
+    const cipher = (0, node_crypto_1.createCipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6));
+    return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final());
+};
+exports.wrap = wrap;
+const unwrap = (alg, key, encryptedKey) => {
+    const size = parseInt(alg.slice(1, 4), 10);
+    const algorithm = `aes${size}-wrap`;
+    if (!(0, ciphers_js_1.default)(algorithm)) {
+        throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
     }
-    setProtectedHeader(protectedHeader) {
-        if (this._protectedHeader) {
-            throw new TypeError('setProtectedHeader can only be called once');
+    const keyObject = ensureKeyObject(key, alg, 'unwrapKey');
+    checkKeySize(keyObject, alg);
+    const cipher = (0, node_crypto_1.createDecipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6));
+    return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final());
+};
+exports.unwrap = unwrap;
+
+
+/***/ }),
+
+/***/ 12774:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0;
+const node_crypto_1 = __nccwpck_require__(77598);
+const node_buffer_1 = __nccwpck_require__(4573);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const genericExport = (keyType, keyFormat, key) => {
+    let keyObject;
+    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
+        if (!key.extractable) {
+            throw new TypeError('CryptoKey is not extractable');
         }
-        this._protectedHeader = protectedHeader;
-        return this;
+        keyObject = node_crypto_1.KeyObject.from(key);
     }
-    setSharedUnprotectedHeader(sharedUnprotectedHeader) {
-        if (this._unprotectedHeader) {
-            throw new TypeError('setSharedUnprotectedHeader can only be called once');
-        }
-        this._unprotectedHeader = sharedUnprotectedHeader;
-        return this;
+    else if ((0, is_key_object_js_1.default)(key)) {
+        keyObject = key;
     }
-    setAdditionalAuthenticatedData(aad) {
-        this._aad = aad;
-        return this;
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
     }
-    async encrypt() {
-        if (!this._recipients.length) {
-            throw new errors_js_1.JWEInvalid('at least one recipient must be added');
-        }
-        if (this._recipients.length === 1) {
-            const [recipient] = this._recipients;
-            const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext)
-                .setAdditionalAuthenticatedData(this._aad)
-                .setProtectedHeader(this._protectedHeader)
-                .setSharedUnprotectedHeader(this._unprotectedHeader)
-                .setUnprotectedHeader(recipient.unprotectedHeader)
-                .encrypt(recipient.key, { ...recipient.options });
-            const jwe = {
-                ciphertext: flattened.ciphertext,
-                iv: flattened.iv,
-                recipients: [{}],
-                tag: flattened.tag,
-            };
-            if (flattened.aad)
-                jwe.aad = flattened.aad;
-            if (flattened.protected)
-                jwe.protected = flattened.protected;
-            if (flattened.unprotected)
-                jwe.unprotected = flattened.unprotected;
-            if (flattened.encrypted_key)
-                jwe.recipients[0].encrypted_key = flattened.encrypted_key;
-            if (flattened.header)
-                jwe.recipients[0].header = flattened.header;
-            return jwe;
-        }
-        let enc;
-        for (let i = 0; i < this._recipients.length; i++) {
-            const recipient = this._recipients[i];
-            if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
-                throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
-            }
-            const joseHeader = {
-                ...this._protectedHeader,
-                ...this._unprotectedHeader,
-                ...recipient.unprotectedHeader,
-            };
-            const { alg } = joseHeader;
-            if (typeof alg !== 'string' || !alg) {
-                throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
-            }
-            if (alg === 'dir' || alg === 'ECDH-ES') {
-                throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
-            }
-            if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
-                throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
-            }
-            if (!enc) {
-                enc = joseHeader.enc;
-            }
-            else if (enc !== joseHeader.enc) {
-                throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
-            }
-            (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
-            if (joseHeader.zip !== undefined) {
-                throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
-            }
-        }
-        const cek = (0, cek_js_1.default)(enc);
-        const jwe = {
-            ciphertext: '',
-            iv: '',
-            recipients: [],
-            tag: '',
-        };
-        for (let i = 0; i < this._recipients.length; i++) {
-            const recipient = this._recipients[i];
-            const target = {};
-            jwe.recipients.push(target);
-            const joseHeader = {
-                ...this._protectedHeader,
-                ...this._unprotectedHeader,
-                ...recipient.unprotectedHeader,
-            };
-            const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;
-            if (i === 0) {
-                const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext)
-                    .setAdditionalAuthenticatedData(this._aad)
-                    .setContentEncryptionKey(cek)
-                    .setProtectedHeader(this._protectedHeader)
-                    .setSharedUnprotectedHeader(this._unprotectedHeader)
-                    .setUnprotectedHeader(recipient.unprotectedHeader)
-                    .setKeyManagementParameters({ p2c })
-                    .encrypt(recipient.key, {
-                    ...recipient.options,
-                    [private_symbols_js_1.unprotected]: true,
-                });
-                jwe.ciphertext = flattened.ciphertext;
-                jwe.iv = flattened.iv;
-                jwe.tag = flattened.tag;
-                if (flattened.aad)
-                    jwe.aad = flattened.aad;
-                if (flattened.protected)
-                    jwe.protected = flattened.protected;
-                if (flattened.unprotected)
-                    jwe.unprotected = flattened.unprotected;
-                target.encrypted_key = flattened.encrypted_key;
-                if (flattened.header)
-                    target.header = flattened.header;
-                continue;
-            }
-            const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg ||
-                this._protectedHeader?.alg ||
-                this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
-            target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
-            if (recipient.unprotectedHeader || parameters)
-                target.header = { ...recipient.unprotectedHeader, ...parameters };
+    if (keyObject.type !== keyType) {
+        throw new TypeError(`key is not a ${keyType} key`);
+    }
+    return keyObject.export({ format: 'pem', type: keyFormat });
+};
+const toSPKI = (key) => {
+    return genericExport('public', 'spki', key);
+};
+exports.toSPKI = toSPKI;
+const toPKCS8 = (key) => {
+    return genericExport('private', 'pkcs8', key);
+};
+exports.toPKCS8 = toPKCS8;
+const fromPKCS8 = (pem) => (0, node_crypto_1.createPrivateKey)({
+    key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'),
+    type: 'pkcs8',
+    format: 'der',
+});
+exports.fromPKCS8 = fromPKCS8;
+const fromSPKI = (pem) => (0, node_crypto_1.createPublicKey)({
+    key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'),
+    type: 'spki',
+    format: 'der',
+});
+exports.fromSPKI = fromSPKI;
+const fromX509 = (pem) => (0, node_crypto_1.createPublicKey)({
+    key: pem,
+    type: 'spki',
+    format: 'pem',
+});
+exports.fromX509 = fromX509;
+
+
+/***/ }),
+
+/***/ 12635:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0;
+const node_buffer_1 = __nccwpck_require__(4573);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+function normalize(input) {
+    let encoded = input;
+    if (encoded instanceof Uint8Array) {
+        encoded = buffer_utils_js_1.decoder.decode(encoded);
+    }
+    return encoded;
+}
+const encode = (input) => node_buffer_1.Buffer.from(input).toString('base64url');
+exports.encode = encode;
+const decodeBase64 = (input) => new Uint8Array(node_buffer_1.Buffer.from(input, 'base64'));
+exports.decodeBase64 = decodeBase64;
+const encodeBase64 = (input) => node_buffer_1.Buffer.from(input).toString('base64');
+exports.encodeBase64 = encodeBase64;
+const decode = (input) => new Uint8Array(node_buffer_1.Buffer.from(normalize(input), 'base64url'));
+exports.decode = decode;
+
+
+/***/ }),
+
+/***/ 36910:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = cbcTag;
+const node_crypto_1 = __nccwpck_require__(77598);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {
+    const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3));
+    const hmac = (0, node_crypto_1.createHmac)(`sha${macSize}`, macKey);
+    hmac.update(macData);
+    return hmac.digest().slice(0, keySize >> 3);
+}
+
+
+/***/ }),
+
+/***/ 67000:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const errors_js_1 = __nccwpck_require__(15974);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const checkCekLength = (enc, cek) => {
+    let expected;
+    switch (enc) {
+        case 'A128CBC-HS256':
+        case 'A192CBC-HS384':
+        case 'A256CBC-HS512':
+            expected = parseInt(enc.slice(-3), 10);
+            break;
+        case 'A128GCM':
+        case 'A192GCM':
+        case 'A256GCM':
+            expected = parseInt(enc.slice(1, 4), 10);
+            break;
+        default:
+            throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`);
+    }
+    if (cek instanceof Uint8Array) {
+        const actual = cek.byteLength << 3;
+        if (actual !== expected) {
+            throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
         }
-        return jwe;
+        return;
     }
-}
-exports.GeneralEncrypt = GeneralEncrypt;
+    if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') {
+        const actual = cek.symmetricKeySize << 3;
+        if (actual !== expected) {
+            throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
+        }
+        return;
+    }
+    throw new TypeError('Invalid Content Encryption Key type');
+};
+exports["default"] = checkCekLength;
 
 
 /***/ }),
 
-/***/ 88541:
+/***/ 65142:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.EmbeddedJWK = EmbeddedJWK;
-const import_js_1 = __nccwpck_require__(45647);
-const is_object_js_1 = __nccwpck_require__(92242);
-const errors_js_1 = __nccwpck_require__(15974);
-async function EmbeddedJWK(protectedHeader, token) {
-    const joseHeader = {
-        ...protectedHeader,
-        ...token?.header,
-    };
-    if (!(0, is_object_js_1.default)(joseHeader.jwk)) {
-        throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
+const node_crypto_1 = __nccwpck_require__(77598);
+exports["default"] = (key, alg) => {
+    let modulusLength;
+    try {
+        if (key instanceof node_crypto_1.KeyObject) {
+            modulusLength = key.asymmetricKeyDetails?.modulusLength;
+        }
+        else {
+            modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3;
+        }
     }
-    const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
-    if (key instanceof Uint8Array || key.type !== 'public') {
-        throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
+    catch { }
+    if (typeof modulusLength !== 'number' || modulusLength < 2048) {
+        throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
     }
-    return key;
-}
+};
 
 
 /***/ }),
 
-/***/ 45396:
+/***/ 99271:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.calculateJwkThumbprint = calculateJwkThumbprint;
-exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri;
-const digest_js_1 = __nccwpck_require__(12931);
-const base64url_js_1 = __nccwpck_require__(12635);
-const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const is_object_js_1 = __nccwpck_require__(92242);
-const check = (value, description) => {
-    if (typeof value !== 'string' || !value) {
-        throw new errors_js_1.JWKInvalid(`${description} missing or invalid`);
-    }
+const node_crypto_1 = __nccwpck_require__(77598);
+let ciphers;
+exports["default"] = (algorithm) => {
+    ciphers ||= new Set((0, node_crypto_1.getCiphers)());
+    return ciphers.has(algorithm);
 };
-async function calculateJwkThumbprint(jwk, digestAlgorithm) {
-    if (!(0, is_object_js_1.default)(jwk)) {
-        throw new TypeError('JWK must be an object');
-    }
-    digestAlgorithm ??= 'sha256';
-    if (digestAlgorithm !== 'sha256' &&
-        digestAlgorithm !== 'sha384' &&
-        digestAlgorithm !== 'sha512') {
-        throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
-    }
-    let components;
-    switch (jwk.kty) {
-        case 'EC':
-            check(jwk.crv, '"crv" (Curve) Parameter');
-            check(jwk.x, '"x" (X Coordinate) Parameter');
-            check(jwk.y, '"y" (Y Coordinate) Parameter');
-            components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
-            break;
-        case 'OKP':
-            check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
-            check(jwk.x, '"x" (Public Key) Parameter');
-            components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
-            break;
-        case 'RSA':
-            check(jwk.e, '"e" (Exponent) Parameter');
-            check(jwk.n, '"n" (Modulus) Parameter');
-            components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
-            break;
-        case 'oct':
-            check(jwk.k, '"k" (Key Value) Parameter');
-            components = { k: jwk.k, kty: jwk.kty };
-            break;
-        default:
-            throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
-    }
-    const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components));
-    return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data));
-}
-async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
-    digestAlgorithm ??= 'sha256';
-    const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
-    return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
-}
 
 
 /***/ }),
 
-/***/ 25275:
+/***/ 52806:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createLocalJWKSet = createLocalJWKSet;
-const import_js_1 = __nccwpck_require__(45647);
+const node_crypto_1 = __nccwpck_require__(77598);
+const check_iv_length_js_1 = __nccwpck_require__(63351);
+const check_cek_length_js_1 = __nccwpck_require__(67000);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
 const errors_js_1 = __nccwpck_require__(15974);
-const is_object_js_1 = __nccwpck_require__(92242);
-function getKtyFromAlg(alg) {
-    switch (typeof alg === 'string' && alg.slice(0, 2)) {
-        case 'RS':
-        case 'PS':
-            return 'RSA';
-        case 'ES':
-            return 'EC';
-        case 'Ed':
-            return 'OKP';
-        default:
-            throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
+const timing_safe_equal_js_1 = __nccwpck_require__(39106);
+const cbc_tag_js_1 = __nccwpck_require__(36910);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const ciphers_js_1 = __nccwpck_require__(99271);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
+    const keySize = parseInt(enc.slice(1, 4), 10);
+    if ((0, is_key_object_js_1.default)(cek)) {
+        cek = cek.export();
     }
-}
-function isJWKSLike(jwks) {
-    return (jwks &&
-        typeof jwks === 'object' &&
-        Array.isArray(jwks.keys) &&
-        jwks.keys.every(isJWKLike));
-}
-function isJWKLike(key) {
-    return (0, is_object_js_1.default)(key);
-}
-function clone(obj) {
-    if (typeof structuredClone === 'function') {
-        return structuredClone(obj);
+    const encKey = cek.subarray(keySize >> 3);
+    const macKey = cek.subarray(0, keySize >> 3);
+    const macSize = parseInt(enc.slice(-3), 10);
+    const algorithm = `aes-${keySize}-cbc`;
+    if (!(0, ciphers_js_1.default)(algorithm)) {
+        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
     }
-    return JSON.parse(JSON.stringify(obj));
-}
-class LocalJWKSet {
-    _jwks;
-    _cached = new WeakMap();
-    constructor(jwks) {
-        if (!isJWKSLike(jwks)) {
-            throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed');
-        }
-        this._jwks = clone(jwks);
+    const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize);
+    let macCheckPassed;
+    try {
+        macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag);
     }
-    async getKey(protectedHeader, token) {
-        const { alg, kid } = { ...protectedHeader, ...token?.header };
-        const kty = getKtyFromAlg(alg);
-        const candidates = this._jwks.keys.filter((jwk) => {
-            let candidate = kty === jwk.kty;
-            if (candidate && typeof kid === 'string') {
-                candidate = kid === jwk.kid;
-            }
-            if (candidate && typeof jwk.alg === 'string') {
-                candidate = alg === jwk.alg;
-            }
-            if (candidate && typeof jwk.use === 'string') {
-                candidate = jwk.use === 'sig';
-            }
-            if (candidate && Array.isArray(jwk.key_ops)) {
-                candidate = jwk.key_ops.includes('verify');
-            }
-            if (candidate && alg === 'EdDSA') {
-                candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';
-            }
-            if (candidate) {
-                switch (alg) {
-                    case 'ES256':
-                        candidate = jwk.crv === 'P-256';
-                        break;
-                    case 'ES256K':
-                        candidate = jwk.crv === 'secp256k1';
-                        break;
-                    case 'ES384':
-                        candidate = jwk.crv === 'P-384';
-                        break;
-                    case 'ES512':
-                        candidate = jwk.crv === 'P-521';
-                        break;
-                }
-            }
-            return candidate;
-        });
-        const { 0: jwk, length } = candidates;
-        if (length === 0) {
-            throw new errors_js_1.JWKSNoMatchingKey();
-        }
-        if (length !== 1) {
-            const error = new errors_js_1.JWKSMultipleMatchingKeys();
-            const { _cached } = this;
-            error[Symbol.asyncIterator] = async function* () {
-                for (const jwk of candidates) {
-                    try {
-                        yield await importWithAlgCache(_cached, jwk, alg);
-                    }
-                    catch { }
-                }
-            };
-            throw error;
-        }
-        return importWithAlgCache(this._cached, jwk, alg);
+    catch {
+    }
+    if (!macCheckPassed) {
+        throw new errors_js_1.JWEDecryptionFailed();
+    }
+    let plaintext;
+    try {
+        const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, encKey, iv);
+        plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final());
+    }
+    catch {
+    }
+    if (!plaintext) {
+        throw new errors_js_1.JWEDecryptionFailed();
     }
+    return plaintext;
 }
-async function importWithAlgCache(cache, jwk, alg) {
-    const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
-    if (cached[alg] === undefined) {
-        const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg);
-        if (key instanceof Uint8Array || key.type !== 'public') {
-            throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys');
+function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
+    const keySize = parseInt(enc.slice(1, 4), 10);
+    const algorithm = `aes-${keySize}-gcm`;
+    if (!(0, ciphers_js_1.default)(algorithm)) {
+        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
+    }
+    try {
+        const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 });
+        decipher.setAuthTag(tag);
+        if (aad.byteLength) {
+            decipher.setAAD(aad, { plaintextLength: ciphertext.length });
         }
-        cached[alg] = key;
+        const plaintext = decipher.update(ciphertext);
+        decipher.final();
+        return plaintext;
+    }
+    catch {
+        throw new errors_js_1.JWEDecryptionFailed();
     }
-    return cached[alg];
-}
-function createLocalJWKSet(jwks) {
-    const set = new LocalJWKSet(jwks);
-    const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
-    Object.defineProperties(localJWKSet, {
-        jwks: {
-            value: () => clone(set._jwks),
-            enumerable: true,
-            configurable: false,
-            writable: false,
-        },
-    });
-    return localJWKSet;
 }
+const decrypt = (enc, cek, ciphertext, iv, tag, aad) => {
+    let key;
+    if ((0, webcrypto_js_1.isCryptoKey)(cek)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt');
+        key = node_crypto_1.KeyObject.from(cek);
+    }
+    else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) {
+        key = cek;
+    }
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array'));
+    }
+    if (!iv) {
+        throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing');
+    }
+    if (!tag) {
+        throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing');
+    }
+    (0, check_cek_length_js_1.default)(enc, key);
+    (0, check_iv_length_js_1.default)(enc, iv);
+    switch (enc) {
+        case 'A128CBC-HS256':
+        case 'A192CBC-HS384':
+        case 'A256CBC-HS512':
+            return cbcDecrypt(enc, key, ciphertext, iv, tag, aad);
+        case 'A128GCM':
+        case 'A192GCM':
+        case 'A256GCM':
+            return gcmDecrypt(enc, key, ciphertext, iv, tag, aad);
+        default:
+            throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
+    }
+};
+exports["default"] = decrypt;
 
 
 /***/ }),
 
-/***/ 69260:
+/***/ 12931:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.experimental_jwksCache = exports.jwksCache = void 0;
-exports.createRemoteJWKSet = createRemoteJWKSet;
-const fetch_jwks_js_1 = __nccwpck_require__(20311);
+const node_crypto_1 = __nccwpck_require__(77598);
+const digest = (algorithm, data) => (0, node_crypto_1.createHash)(algorithm).update(data).digest();
+exports["default"] = digest;
+
+
+/***/ }),
+
+/***/ 74510:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports["default"] = dsaDigest;
 const errors_js_1 = __nccwpck_require__(15974);
-const local_js_1 = __nccwpck_require__(25275);
-const is_object_js_1 = __nccwpck_require__(92242);
-function isCloudflareWorkers() {
-    return (typeof WebSocketPair !== 'undefined' ||
-        (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
-        (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
-}
-let USER_AGENT;
-if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
-    const NAME = 'jose';
-    const VERSION = 'v5.9.6';
-    USER_AGENT = `${NAME}/${VERSION}`;
+function dsaDigest(alg) {
+    switch (alg) {
+        case 'PS256':
+        case 'RS256':
+        case 'ES256':
+        case 'ES256K':
+            return 'sha256';
+        case 'PS384':
+        case 'RS384':
+        case 'ES384':
+            return 'sha384';
+        case 'PS512':
+        case 'RS512':
+        case 'ES512':
+            return 'sha512';
+        case 'EdDSA':
+            return undefined;
+        default:
+            throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+    }
 }
-exports.jwksCache = Symbol();
-function isFreshJwksCache(input, cacheMaxAge) {
-    if (typeof input !== 'object' || input === null) {
-        return false;
+
+
+/***/ }),
+
+/***/ 43359:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ecdhAllowed = void 0;
+exports.deriveKey = deriveKey;
+exports.generateEpk = generateEpk;
+const node_crypto_1 = __nccwpck_require__(77598);
+const node_util_1 = __nccwpck_require__(57975);
+const get_named_curve_js_1 = __nccwpck_require__(65661);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const errors_js_1 = __nccwpck_require__(15974);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const generateKeyPair = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair);
+async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
+    let publicKey;
+    if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH');
+        publicKey = node_crypto_1.KeyObject.from(publicKee);
     }
-    if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {
-        return false;
+    else if ((0, is_key_object_js_1.default)(publicKee)) {
+        publicKey = publicKee;
     }
-    if (!('jwks' in input) ||
-        !(0, is_object_js_1.default)(input.jwks) ||
-        !Array.isArray(input.jwks.keys) ||
-        !Array.prototype.every.call(input.jwks.keys, is_object_js_1.default)) {
-        return false;
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types));
     }
-    return true;
-}
-class RemoteJWKSet {
-    _url;
-    _timeoutDuration;
-    _cooldownDuration;
-    _cacheMaxAge;
-    _jwksTimestamp;
-    _pendingFetch;
-    _options;
-    _local;
-    _cache;
-    constructor(url, options) {
-        if (!(url instanceof URL)) {
-            throw new TypeError('url must be an instance of URL');
-        }
-        this._url = new URL(url.href);
-        this._options = { agent: options?.agent, headers: options?.headers };
-        this._timeoutDuration =
-            typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
-        this._cooldownDuration =
-            typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
-        this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
-        if (options?.[exports.jwksCache] !== undefined) {
-            this._cache = options?.[exports.jwksCache];
-            if (isFreshJwksCache(options?.[exports.jwksCache], this._cacheMaxAge)) {
-                this._jwksTimestamp = this._cache.uat;
-                this._local = (0, local_js_1.createLocalJWKSet)(this._cache.jwks);
-            }
-        }
+    let privateKey;
+    if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits');
+        privateKey = node_crypto_1.KeyObject.from(privateKee);
     }
-    coolingDown() {
-        return typeof this._jwksTimestamp === 'number'
-            ? Date.now() < this._jwksTimestamp + this._cooldownDuration
-            : false;
+    else if ((0, is_key_object_js_1.default)(privateKee)) {
+        privateKey = privateKee;
     }
-    fresh() {
-        return typeof this._jwksTimestamp === 'number'
-            ? Date.now() < this._jwksTimestamp + this._cacheMaxAge
-            : false;
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types));
     }
-    async getKey(protectedHeader, token) {
-        if (!this._local || !this.fresh()) {
-            await this.reload();
-        }
-        try {
-            return await this._local(protectedHeader, token);
-        }
-        catch (err) {
-            if (err instanceof errors_js_1.JWKSNoMatchingKey) {
-                if (this.coolingDown() === false) {
-                    await this.reload();
-                    return this._local(protectedHeader, token);
-                }
-            }
-            throw err;
-        }
+    const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength));
+    const sharedSecret = (0, node_crypto_1.diffieHellman)({ privateKey, publicKey });
+    return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value);
+}
+async function generateEpk(kee) {
+    let key;
+    if ((0, webcrypto_js_1.isCryptoKey)(kee)) {
+        key = node_crypto_1.KeyObject.from(kee);
     }
-    async reload() {
-        if (this._pendingFetch && isCloudflareWorkers()) {
-            this._pendingFetch = undefined;
+    else if ((0, is_key_object_js_1.default)(kee)) {
+        key = kee;
+    }
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types));
+    }
+    switch (key.asymmetricKeyType) {
+        case 'x25519':
+            return generateKeyPair('x25519');
+        case 'x448': {
+            return generateKeyPair('x448');
         }
-        const headers = new Headers(this._options.headers);
-        if (USER_AGENT && !headers.has('User-Agent')) {
-            headers.set('User-Agent', USER_AGENT);
-            this._options.headers = Object.fromEntries(headers.entries());
+        case 'ec': {
+            const namedCurve = (0, get_named_curve_js_1.default)(key);
+            return generateKeyPair('ec', { namedCurve });
         }
-        this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options)
-            .then((json) => {
-            this._local = (0, local_js_1.createLocalJWKSet)(json);
-            if (this._cache) {
-                this._cache.uat = Date.now();
-                this._cache.jwks = json;
-            }
-            this._jwksTimestamp = Date.now();
-            this._pendingFetch = undefined;
-        })
-            .catch((err) => {
-            this._pendingFetch = undefined;
-            throw err;
-        });
-        await this._pendingFetch;
+        default:
+            throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK');
     }
 }
-function createRemoteJWKSet(url, options) {
-    const set = new RemoteJWKSet(url, options);
-    const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
-    Object.defineProperties(remoteJWKSet, {
-        coolingDown: {
-            get: () => set.coolingDown(),
-            enumerable: true,
-            configurable: false,
-        },
-        fresh: {
-            get: () => set.fresh(),
-            enumerable: true,
-            configurable: false,
-        },
-        reload: {
-            value: () => set.reload(),
-            enumerable: true,
-            configurable: false,
-            writable: false,
-        },
-        reloading: {
-            get: () => !!set._pendingFetch,
-            enumerable: true,
-            configurable: false,
-        },
-        jwks: {
-            value: () => set._local?.jwks(),
-            enumerable: true,
-            configurable: false,
-            writable: false,
-        },
-    });
-    return remoteJWKSet;
-}
-exports.experimental_jwksCache = exports.jwksCache;
+const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key));
+exports.ecdhAllowed = ecdhAllowed;
 
 
 /***/ }),
 
-/***/ 21760:
+/***/ 36286:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.CompactSign = void 0;
-const sign_js_1 = __nccwpck_require__(86170);
-class CompactSign {
-    _flattened;
-    constructor(payload) {
-        this._flattened = new sign_js_1.FlattenedSign(payload);
+const node_crypto_1 = __nccwpck_require__(77598);
+const check_iv_length_js_1 = __nccwpck_require__(63351);
+const check_cek_length_js_1 = __nccwpck_require__(67000);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const cbc_tag_js_1 = __nccwpck_require__(36910);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const iv_js_1 = __nccwpck_require__(56565);
+const errors_js_1 = __nccwpck_require__(15974);
+const ciphers_js_1 = __nccwpck_require__(99271);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+function cbcEncrypt(enc, plaintext, cek, iv, aad) {
+    const keySize = parseInt(enc.slice(1, 4), 10);
+    if ((0, is_key_object_js_1.default)(cek)) {
+        cek = cek.export();
     }
-    setProtectedHeader(protectedHeader) {
-        this._flattened.setProtectedHeader(protectedHeader);
-        return this;
+    const encKey = cek.subarray(keySize >> 3);
+    const macKey = cek.subarray(0, keySize >> 3);
+    const algorithm = `aes-${keySize}-cbc`;
+    if (!(0, ciphers_js_1.default)(algorithm)) {
+        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
     }
-    async sign(key, options) {
-        const jws = await this._flattened.sign(key, options);
-        if (jws.payload === undefined) {
-            throw new TypeError('use the flattened module for creating JWS with b64: false');
-        }
-        return `${jws.protected}.${jws.payload}.${jws.signature}`;
+    const cipher = (0, node_crypto_1.createCipheriv)(algorithm, encKey, iv);
+    const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final());
+    const macSize = parseInt(enc.slice(-3), 10);
+    const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize);
+    return { ciphertext, tag, iv };
+}
+function gcmEncrypt(enc, plaintext, cek, iv, aad) {
+    const keySize = parseInt(enc.slice(1, 4), 10);
+    const algorithm = `aes-${keySize}-gcm`;
+    if (!(0, ciphers_js_1.default)(algorithm)) {
+        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
+    }
+    const cipher = (0, node_crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 });
+    if (aad.byteLength) {
+        cipher.setAAD(aad, { plaintextLength: plaintext.length });
     }
+    const ciphertext = cipher.update(plaintext);
+    cipher.final();
+    const tag = cipher.getAuthTag();
+    return { ciphertext, tag, iv };
 }
-exports.CompactSign = CompactSign;
+const encrypt = (enc, plaintext, cek, iv, aad) => {
+    let key;
+    if ((0, webcrypto_js_1.isCryptoKey)(cek)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt');
+        key = node_crypto_1.KeyObject.from(cek);
+    }
+    else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) {
+        key = cek;
+    }
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array'));
+    }
+    (0, check_cek_length_js_1.default)(enc, key);
+    if (iv) {
+        (0, check_iv_length_js_1.default)(enc, iv);
+    }
+    else {
+        iv = (0, iv_js_1.default)(enc);
+    }
+    switch (enc) {
+        case 'A128CBC-HS256':
+        case 'A192CBC-HS384':
+        case 'A256CBC-HS512':
+            return cbcEncrypt(enc, plaintext, key, iv, aad);
+        case 'A128GCM':
+        case 'A192GCM':
+        case 'A256GCM':
+            return gcmEncrypt(enc, plaintext, key, iv, aad);
+        default:
+            throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
+    }
+};
+exports["default"] = encrypt;
 
 
 /***/ }),
 
-/***/ 94212:
+/***/ 20311:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.compactVerify = compactVerify;
-const verify_js_1 = __nccwpck_require__(56358);
+const http = __nccwpck_require__(37067);
+const https = __nccwpck_require__(44708);
+const node_events_1 = __nccwpck_require__(78474);
 const errors_js_1 = __nccwpck_require__(15974);
 const buffer_utils_js_1 = __nccwpck_require__(45734);
-async function compactVerify(jws, key, options) {
-    if (jws instanceof Uint8Array) {
-        jws = buffer_utils_js_1.decoder.decode(jws);
+const fetchJwks = async (url, timeout, options) => {
+    let get;
+    switch (url.protocol) {
+        case 'https:':
+            get = https.get;
+            break;
+        case 'http:':
+            get = http.get;
+            break;
+        default:
+            throw new TypeError('Unsupported URL protocol.');
     }
-    if (typeof jws !== 'string') {
-        throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array');
+    const { agent, headers } = options;
+    const req = get(url.href, {
+        agent,
+        timeout,
+        headers,
+    });
+    const [response] = (await Promise.race([(0, node_events_1.once)(req, 'response'), (0, node_events_1.once)(req, 'timeout')]));
+    if (!response) {
+        req.destroy();
+        throw new errors_js_1.JWKSTimeout();
     }
-    const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
-    if (length !== 3) {
-        throw new errors_js_1.JWSInvalid('Invalid Compact JWS');
+    if (response.statusCode !== 200) {
+        throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
     }
-    const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options);
-    const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
-    if (typeof key === 'function') {
-        return { ...result, key: verified.key };
+    const parts = [];
+    for await (const part of response) {
+        parts.push(part);
     }
-    return result;
-}
+    try {
+        return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts)));
+    }
+    catch {
+        throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
+    }
+};
+exports["default"] = fetchJwks;
 
 
 /***/ }),
 
-/***/ 86170:
+/***/ 10088:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.FlattenedSign = void 0;
-const base64url_js_1 = __nccwpck_require__(12635);
-const sign_js_1 = __nccwpck_require__(26966);
-const is_disjoint_js_1 = __nccwpck_require__(21853);
+exports.generateSecret = generateSecret;
+exports.generateKeyPair = generateKeyPair;
+const node_crypto_1 = __nccwpck_require__(77598);
+const node_util_1 = __nccwpck_require__(57975);
+const random_js_1 = __nccwpck_require__(23376);
 const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const check_key_type_js_1 = __nccwpck_require__(29555);
-const validate_crit_js_1 = __nccwpck_require__(15595);
-class FlattenedSign {
-    _payload;
-    _protectedHeader;
-    _unprotectedHeader;
-    constructor(payload) {
-        if (!(payload instanceof Uint8Array)) {
-            throw new TypeError('payload must be an instance of Uint8Array');
-        }
-        this._payload = payload;
-    }
-    setProtectedHeader(protectedHeader) {
-        if (this._protectedHeader) {
-            throw new TypeError('setProtectedHeader can only be called once');
-        }
-        this._protectedHeader = protectedHeader;
-        return this;
-    }
-    setUnprotectedHeader(unprotectedHeader) {
-        if (this._unprotectedHeader) {
-            throw new TypeError('setUnprotectedHeader can only be called once');
-        }
-        this._unprotectedHeader = unprotectedHeader;
-        return this;
+const generate = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair);
+async function generateSecret(alg, options) {
+    let length;
+    switch (alg) {
+        case 'HS256':
+        case 'HS384':
+        case 'HS512':
+        case 'A128CBC-HS256':
+        case 'A192CBC-HS384':
+        case 'A256CBC-HS512':
+            length = parseInt(alg.slice(-3), 10);
+            break;
+        case 'A128KW':
+        case 'A192KW':
+        case 'A256KW':
+        case 'A128GCMKW':
+        case 'A192GCMKW':
+        case 'A256GCMKW':
+        case 'A128GCM':
+        case 'A192GCM':
+        case 'A256GCM':
+            length = parseInt(alg.slice(1, 4), 10);
+            break;
+        default:
+            throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
     }
-    async sign(key, options) {
-        if (!this._protectedHeader && !this._unprotectedHeader) {
-            throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
-        }
-        if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) {
-            throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
-        }
-        const joseHeader = {
-            ...this._protectedHeader,
-            ...this._unprotectedHeader,
-        };
-        const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
-        let b64 = true;
-        if (extensions.has('b64')) {
-            b64 = this._protectedHeader.b64;
-            if (typeof b64 !== 'boolean') {
-                throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+    return (0, node_crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3)));
+}
+async function generateKeyPair(alg, options) {
+    switch (alg) {
+        case 'RS256':
+        case 'RS384':
+        case 'RS512':
+        case 'PS256':
+        case 'PS384':
+        case 'PS512':
+        case 'RSA-OAEP':
+        case 'RSA-OAEP-256':
+        case 'RSA-OAEP-384':
+        case 'RSA-OAEP-512':
+        case 'RSA1_5': {
+            const modulusLength = options?.modulusLength ?? 2048;
+            if (typeof modulusLength !== 'number' || modulusLength < 2048) {
+                throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
             }
+            const keypair = await generate('rsa', {
+                modulusLength,
+                publicExponent: 0x10001,
+            });
+            return keypair;
         }
-        const { alg } = joseHeader;
-        if (typeof alg !== 'string' || !alg) {
-            throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
-        }
-        (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'sign');
-        let payload = this._payload;
-        if (b64) {
-            payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload));
-        }
-        let protectedHeader;
-        if (this._protectedHeader) {
-            protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
-        }
-        else {
-            protectedHeader = buffer_utils_js_1.encoder.encode('');
-        }
-        const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload);
-        const signature = await (0, sign_js_1.default)(alg, key, data);
-        const jws = {
-            signature: (0, base64url_js_1.encode)(signature),
-            payload: '',
-        };
-        if (b64) {
-            jws.payload = buffer_utils_js_1.decoder.decode(payload);
-        }
-        if (this._unprotectedHeader) {
-            jws.header = this._unprotectedHeader;
+        case 'ES256':
+            return generate('ec', { namedCurve: 'P-256' });
+        case 'ES256K':
+            return generate('ec', { namedCurve: 'secp256k1' });
+        case 'ES384':
+            return generate('ec', { namedCurve: 'P-384' });
+        case 'ES512':
+            return generate('ec', { namedCurve: 'P-521' });
+        case 'EdDSA': {
+            switch (options?.crv) {
+                case undefined:
+                case 'Ed25519':
+                    return generate('ed25519');
+                case 'Ed448':
+                    return generate('ed448');
+                default:
+                    throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448');
+            }
         }
-        if (this._protectedHeader) {
-            jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
+        case 'ECDH-ES':
+        case 'ECDH-ES+A128KW':
+        case 'ECDH-ES+A192KW':
+        case 'ECDH-ES+A256KW': {
+            const crv = options?.crv ?? 'P-256';
+            switch (crv) {
+                case undefined:
+                case 'P-256':
+                case 'P-384':
+                case 'P-521':
+                    return generate('ec', { namedCurve: crv });
+                case 'X25519':
+                    return generate('x25519');
+                case 'X448':
+                    return generate('x448');
+                default:
+                    throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
+            }
         }
-        return jws;
+        default:
+            throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
     }
 }
-exports.FlattenedSign = FlattenedSign;
 
 
 /***/ }),
 
-/***/ 56358:
+/***/ 65661:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.flattenedVerify = flattenedVerify;
-const base64url_js_1 = __nccwpck_require__(12635);
-const verify_js_1 = __nccwpck_require__(11242);
+exports.weakMap = void 0;
+const node_crypto_1 = __nccwpck_require__(77598);
 const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const is_disjoint_js_1 = __nccwpck_require__(21853);
-const is_object_js_1 = __nccwpck_require__(92242);
-const check_key_type_js_1 = __nccwpck_require__(29555);
-const validate_crit_js_1 = __nccwpck_require__(15595);
-const validate_algorithms_js_1 = __nccwpck_require__(19917);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
 const is_jwk_js_1 = __nccwpck_require__(91229);
-const import_js_1 = __nccwpck_require__(45647);
-async function flattenedVerify(jws, key, options) {
-    if (!(0, is_object_js_1.default)(jws)) {
-        throw new errors_js_1.JWSInvalid('Flattened JWS must be an object');
-    }
-    if (jws.protected === undefined && jws.header === undefined) {
-        throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
-    }
-    if (jws.protected !== undefined && typeof jws.protected !== 'string') {
-        throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type');
-    }
-    if (jws.payload === undefined) {
-        throw new errors_js_1.JWSInvalid('JWS Payload missing');
-    }
-    if (typeof jws.signature !== 'string') {
-        throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type');
-    }
-    if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) {
-        throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type');
-    }
-    let parsedProt = {};
-    if (jws.protected) {
-        try {
-            const protectedHeader = (0, base64url_js_1.decode)(jws.protected);
-            parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
-        }
-        catch {
-            throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid');
-        }
-    }
-    if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) {
-        throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
-    }
-    const joseHeader = {
-        ...parsedProt,
-        ...jws.header,
-    };
-    const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
-    let b64 = true;
-    if (extensions.has('b64')) {
-        b64 = parsedProt.b64;
-        if (typeof b64 !== 'boolean') {
-            throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
-        }
-    }
-    const { alg } = joseHeader;
-    if (typeof alg !== 'string' || !alg) {
-        throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
-    }
-    const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms);
-    if (algorithms && !algorithms.has(alg)) {
-        throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
-    }
-    if (b64) {
-        if (typeof jws.payload !== 'string') {
-            throw new errors_js_1.JWSInvalid('JWS Payload must be a string');
-        }
-    }
-    else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
-        throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
-    }
-    let resolvedKey = false;
-    if (typeof key === 'function') {
-        key = await key(parsedProt, jws);
-        resolvedKey = true;
-        (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify');
-        if ((0, is_jwk_js_1.isJWK)(key)) {
-            key = await (0, import_js_1.importJWK)(key, alg);
-        }
-    }
-    else {
-        (0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify');
-    }
-    const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload);
-    let signature;
-    try {
-        signature = (0, base64url_js_1.decode)(jws.signature);
-    }
-    catch {
-        throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature');
-    }
-    const verified = await (0, verify_js_1.default)(alg, key, signature, data);
-    if (!verified) {
-        throw new errors_js_1.JWSSignatureVerificationFailed();
+exports.weakMap = new WeakMap();
+const namedCurveToJOSE = (namedCurve) => {
+    switch (namedCurve) {
+        case 'prime256v1':
+            return 'P-256';
+        case 'secp384r1':
+            return 'P-384';
+        case 'secp521r1':
+            return 'P-521';
+        case 'secp256k1':
+            return 'secp256k1';
+        default:
+            throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation');
     }
-    let payload;
-    if (b64) {
-        try {
-            payload = (0, base64url_js_1.decode)(jws.payload);
-        }
-        catch {
-            throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload');
-        }
+};
+const getNamedCurve = (kee, raw) => {
+    let key;
+    if ((0, webcrypto_js_1.isCryptoKey)(kee)) {
+        key = node_crypto_1.KeyObject.from(kee);
     }
-    else if (typeof jws.payload === 'string') {
-        payload = buffer_utils_js_1.encoder.encode(jws.payload);
+    else if ((0, is_key_object_js_1.default)(kee)) {
+        key = kee;
     }
-    else {
-        payload = jws.payload;
+    else if ((0, is_jwk_js_1.isJWK)(kee)) {
+        return kee.crv;
     }
-    const result = { payload };
-    if (jws.protected !== undefined) {
-        result.protectedHeader = parsedProt;
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types));
     }
-    if (jws.header !== undefined) {
-        result.unprotectedHeader = jws.header;
+    if (key.type === 'secret') {
+        throw new TypeError('only "private" or "public" type keys can be used for this operation');
     }
-    if (resolvedKey) {
-        return { ...result, key };
+    switch (key.asymmetricKeyType) {
+        case 'ed25519':
+        case 'ed448':
+            return `Ed${key.asymmetricKeyType.slice(2)}`;
+        case 'x25519':
+        case 'x448':
+            return `X${key.asymmetricKeyType.slice(1)}`;
+        case 'ec': {
+            const namedCurve = key.asymmetricKeyDetails.namedCurve;
+            if (raw) {
+                return namedCurve;
+            }
+            return namedCurveToJOSE(namedCurve);
+        }
+        default:
+            throw new TypeError('Invalid asymmetric key type for this operation');
     }
-    return result;
-}
+};
+exports["default"] = getNamedCurve;
 
 
 /***/ }),
 
-/***/ 50443:
+/***/ 80723:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GeneralSign = void 0;
-const sign_js_1 = __nccwpck_require__(86170);
-const errors_js_1 = __nccwpck_require__(15974);
-class IndividualSignature {
-    parent;
-    protectedHeader;
-    unprotectedHeader;
-    options;
-    key;
-    constructor(sig, key, options) {
-        this.parent = sig;
-        this.key = key;
-        this.options = options;
-    }
-    setProtectedHeader(protectedHeader) {
-        if (this.protectedHeader) {
-            throw new TypeError('setProtectedHeader can only be called once');
-        }
-        this.protectedHeader = protectedHeader;
-        return this;
-    }
-    setUnprotectedHeader(unprotectedHeader) {
-        if (this.unprotectedHeader) {
-            throw new TypeError('setUnprotectedHeader can only be called once');
+exports["default"] = getSignVerifyKey;
+const node_crypto_1 = __nccwpck_require__(77598);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const jwk = __nccwpck_require__(91229);
+function getSignVerifyKey(alg, key, usage) {
+    if (key instanceof Uint8Array) {
+        if (!alg.startsWith('HS')) {
+            throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
         }
-        this.unprotectedHeader = unprotectedHeader;
-        return this;
-    }
-    addSignature(...args) {
-        return this.parent.addSignature(...args);
-    }
-    sign(...args) {
-        return this.parent.sign(...args);
-    }
-    done() {
-        return this.parent;
+        return (0, node_crypto_1.createSecretKey)(key);
     }
-}
-class GeneralSign {
-    _payload;
-    _signatures = [];
-    constructor(payload) {
-        this._payload = payload;
+    if (key instanceof node_crypto_1.KeyObject) {
+        return key;
     }
-    addSignature(key, options) {
-        const signature = new IndividualSignature(this, key, options);
-        this._signatures.push(signature);
-        return signature;
+    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
+        (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage);
+        return node_crypto_1.KeyObject.from(key);
     }
-    async sign() {
-        if (!this._signatures.length) {
-            throw new errors_js_1.JWSInvalid('at least one signature must be added');
-        }
-        const jws = {
-            signatures: [],
-            payload: '',
-        };
-        for (let i = 0; i < this._signatures.length; i++) {
-            const signature = this._signatures[i];
-            const flattened = new sign_js_1.FlattenedSign(this._payload);
-            flattened.setProtectedHeader(signature.protectedHeader);
-            flattened.setUnprotectedHeader(signature.unprotectedHeader);
-            const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
-            if (i === 0) {
-                jws.payload = payload;
-            }
-            else if (jws.payload !== payload) {
-                throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');
-            }
-            jws.signatures.push(rest);
+    if (jwk.isJWK(key)) {
+        if (alg.startsWith('HS')) {
+            return (0, node_crypto_1.createSecretKey)(Buffer.from(key.k, 'base64url'));
         }
-        return jws;
+        return key;
     }
+    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array', 'JSON Web Key'));
 }
-exports.GeneralSign = GeneralSign;
 
 
 /***/ }),
 
-/***/ 88323:
+/***/ 57399:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.generalVerify = generalVerify;
-const verify_js_1 = __nccwpck_require__(56358);
+exports["default"] = hmacDigest;
 const errors_js_1 = __nccwpck_require__(15974);
-const is_object_js_1 = __nccwpck_require__(92242);
-async function generalVerify(jws, key, options) {
-    if (!(0, is_object_js_1.default)(jws)) {
-        throw new errors_js_1.JWSInvalid('General JWS must be an object');
-    }
-    if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) {
-        throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type');
-    }
-    for (const signature of jws.signatures) {
-        try {
-            return await (0, verify_js_1.flattenedVerify)({
-                header: signature.header,
-                payload: jws.payload,
-                protected: signature.protected,
-                signature: signature.signature,
-            }, key, options);
-        }
-        catch {
-        }
+function hmacDigest(alg) {
+    switch (alg) {
+        case 'HS256':
+            return 'sha256';
+        case 'HS384':
+            return 'sha384';
+        case 'HS512':
+            return 'sha512';
+        default:
+            throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
     }
-    throw new errors_js_1.JWSSignatureVerificationFailed();
 }
 
 
 /***/ }),
 
-/***/ 95339:
+/***/ 7433:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.jwtDecrypt = jwtDecrypt;
-const decrypt_js_1 = __nccwpck_require__(14298);
-const jwt_claims_set_js_1 = __nccwpck_require__(13354);
-const errors_js_1 = __nccwpck_require__(15974);
-async function jwtDecrypt(jwt, key, options) {
-    const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options);
-    const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options);
-    const { protectedHeader } = decrypted;
-    if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
-        throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch');
-    }
-    if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
-        throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch');
-    }
-    if (protectedHeader.aud !== undefined &&
-        JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
-        throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch');
-    }
-    const result = { payload, protectedHeader };
-    if (typeof key === 'function') {
-        return { ...result, key: decrypted.key };
-    }
-    return result;
+exports.types = void 0;
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+exports["default"] = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key);
+const types = ['KeyObject'];
+exports.types = types;
+if (globalThis.CryptoKey || webcrypto_js_1.default?.CryptoKey) {
+    types.push('CryptoKey');
 }
 
 
 /***/ }),
 
-/***/ 38375:
+/***/ 68685:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.EncryptJWT = void 0;
-const encrypt_js_1 = __nccwpck_require__(4434);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const produce_js_1 = __nccwpck_require__(37318);
-class EncryptJWT extends produce_js_1.ProduceJWT {
-    _cek;
-    _iv;
-    _keyManagementParameters;
-    _protectedHeader;
-    _replicateIssuerAsHeader;
-    _replicateSubjectAsHeader;
-    _replicateAudienceAsHeader;
-    setProtectedHeader(protectedHeader) {
-        if (this._protectedHeader) {
-            throw new TypeError('setProtectedHeader can only be called once');
-        }
-        this._protectedHeader = protectedHeader;
-        return this;
-    }
-    setKeyManagementParameters(parameters) {
-        if (this._keyManagementParameters) {
-            throw new TypeError('setKeyManagementParameters can only be called once');
-        }
-        this._keyManagementParameters = parameters;
-        return this;
-    }
-    setContentEncryptionKey(cek) {
-        if (this._cek) {
-            throw new TypeError('setContentEncryptionKey can only be called once');
-        }
-        this._cek = cek;
-        return this;
-    }
-    setInitializationVector(iv) {
-        if (this._iv) {
-            throw new TypeError('setInitializationVector can only be called once');
-        }
-        this._iv = iv;
-        return this;
-    }
-    replicateIssuerAsHeader() {
-        this._replicateIssuerAsHeader = true;
-        return this;
-    }
-    replicateSubjectAsHeader() {
-        this._replicateSubjectAsHeader = true;
-        return this;
-    }
-    replicateAudienceAsHeader() {
-        this._replicateAudienceAsHeader = true;
-        return this;
-    }
-    async encrypt(key, options) {
-        const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
-        if (this._replicateIssuerAsHeader) {
-            this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };
-        }
-        if (this._replicateSubjectAsHeader) {
-            this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };
-        }
-        if (this._replicateAudienceAsHeader) {
-            this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };
-        }
-        enc.setProtectedHeader(this._protectedHeader);
-        if (this._iv) {
-            enc.setInitializationVector(this._iv);
-        }
-        if (this._cek) {
-            enc.setContentEncryptionKey(this._cek);
-        }
-        if (this._keyManagementParameters) {
-            enc.setKeyManagementParameters(this._keyManagementParameters);
-        }
-        return enc.encrypt(key, options);
-    }
-}
-exports.EncryptJWT = EncryptJWT;
+const util = __nccwpck_require__(57975);
+exports["default"] = (obj) => util.types.isKeyObject(obj);
 
 
 /***/ }),
 
-/***/ 37318:
+/***/ 80939:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ProduceJWT = void 0;
-const epoch_js_1 = __nccwpck_require__(40485);
-const is_object_js_1 = __nccwpck_require__(92242);
-const secs_js_1 = __nccwpck_require__(40556);
-function validateInput(label, input) {
-    if (!Number.isFinite(input)) {
-        throw new TypeError(`Invalid ${label} input`);
+const node_crypto_1 = __nccwpck_require__(77598);
+const parse = (key) => {
+    if (key.d) {
+        return (0, node_crypto_1.createPrivateKey)({ format: 'jwk', key });
     }
-    return input;
-}
-class ProduceJWT {
-    _payload;
-    constructor(payload = {}) {
-        if (!(0, is_object_js_1.default)(payload)) {
-            throw new TypeError('JWT Claims Set MUST be an object');
+    return (0, node_crypto_1.createPublicKey)({ format: 'jwk', key });
+};
+exports["default"] = parse;
+
+
+/***/ }),
+
+/***/ 9041:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const node_crypto_1 = __nccwpck_require__(77598);
+const base64url_js_1 = __nccwpck_require__(12635);
+const errors_js_1 = __nccwpck_require__(15974);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const keyToJWK = (key) => {
+    let keyObject;
+    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
+        if (!key.extractable) {
+            throw new TypeError('CryptoKey is not extractable');
         }
-        this._payload = payload;
-    }
-    setIssuer(issuer) {
-        this._payload = { ...this._payload, iss: issuer };
-        return this;
-    }
-    setSubject(subject) {
-        this._payload = { ...this._payload, sub: subject };
-        return this;
-    }
-    setAudience(audience) {
-        this._payload = { ...this._payload, aud: audience };
-        return this;
+        keyObject = node_crypto_1.KeyObject.from(key);
     }
-    setJti(jwtId) {
-        this._payload = { ...this._payload, jti: jwtId };
-        return this;
+    else if ((0, is_key_object_js_1.default)(key)) {
+        keyObject = key;
     }
-    setNotBefore(input) {
-        if (typeof input === 'number') {
-            this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
-        }
-        else if (input instanceof Date) {
-            this._payload = { ...this._payload, nbf: validateInput('setNotBefore', (0, epoch_js_1.default)(input)) };
-        }
-        else {
-            this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) };
-        }
-        return this;
+    else if (key instanceof Uint8Array) {
+        return {
+            kty: 'oct',
+            k: (0, base64url_js_1.encode)(key),
+        };
     }
-    setExpirationTime(input) {
-        if (typeof input === 'number') {
-            this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
-        }
-        else if (input instanceof Date) {
-            this._payload = { ...this._payload, exp: validateInput('setExpirationTime', (0, epoch_js_1.default)(input)) };
-        }
-        else {
-            this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) };
-        }
-        return this;
+    else {
+        throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));
     }
-    setIssuedAt(input) {
-        if (typeof input === 'undefined') {
-            this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) };
-        }
-        else if (input instanceof Date) {
-            this._payload = { ...this._payload, iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(input)) };
-        }
-        else if (typeof input === 'string') {
-            this._payload = {
-                ...this._payload,
-                iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input)),
-            };
-        }
-        else {
-            this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
-        }
-        return this;
+    if (keyObject.type !== 'secret' &&
+        !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
+        throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType');
     }
-}
-exports.ProduceJWT = ProduceJWT;
+    return keyObject.export({ format: 'jwk' });
+};
+exports["default"] = keyToJWK;
 
 
 /***/ }),
 
-/***/ 22713:
+/***/ 70363:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SignJWT = void 0;
-const sign_js_1 = __nccwpck_require__(21760);
+exports["default"] = keyForCrypto;
+const node_crypto_1 = __nccwpck_require__(77598);
+const get_named_curve_js_1 = __nccwpck_require__(65661);
 const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const produce_js_1 = __nccwpck_require__(37318);
-class SignJWT extends produce_js_1.ProduceJWT {
-    _protectedHeader;
-    setProtectedHeader(protectedHeader) {
-        this._protectedHeader = protectedHeader;
-        return this;
+const check_key_length_js_1 = __nccwpck_require__(65142);
+const ecCurveAlgMap = new Map([
+    ['ES256', 'P-256'],
+    ['ES256K', 'secp256k1'],
+    ['ES384', 'P-384'],
+    ['ES512', 'P-521'],
+]);
+function keyForCrypto(alg, key) {
+    let asymmetricKeyType;
+    let asymmetricKeyDetails;
+    let isJWK;
+    if (key instanceof node_crypto_1.KeyObject) {
+        asymmetricKeyType = key.asymmetricKeyType;
+        asymmetricKeyDetails = key.asymmetricKeyDetails;
     }
-    async sign(key, options) {
-        const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
-        sig.setProtectedHeader(this._protectedHeader);
-        if (Array.isArray(this._protectedHeader?.crit) &&
-            this._protectedHeader.crit.includes('b64') &&
-            this._protectedHeader.b64 === false) {
-            throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload');
+    else {
+        isJWK = true;
+        switch (key.kty) {
+            case 'RSA':
+                asymmetricKeyType = 'rsa';
+                break;
+            case 'EC':
+                asymmetricKeyType = 'ec';
+                break;
+            case 'OKP': {
+                if (key.crv === 'Ed25519') {
+                    asymmetricKeyType = 'ed25519';
+                    break;
+                }
+                if (key.crv === 'Ed448') {
+                    asymmetricKeyType = 'ed448';
+                    break;
+                }
+                throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448');
+            }
+            default:
+                throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC');
         }
-        return sig.sign(key, options);
     }
+    let options;
+    switch (alg) {
+        case 'EdDSA':
+            if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) {
+                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448');
+            }
+            break;
+        case 'RS256':
+        case 'RS384':
+        case 'RS512':
+            if (asymmetricKeyType !== 'rsa') {
+                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
+            }
+            (0, check_key_length_js_1.default)(key, alg);
+            break;
+        case 'PS256':
+        case 'PS384':
+        case 'PS512':
+            if (asymmetricKeyType === 'rsa-pss') {
+                const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails;
+                const length = parseInt(alg.slice(-3), 10);
+                if (hashAlgorithm !== undefined &&
+                    (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {
+                    throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`);
+                }
+                if (saltLength !== undefined && saltLength > length >> 3) {
+                    throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`);
+                }
+            }
+            else if (asymmetricKeyType !== 'rsa') {
+                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss');
+            }
+            (0, check_key_length_js_1.default)(key, alg);
+            options = {
+                padding: node_crypto_1.constants.RSA_PKCS1_PSS_PADDING,
+                saltLength: node_crypto_1.constants.RSA_PSS_SALTLEN_DIGEST,
+            };
+            break;
+        case 'ES256':
+        case 'ES256K':
+        case 'ES384':
+        case 'ES512': {
+            if (asymmetricKeyType !== 'ec') {
+                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec');
+            }
+            const actual = (0, get_named_curve_js_1.default)(key);
+            const expected = ecCurveAlgMap.get(alg);
+            if (actual !== expected) {
+                throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);
+            }
+            options = { dsaEncoding: 'ieee-p1363' };
+            break;
+        }
+        default:
+            throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+    }
+    if (isJWK) {
+        return { format: 'jwk', key, ...options };
+    }
+    return options ? { ...options, key } : key;
 }
-exports.SignJWT = SignJWT;
 
 
 /***/ }),
 
-/***/ 40560:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 51276:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.UnsecuredJWT = void 0;
-const base64url = __nccwpck_require__(12635);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const errors_js_1 = __nccwpck_require__(15974);
-const jwt_claims_set_js_1 = __nccwpck_require__(13354);
-const produce_js_1 = __nccwpck_require__(37318);
-class UnsecuredJWT extends produce_js_1.ProduceJWT {
-    encode() {
-        const header = base64url.encode(JSON.stringify({ alg: 'none' }));
-        const payload = base64url.encode(JSON.stringify(this._payload));
-        return `${header}.${payload}.`;
-    }
-    static decode(jwt, options) {
-        if (typeof jwt !== 'string') {
-            throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string');
-        }
-        const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');
-        if (length !== 3 || signature !== '') {
-            throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT');
-        }
-        let header;
-        try {
-            header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader)));
-            if (header.alg !== 'none')
-                throw new Error();
-        }
-        catch {
-            throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT');
-        }
-        const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options);
-        return { payload, header };
-    }
-}
-exports.UnsecuredJWT = UnsecuredJWT;
+exports["default"] = {};
 
 
 /***/ }),
 
-/***/ 35297:
+/***/ 52741:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.jwtVerify = jwtVerify;
-const verify_js_1 = __nccwpck_require__(94212);
-const jwt_claims_set_js_1 = __nccwpck_require__(13354);
-const errors_js_1 = __nccwpck_require__(15974);
-async function jwtVerify(jwt, key, options) {
-    const verified = await (0, verify_js_1.compactVerify)(jwt, key, options);
-    if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
-        throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload');
+exports.decrypt = exports.encrypt = void 0;
+const node_util_1 = __nccwpck_require__(57975);
+const node_crypto_1 = __nccwpck_require__(77598);
+const random_js_1 = __nccwpck_require__(23376);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const base64url_js_1 = __nccwpck_require__(12635);
+const aeskw_js_1 = __nccwpck_require__(76202);
+const check_p2s_js_1 = __nccwpck_require__(88040);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const pbkdf2 = (0, node_util_1.promisify)(node_crypto_1.pbkdf2);
+function getPassword(key, alg) {
+    if ((0, is_key_object_js_1.default)(key)) {
+        return key.export();
     }
-    const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options);
-    const result = { payload, protectedHeader: verified.protectedHeader };
-    if (typeof key === 'function') {
-        return { ...result, key: verified.key };
+    if (key instanceof Uint8Array) {
+        return key;
     }
-    return result;
+    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey');
+        return node_crypto_1.KeyObject.from(key).export();
+    }
+    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));
 }
+const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => {
+    (0, check_p2s_js_1.default)(p2s);
+    const salt = (0, buffer_utils_js_1.p2s)(alg, p2s);
+    const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
+    const password = getPassword(key, alg);
+    const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
+    const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek);
+    return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) };
+};
+exports.encrypt = encrypt;
+const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
+    (0, check_p2s_js_1.default)(p2s);
+    const salt = (0, buffer_utils_js_1.p2s)(alg, p2s);
+    const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
+    const password = getPassword(key, alg);
+    const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
+    return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey);
+};
+exports.decrypt = decrypt;
 
 
 /***/ }),
 
-/***/ 48108:
+/***/ 23376:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.exportSPKI = exportSPKI;
-exports.exportPKCS8 = exportPKCS8;
-exports.exportJWK = exportJWK;
-const asn1_js_1 = __nccwpck_require__(12774);
-const asn1_js_2 = __nccwpck_require__(12774);
-const key_to_jwk_js_1 = __nccwpck_require__(9041);
-async function exportSPKI(key) {
-    return (0, asn1_js_1.toSPKI)(key);
-}
-async function exportPKCS8(key) {
-    return (0, asn1_js_2.toPKCS8)(key);
-}
-async function exportJWK(key) {
-    return (0, key_to_jwk_js_1.default)(key);
-}
+exports["default"] = void 0;
+var node_crypto_1 = __nccwpck_require__(77598);
+Object.defineProperty(exports, "default", ({ enumerable: true, get: function () { return node_crypto_1.randomFillSync; } }));
 
 
 /***/ }),
 
-/***/ 87820:
+/***/ 61129:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.generateKeyPair = generateKeyPair;
-const generate_js_1 = __nccwpck_require__(10088);
-async function generateKeyPair(alg, options) {
-    return (0, generate_js_1.generateKeyPair)(alg, options);
+exports.decrypt = exports.encrypt = void 0;
+const node_crypto_1 = __nccwpck_require__(77598);
+const node_util_1 = __nccwpck_require__(57975);
+const check_key_length_js_1 = __nccwpck_require__(65142);
+const webcrypto_js_1 = __nccwpck_require__(59044);
+const crypto_key_js_1 = __nccwpck_require__(26319);
+const is_key_object_js_1 = __nccwpck_require__(68685);
+const invalid_key_input_js_1 = __nccwpck_require__(16632);
+const is_key_like_js_1 = __nccwpck_require__(7433);
+const checkKey = (key, alg) => {
+    if (key.asymmetricKeyType !== 'rsa') {
+        throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
+    }
+    (0, check_key_length_js_1.default)(key, alg);
+};
+const RSA1_5 = (0, node_util_1.deprecate)(() => node_crypto_1.constants.RSA_PKCS1_PADDING, 'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');
+const resolvePadding = (alg) => {
+    switch (alg) {
+        case 'RSA-OAEP':
+        case 'RSA-OAEP-256':
+        case 'RSA-OAEP-384':
+        case 'RSA-OAEP-512':
+            return node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING;
+        case 'RSA1_5':
+            return RSA1_5();
+        default:
+            return undefined;
+    }
+};
+const resolveOaepHash = (alg) => {
+    switch (alg) {
+        case 'RSA-OAEP':
+            return 'sha1';
+        case 'RSA-OAEP-256':
+            return 'sha256';
+        case 'RSA-OAEP-384':
+            return 'sha384';
+        case 'RSA-OAEP-512':
+            return 'sha512';
+        default:
+            return undefined;
+    }
+};
+function ensureKeyObject(key, alg, ...usages) {
+    if ((0, is_key_object_js_1.default)(key)) {
+        return key;
+    }
+    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
+        (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages);
+        return node_crypto_1.KeyObject.from(key);
+    }
+    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
 }
+const encrypt = (alg, key, cek) => {
+    const padding = resolvePadding(alg);
+    const oaepHash = resolveOaepHash(alg);
+    const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt');
+    checkKey(keyObject, alg);
+    return (0, node_crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek);
+};
+exports.encrypt = encrypt;
+const decrypt = (alg, key, encryptedKey) => {
+    const padding = resolvePadding(alg);
+    const oaepHash = resolveOaepHash(alg);
+    const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt');
+    checkKey(keyObject, alg);
+    return (0, node_crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey);
+};
+exports.decrypt = decrypt;
 
 
 /***/ }),
 
-/***/ 37152:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 95527:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.generateSecret = generateSecret;
-const generate_js_1 = __nccwpck_require__(10088);
-async function generateSecret(alg, options) {
-    return (0, generate_js_1.generateSecret)(alg, options);
-}
+exports["default"] = 'node:crypto';
 
 
 /***/ }),
 
-/***/ 45647:
+/***/ 26966:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.importSPKI = importSPKI;
-exports.importX509 = importX509;
-exports.importPKCS8 = importPKCS8;
-exports.importJWK = importJWK;
-const base64url_js_1 = __nccwpck_require__(12635);
-const asn1_js_1 = __nccwpck_require__(12774);
-const jwk_to_key_js_1 = __nccwpck_require__(80939);
-const errors_js_1 = __nccwpck_require__(15974);
-const is_object_js_1 = __nccwpck_require__(92242);
-async function importSPKI(spki, alg, options) {
-    if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
-        throw new TypeError('"spki" must be SPKI formatted string');
-    }
-    return (0, asn1_js_1.fromSPKI)(spki, alg, options);
-}
-async function importX509(x509, alg, options) {
-    if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {
-        throw new TypeError('"x509" must be X.509 formatted string');
-    }
-    return (0, asn1_js_1.fromX509)(x509, alg, options);
-}
-async function importPKCS8(pkcs8, alg, options) {
-    if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {
-        throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
-    }
-    return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options);
-}
-async function importJWK(jwk, alg) {
-    if (!(0, is_object_js_1.default)(jwk)) {
-        throw new TypeError('JWK must be an object');
-    }
-    alg ||= jwk.alg;
-    switch (jwk.kty) {
-        case 'oct':
-            if (typeof jwk.k !== 'string' || !jwk.k) {
-                throw new TypeError('missing "k" (Key Value) Parameter value');
-            }
-            return (0, base64url_js_1.decode)(jwk.k);
-        case 'RSA':
-            if (jwk.oth !== undefined) {
-                throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
-            }
-        case 'EC':
-        case 'OKP':
-            return (0, jwk_to_key_js_1.default)({ ...jwk, alg });
-        default:
-            throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
+const crypto = __nccwpck_require__(77598);
+const node_util_1 = __nccwpck_require__(57975);
+const dsa_digest_js_1 = __nccwpck_require__(74510);
+const hmac_digest_js_1 = __nccwpck_require__(57399);
+const node_key_js_1 = __nccwpck_require__(70363);
+const get_sign_verify_key_js_1 = __nccwpck_require__(80723);
+const oneShotSign = (0, node_util_1.promisify)(crypto.sign);
+const sign = async (alg, key, data) => {
+    const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign');
+    if (alg.startsWith('HS')) {
+        const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), k);
+        hmac.update(data);
+        return hmac.digest();
     }
-}
+    return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, k));
+};
+exports["default"] = sign;
 
 
 /***/ }),
 
-/***/ 95864:
+/***/ 39106:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.wrap = wrap;
-exports.unwrap = unwrap;
-const encrypt_js_1 = __nccwpck_require__(36286);
-const decrypt_js_1 = __nccwpck_require__(52806);
-const base64url_js_1 = __nccwpck_require__(12635);
-async function wrap(alg, key, cek, iv) {
-    const jweAlgorithm = alg.slice(0, 7);
-    const wrapped = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0));
-    return {
-        encryptedKey: wrapped.ciphertext,
-        iv: (0, base64url_js_1.encode)(wrapped.iv),
-        tag: (0, base64url_js_1.encode)(wrapped.tag),
-    };
-}
-async function unwrap(alg, key, encryptedKey, iv, tag) {
-    const jweAlgorithm = alg.slice(0, 7);
-    return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));
-}
+const node_crypto_1 = __nccwpck_require__(77598);
+const timingSafeEqual = node_crypto_1.timingSafeEqual;
+exports["default"] = timingSafeEqual;
 
 
 /***/ }),
 
-/***/ 45734:
+/***/ 11242:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decoder = exports.encoder = void 0;
-exports.concat = concat;
-exports.p2s = p2s;
-exports.uint64be = uint64be;
-exports.uint32be = uint32be;
-exports.lengthAndInput = lengthAndInput;
-exports.concatKdf = concatKdf;
-const digest_js_1 = __nccwpck_require__(12931);
-exports.encoder = new TextEncoder();
-exports.decoder = new TextDecoder();
-const MAX_INT32 = 2 ** 32;
-function concat(...buffers) {
-    const size = buffers.reduce((acc, { length }) => acc + length, 0);
-    const buf = new Uint8Array(size);
-    let i = 0;
-    for (const buffer of buffers) {
-        buf.set(buffer, i);
-        i += buffer.length;
+const crypto = __nccwpck_require__(77598);
+const node_util_1 = __nccwpck_require__(57975);
+const dsa_digest_js_1 = __nccwpck_require__(74510);
+const node_key_js_1 = __nccwpck_require__(70363);
+const sign_js_1 = __nccwpck_require__(26966);
+const get_sign_verify_key_js_1 = __nccwpck_require__(80723);
+const oneShotVerify = (0, node_util_1.promisify)(crypto.verify);
+const verify = async (alg, key, signature, data) => {
+    const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify');
+    if (alg.startsWith('HS')) {
+        const expected = await (0, sign_js_1.default)(alg, k, data);
+        const actual = signature;
+        try {
+            return crypto.timingSafeEqual(actual, expected);
+        }
+        catch {
+            return false;
+        }
     }
-    return buf;
-}
-function p2s(alg, p2sInput) {
-    return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput);
-}
-function writeUInt32BE(buf, value, offset) {
-    if (value < 0 || value >= MAX_INT32) {
-        throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
+    const algorithm = (0, dsa_digest_js_1.default)(alg);
+    const keyInput = (0, node_key_js_1.default)(alg, k);
+    try {
+        return await oneShotVerify(algorithm, data, keyInput, signature);
     }
-    buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);
-}
-function uint64be(value) {
-    const high = Math.floor(value / MAX_INT32);
-    const low = value % MAX_INT32;
-    const buf = new Uint8Array(8);
-    writeUInt32BE(buf, high, 0);
-    writeUInt32BE(buf, low, 4);
-    return buf;
-}
-function uint32be(value) {
-    const buf = new Uint8Array(4);
-    writeUInt32BE(buf, value);
-    return buf;
-}
-function lengthAndInput(input) {
-    return concat(uint32be(input.length), input);
-}
-async function concatKdf(secret, bits, value) {
-    const iterations = Math.ceil((bits >> 3) / 32);
-    const res = new Uint8Array(iterations * 32);
-    for (let iter = 0; iter < iterations; iter++) {
-        const buf = new Uint8Array(4 + secret.length + value.length);
-        buf.set(uint32be(iter + 1));
-        buf.set(secret, 4);
-        buf.set(value, 4 + secret.length);
-        res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32);
+    catch {
+        return false;
     }
-    return res.slice(0, bits >> 3);
-}
+};
+exports["default"] = verify;
 
 
 /***/ }),
 
-/***/ 87937:
+/***/ 59044:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.bitLength = bitLength;
-const errors_js_1 = __nccwpck_require__(15974);
-const random_js_1 = __nccwpck_require__(23376);
-function bitLength(alg) {
-    switch (alg) {
-        case 'A128GCM':
-            return 128;
-        case 'A192GCM':
-            return 192;
-        case 'A256GCM':
-        case 'A128CBC-HS256':
-            return 256;
-        case 'A192CBC-HS384':
-            return 384;
-        case 'A256CBC-HS512':
-            return 512;
-        default:
-            throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
-    }
-}
-exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3));
+exports.isCryptoKey = void 0;
+const crypto = __nccwpck_require__(77598);
+const util = __nccwpck_require__(57975);
+const webcrypto = crypto.webcrypto;
+exports["default"] = webcrypto;
+const isCryptoKey = (key) => util.types.isCryptoKey(key);
+exports.isCryptoKey = isCryptoKey;
 
 
 /***/ }),
 
-/***/ 63351:
+/***/ 78305:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-const errors_js_1 = __nccwpck_require__(15974);
-const iv_js_1 = __nccwpck_require__(56565);
-const checkIvLength = (enc, iv) => {
-    if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) {
-        throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length');
-    }
-};
-exports["default"] = checkIvLength;
+exports.decode = exports.encode = void 0;
+const base64url = __nccwpck_require__(12635);
+exports.encode = base64url.encode;
+exports.decode = base64url.decode;
 
 
 /***/ }),
 
-/***/ 29555:
+/***/ 60002:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.checkKeyTypeWithJwk = void 0;
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const jwk = __nccwpck_require__(91229);
-const tag = (key) => key?.[Symbol.toStringTag];
-const jwkMatchesOp = (alg, key, usage) => {
-    if (key.use !== undefined && key.use !== 'sig') {
-        throw new TypeError('Invalid key for this operation, when present its use must be sig');
-    }
-    if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {
-        throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);
-    }
-    if (key.alg !== undefined && key.alg !== alg) {
-        throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);
-    }
-    return true;
-};
-const symmetricTypeCheck = (alg, key, usage, allowJwk) => {
-    if (key instanceof Uint8Array)
-        return;
-    if (allowJwk && jwk.isJWK(key)) {
-        if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
-            return;
-        throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
-    }
-    if (!(0, is_key_like_js_1.default)(key)) {
-        throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));
-    }
-    if (key.type !== 'secret') {
-        throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
-    }
-};
-const asymmetricTypeCheck = (alg, key, usage, allowJwk) => {
-    if (allowJwk && jwk.isJWK(key)) {
-        switch (usage) {
-            case 'sign':
-                if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
-                    return;
-                throw new TypeError(`JSON Web Key for this operation be a private JWK`);
-            case 'verify':
-                if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
-                    return;
-                throw new TypeError(`JSON Web Key for this operation be a public JWK`);
-        }
-    }
-    if (!(0, is_key_like_js_1.default)(key)) {
-        throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, allowJwk ? 'JSON Web Key' : null));
-    }
-    if (key.type === 'secret') {
-        throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
-    }
-    if (usage === 'sign' && key.type === 'public') {
-        throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
-    }
-    if (usage === 'decrypt' && key.type === 'public') {
-        throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
-    }
-    if (key.algorithm && usage === 'verify' && key.type === 'private') {
-        throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
+exports.decodeJwt = decodeJwt;
+const base64url_js_1 = __nccwpck_require__(78305);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const is_object_js_1 = __nccwpck_require__(92242);
+const errors_js_1 = __nccwpck_require__(15974);
+function decodeJwt(jwt) {
+    if (typeof jwt !== 'string')
+        throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
+    const { 1: payload, length } = jwt.split('.');
+    if (length === 5)
+        throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
+    if (length !== 3)
+        throw new errors_js_1.JWTInvalid('Invalid JWT');
+    if (!payload)
+        throw new errors_js_1.JWTInvalid('JWTs must contain a payload');
+    let decoded;
+    try {
+        decoded = (0, base64url_js_1.decode)(payload);
     }
-    if (key.algorithm && usage === 'encrypt' && key.type === 'private') {
-        throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
+    catch {
+        throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload');
     }
-};
-function checkKeyType(allowJwk, alg, key, usage) {
-    const symmetric = alg.startsWith('HS') ||
-        alg === 'dir' ||
-        alg.startsWith('PBES2') ||
-        /^A\d{3}(?:GCM)?KW$/.test(alg);
-    if (symmetric) {
-        symmetricTypeCheck(alg, key, usage, allowJwk);
+    let result;
+    try {
+        result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded));
     }
-    else {
-        asymmetricTypeCheck(alg, key, usage, allowJwk);
+    catch {
+        throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON');
     }
+    if (!(0, is_object_js_1.default)(result))
+        throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set');
+    return result;
 }
-exports["default"] = checkKeyType.bind(undefined, false);
-exports.checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);
 
 
 /***/ }),
 
-/***/ 88040:
+/***/ 14704:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = checkP2s;
-const errors_js_1 = __nccwpck_require__(15974);
-function checkP2s(p2s) {
-    if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
-        throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets');
+exports.decodeProtectedHeader = decodeProtectedHeader;
+const base64url_js_1 = __nccwpck_require__(78305);
+const buffer_utils_js_1 = __nccwpck_require__(45734);
+const is_object_js_1 = __nccwpck_require__(92242);
+function decodeProtectedHeader(token) {
+    let protectedB64u;
+    if (typeof token === 'string') {
+        const parts = token.split('.');
+        if (parts.length === 3 || parts.length === 5) {
+            ;
+            [protectedB64u] = parts;
+        }
+    }
+    else if (typeof token === 'object' && token) {
+        if ('protected' in token) {
+            protectedB64u = token.protected;
+        }
+        else {
+            throw new TypeError('Token does not contain a Protected Header');
+        }
+    }
+    try {
+        if (typeof protectedB64u !== 'string' || !protectedB64u) {
+            throw new Error();
+        }
+        const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u)));
+        if (!(0, is_object_js_1.default)(result)) {
+            throw new Error();
+        }
+        return result;
+    }
+    catch {
+        throw new TypeError('Invalid Token or Protected Header formatting');
     }
 }
 
 
 /***/ }),
 
-/***/ 26319:
+/***/ 15974:
 /***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.checkSigCryptoKey = checkSigCryptoKey;
-exports.checkEncCryptoKey = checkEncCryptoKey;
-function unusable(name, prop = 'algorithm.name') {
-    return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
+exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0;
+class JOSEError extends Error {
+    static code = 'ERR_JOSE_GENERIC';
+    code = 'ERR_JOSE_GENERIC';
+    constructor(message, options) {
+        super(message, options);
+        this.name = this.constructor.name;
+        Error.captureStackTrace?.(this, this.constructor);
+    }
 }
-function isAlgorithm(algorithm, name) {
-    return algorithm.name === name;
+exports.JOSEError = JOSEError;
+class JWTClaimValidationFailed extends JOSEError {
+    static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
+    code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
+    claim;
+    reason;
+    payload;
+    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
+        super(message, { cause: { claim, reason, payload } });
+        this.claim = claim;
+        this.reason = reason;
+        this.payload = payload;
+    }
 }
-function getHashLength(hash) {
-    return parseInt(hash.name.slice(4), 10);
+exports.JWTClaimValidationFailed = JWTClaimValidationFailed;
+class JWTExpired extends JOSEError {
+    static code = 'ERR_JWT_EXPIRED';
+    code = 'ERR_JWT_EXPIRED';
+    claim;
+    reason;
+    payload;
+    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
+        super(message, { cause: { claim, reason, payload } });
+        this.claim = claim;
+        this.reason = reason;
+        this.payload = payload;
+    }
 }
-function getNamedCurve(alg) {
-    switch (alg) {
-        case 'ES256':
-            return 'P-256';
-        case 'ES384':
-            return 'P-384';
-        case 'ES512':
-            return 'P-521';
-        default:
-            throw new Error('unreachable');
+exports.JWTExpired = JWTExpired;
+class JOSEAlgNotAllowed extends JOSEError {
+    static code = 'ERR_JOSE_ALG_NOT_ALLOWED';
+    code = 'ERR_JOSE_ALG_NOT_ALLOWED';
+}
+exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed;
+class JOSENotSupported extends JOSEError {
+    static code = 'ERR_JOSE_NOT_SUPPORTED';
+    code = 'ERR_JOSE_NOT_SUPPORTED';
+}
+exports.JOSENotSupported = JOSENotSupported;
+class JWEDecryptionFailed extends JOSEError {
+    static code = 'ERR_JWE_DECRYPTION_FAILED';
+    code = 'ERR_JWE_DECRYPTION_FAILED';
+    constructor(message = 'decryption operation failed', options) {
+        super(message, options);
     }
 }
-function checkUsage(key, usages) {
-    if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
-        let msg = 'CryptoKey does not support this operation, its usages must include ';
-        if (usages.length > 2) {
-            const last = usages.pop();
-            msg += `one of ${usages.join(', ')}, or ${last}.`;
-        }
-        else if (usages.length === 2) {
-            msg += `one of ${usages[0]} or ${usages[1]}.`;
-        }
-        else {
-            msg += `${usages[0]}.`;
-        }
-        throw new TypeError(msg);
+exports.JWEDecryptionFailed = JWEDecryptionFailed;
+class JWEInvalid extends JOSEError {
+    static code = 'ERR_JWE_INVALID';
+    code = 'ERR_JWE_INVALID';
+}
+exports.JWEInvalid = JWEInvalid;
+class JWSInvalid extends JOSEError {
+    static code = 'ERR_JWS_INVALID';
+    code = 'ERR_JWS_INVALID';
+}
+exports.JWSInvalid = JWSInvalid;
+class JWTInvalid extends JOSEError {
+    static code = 'ERR_JWT_INVALID';
+    code = 'ERR_JWT_INVALID';
+}
+exports.JWTInvalid = JWTInvalid;
+class JWKInvalid extends JOSEError {
+    static code = 'ERR_JWK_INVALID';
+    code = 'ERR_JWK_INVALID';
+}
+exports.JWKInvalid = JWKInvalid;
+class JWKSInvalid extends JOSEError {
+    static code = 'ERR_JWKS_INVALID';
+    code = 'ERR_JWKS_INVALID';
+}
+exports.JWKSInvalid = JWKSInvalid;
+class JWKSNoMatchingKey extends JOSEError {
+    static code = 'ERR_JWKS_NO_MATCHING_KEY';
+    code = 'ERR_JWKS_NO_MATCHING_KEY';
+    constructor(message = 'no applicable key found in the JSON Web Key Set', options) {
+        super(message, options);
     }
 }
-function checkSigCryptoKey(key, alg, ...usages) {
-    switch (alg) {
-        case 'HS256':
-        case 'HS384':
-        case 'HS512': {
-            if (!isAlgorithm(key.algorithm, 'HMAC'))
-                throw unusable('HMAC');
-            const expected = parseInt(alg.slice(2), 10);
-            const actual = getHashLength(key.algorithm.hash);
-            if (actual !== expected)
-                throw unusable(`SHA-${expected}`, 'algorithm.hash');
-            break;
-        }
-        case 'RS256':
-        case 'RS384':
-        case 'RS512': {
-            if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
-                throw unusable('RSASSA-PKCS1-v1_5');
-            const expected = parseInt(alg.slice(2), 10);
-            const actual = getHashLength(key.algorithm.hash);
-            if (actual !== expected)
-                throw unusable(`SHA-${expected}`, 'algorithm.hash');
-            break;
-        }
-        case 'PS256':
-        case 'PS384':
-        case 'PS512': {
-            if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
-                throw unusable('RSA-PSS');
-            const expected = parseInt(alg.slice(2), 10);
-            const actual = getHashLength(key.algorithm.hash);
-            if (actual !== expected)
-                throw unusable(`SHA-${expected}`, 'algorithm.hash');
-            break;
-        }
-        case 'EdDSA': {
-            if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
-                throw unusable('Ed25519 or Ed448');
-            }
-            break;
-        }
-        case 'ES256':
-        case 'ES384':
-        case 'ES512': {
-            if (!isAlgorithm(key.algorithm, 'ECDSA'))
-                throw unusable('ECDSA');
-            const expected = getNamedCurve(alg);
-            const actual = key.algorithm.namedCurve;
-            if (actual !== expected)
-                throw unusable(expected, 'algorithm.namedCurve');
-            break;
-        }
-        default:
-            throw new TypeError('CryptoKey does not support this operation');
+exports.JWKSNoMatchingKey = JWKSNoMatchingKey;
+class JWKSMultipleMatchingKeys extends JOSEError {
+    [Symbol.asyncIterator];
+    static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
+    code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
+    constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {
+        super(message, options);
     }
-    checkUsage(key, usages);
 }
-function checkEncCryptoKey(key, alg, ...usages) {
-    switch (alg) {
-        case 'A128GCM':
-        case 'A192GCM':
-        case 'A256GCM': {
-            if (!isAlgorithm(key.algorithm, 'AES-GCM'))
-                throw unusable('AES-GCM');
-            const expected = parseInt(alg.slice(1, 4), 10);
-            const actual = key.algorithm.length;
-            if (actual !== expected)
-                throw unusable(expected, 'algorithm.length');
-            break;
-        }
-        case 'A128KW':
-        case 'A192KW':
-        case 'A256KW': {
-            if (!isAlgorithm(key.algorithm, 'AES-KW'))
-                throw unusable('AES-KW');
-            const expected = parseInt(alg.slice(1, 4), 10);
-            const actual = key.algorithm.length;
-            if (actual !== expected)
-                throw unusable(expected, 'algorithm.length');
-            break;
-        }
-        case 'ECDH': {
-            switch (key.algorithm.name) {
-                case 'ECDH':
-                case 'X25519':
-                case 'X448':
-                    break;
-                default:
-                    throw unusable('ECDH, X25519, or X448');
-            }
-            break;
-        }
-        case 'PBES2-HS256+A128KW':
-        case 'PBES2-HS384+A192KW':
-        case 'PBES2-HS512+A256KW':
-            if (!isAlgorithm(key.algorithm, 'PBKDF2'))
-                throw unusable('PBKDF2');
-            break;
-        case 'RSA-OAEP':
-        case 'RSA-OAEP-256':
-        case 'RSA-OAEP-384':
-        case 'RSA-OAEP-512': {
-            if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))
-                throw unusable('RSA-OAEP');
-            const expected = parseInt(alg.slice(9), 10) || 1;
-            const actual = getHashLength(key.algorithm.hash);
-            if (actual !== expected)
-                throw unusable(`SHA-${expected}`, 'algorithm.hash');
-            break;
-        }
-        default:
-            throw new TypeError('CryptoKey does not support this operation');
+exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys;
+class JWKSTimeout extends JOSEError {
+    static code = 'ERR_JWKS_TIMEOUT';
+    code = 'ERR_JWKS_TIMEOUT';
+    constructor(message = 'request timed out', options) {
+        super(message, options);
+    }
+}
+exports.JWKSTimeout = JWKSTimeout;
+class JWSSignatureVerificationFailed extends JOSEError {
+    static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
+    code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
+    constructor(message = 'signature verification failed', options) {
+        super(message, options);
     }
-    checkUsage(key, usages);
 }
+exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed;
 
 
 /***/ }),
 
-/***/ 56243:
+/***/ 25021:
 /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-const aeskw_js_1 = __nccwpck_require__(76202);
-const ECDH = __nccwpck_require__(43359);
-const pbes2kw_js_1 = __nccwpck_require__(52741);
-const rsaes_js_1 = __nccwpck_require__(61129);
-const base64url_js_1 = __nccwpck_require__(12635);
-const normalize_key_js_1 = __nccwpck_require__(51276);
-const errors_js_1 = __nccwpck_require__(15974);
-const cek_js_1 = __nccwpck_require__(87937);
-const import_js_1 = __nccwpck_require__(45647);
-const check_key_type_js_1 = __nccwpck_require__(29555);
-const is_object_js_1 = __nccwpck_require__(92242);
-const aesgcmkw_js_1 = __nccwpck_require__(95864);
-async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
-    (0, check_key_type_js_1.default)(alg, key, 'decrypt');
-    key = (await normalize_key_js_1.default.normalizePrivateKey?.(key, alg)) || key;
-    switch (alg) {
-        case 'dir': {
-            if (encryptedKey !== undefined)
-                throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key');
-            return key;
-        }
-        case 'ECDH-ES':
-            if (encryptedKey !== undefined)
-                throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key');
-        case 'ECDH-ES+A128KW':
-        case 'ECDH-ES+A192KW':
-        case 'ECDH-ES+A256KW': {
-            if (!(0, is_object_js_1.default)(joseHeader.epk))
-                throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
-            if (!ECDH.ecdhAllowed(key))
-                throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
-            const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg);
-            let partyUInfo;
-            let partyVInfo;
-            if (joseHeader.apu !== undefined) {
-                if (typeof joseHeader.apu !== 'string')
-                    throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
-                try {
-                    partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu);
-                }
-                catch {
-                    throw new errors_js_1.JWEInvalid('Failed to base64url decode the apu');
-                }
-            }
-            if (joseHeader.apv !== undefined) {
-                if (typeof joseHeader.apv !== 'string')
-                    throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
-                try {
-                    partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv);
-                }
-                catch {
-                    throw new errors_js_1.JWEInvalid('Failed to base64url decode the apv');
-                }
-            }
-            const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
-            if (alg === 'ECDH-ES')
-                return sharedSecret;
-            if (encryptedKey === undefined)
-                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
-            return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey);
-        }
-        case 'RSA1_5':
-        case 'RSA-OAEP':
-        case 'RSA-OAEP-256':
-        case 'RSA-OAEP-384':
-        case 'RSA-OAEP-512': {
-            if (encryptedKey === undefined)
-                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
-            return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey);
-        }
-        case 'PBES2-HS256+A128KW':
-        case 'PBES2-HS384+A192KW':
-        case 'PBES2-HS512+A256KW': {
-            if (encryptedKey === undefined)
-                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
-            if (typeof joseHeader.p2c !== 'number')
-                throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
-            const p2cLimit = options?.maxPBES2Count || 10_000;
-            if (joseHeader.p2c > p2cLimit)
-                throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
-            if (typeof joseHeader.p2s !== 'string')
-                throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
-            let p2s;
-            try {
-                p2s = (0, base64url_js_1.decode)(joseHeader.p2s);
-            }
-            catch {
-                throw new errors_js_1.JWEInvalid('Failed to base64url decode the p2s');
-            }
-            return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s);
-        }
-        case 'A128KW':
-        case 'A192KW':
-        case 'A256KW': {
-            if (encryptedKey === undefined)
-                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
-            return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey);
-        }
-        case 'A128GCMKW':
-        case 'A192GCMKW':
-        case 'A256GCMKW': {
-            if (encryptedKey === undefined)
-                throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing');
-            if (typeof joseHeader.iv !== 'string')
-                throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
-            if (typeof joseHeader.tag !== 'string')
-                throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
-            let iv;
-            try {
-                iv = (0, base64url_js_1.decode)(joseHeader.iv);
-            }
-            catch {
-                throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv');
-            }
-            let tag;
-            try {
-                tag = (0, base64url_js_1.decode)(joseHeader.tag);
-            }
-            catch {
-                throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag');
-            }
-            return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag);
-        }
-        default: {
-            throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
-        }
+const runtime_js_1 = __nccwpck_require__(95527);
+exports["default"] = runtime_js_1.default;
+
+
+/***/ }),
+
+/***/ 95947:
+/***/ (function(module, exports) {
+
+(function(){
+
+    // Copyright (c) 2005  Tom Wu
+    // All Rights Reserved.
+    // See "LICENSE" for details.
+
+    // Basic JavaScript BN library - subset useful for RSA encryption.
+
+    // Bits per digit
+    var dbits;
+
+    // JavaScript engine analysis
+    var canary = 0xdeadbeefcafe;
+    var j_lm = ((canary&0xffffff)==0xefcafe);
+
+    // (public) Constructor
+    function BigInteger(a,b,c) {
+      if(a != null)
+        if("number" == typeof a) this.fromNumber(a,b,c);
+        else if(b == null && "string" != typeof a) this.fromString(a,256);
+        else this.fromString(a,b);
+    }
+
+    // return new, unset BigInteger
+    function nbi() { return new BigInteger(null); }
+
+    // am: Compute w_j += (x*this_i), propagate carries,
+    // c is initial carry, returns final carry.
+    // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
+    // We need to select the fastest one that works in this environment.
+
+    // am1: use a single mult and divide to get the high bits,
+    // max digit bits should be 26 because
+    // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
+    function am1(i,x,w,j,c,n) {
+      while(--n >= 0) {
+        var v = x*this[i++]+w[j]+c;
+        c = Math.floor(v/0x4000000);
+        w[j++] = v&0x3ffffff;
+      }
+      return c;
+    }
+    // am2 avoids a big mult-and-extract completely.
+    // Max digit bits should be <= 30 because we do bitwise ops
+    // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
+    function am2(i,x,w,j,c,n) {
+      var xl = x&0x7fff, xh = x>>15;
+      while(--n >= 0) {
+        var l = this[i]&0x7fff;
+        var h = this[i++]>>15;
+        var m = xh*l+h*xl;
+        l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
+        c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
+        w[j++] = l&0x3fffffff;
+      }
+      return c;
+    }
+    // Alternately, set max digit bits to 28 since some
+    // browsers slow down when dealing with 32-bit numbers.
+    function am3(i,x,w,j,c,n) {
+      var xl = x&0x3fff, xh = x>>14;
+      while(--n >= 0) {
+        var l = this[i]&0x3fff;
+        var h = this[i++]>>14;
+        var m = xh*l+h*xl;
+        l = xl*l+((m&0x3fff)<<14)+w[j]+c;
+        c = (l>>28)+(m>>14)+xh*h;
+        w[j++] = l&0xfffffff;
+      }
+      return c;
+    }
+    var inBrowser = typeof navigator !== "undefined";
+    if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
+      BigInteger.prototype.am = am2;
+      dbits = 30;
+    }
+    else if(inBrowser && j_lm && (navigator.appName != "Netscape")) {
+      BigInteger.prototype.am = am1;
+      dbits = 26;
+    }
+    else { // Mozilla/Netscape seems to prefer am3
+      BigInteger.prototype.am = am3;
+      dbits = 28;
     }
-}
-exports["default"] = decryptKeyManagement;
 
+    BigInteger.prototype.DB = dbits;
+    BigInteger.prototype.DM = ((1< {
+    // Digit conversions
+    var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
+    var BI_RC = new Array();
+    var rr,vv;
+    rr = "0".charCodeAt(0);
+    for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
+    rr = "a".charCodeAt(0);
+    for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
+    rr = "A".charCodeAt(0);
+    for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
 
-"use strict";
+    function int2char(n) { return BI_RM.charAt(n); }
+    function intAt(s,i) {
+      var c = BI_RC[s.charCodeAt(i)];
+      return (c==null)?-1:c;
+    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const aeskw_js_1 = __nccwpck_require__(76202);
-const ECDH = __nccwpck_require__(43359);
-const pbes2kw_js_1 = __nccwpck_require__(52741);
-const rsaes_js_1 = __nccwpck_require__(61129);
-const base64url_js_1 = __nccwpck_require__(12635);
-const normalize_key_js_1 = __nccwpck_require__(51276);
-const cek_js_1 = __nccwpck_require__(87937);
-const errors_js_1 = __nccwpck_require__(15974);
-const export_js_1 = __nccwpck_require__(48108);
-const check_key_type_js_1 = __nccwpck_require__(29555);
-const aesgcmkw_js_1 = __nccwpck_require__(95864);
-async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
-    let encryptedKey;
-    let parameters;
-    let cek;
-    (0, check_key_type_js_1.default)(alg, key, 'encrypt');
-    key = (await normalize_key_js_1.default.normalizePublicKey?.(key, alg)) || key;
-    switch (alg) {
-        case 'dir': {
-            cek = key;
-            break;
-        }
-        case 'ECDH-ES':
-        case 'ECDH-ES+A128KW':
-        case 'ECDH-ES+A192KW':
-        case 'ECDH-ES+A256KW': {
-            if (!ECDH.ecdhAllowed(key)) {
-                throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
-            }
-            const { apu, apv } = providedParameters;
-            let { epk: ephemeralKey } = providedParameters;
-            ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey;
-            const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey);
-            const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
-            parameters = { epk: { x, crv, kty } };
-            if (kty === 'EC')
-                parameters.epk.y = y;
-            if (apu)
-                parameters.apu = (0, base64url_js_1.encode)(apu);
-            if (apv)
-                parameters.apv = (0, base64url_js_1.encode)(apv);
-            if (alg === 'ECDH-ES') {
-                cek = sharedSecret;
-                break;
-            }
-            cek = providedCek || (0, cek_js_1.default)(enc);
-            const kwAlg = alg.slice(-6);
-            encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek);
-            break;
-        }
-        case 'RSA1_5':
-        case 'RSA-OAEP':
-        case 'RSA-OAEP-256':
-        case 'RSA-OAEP-384':
-        case 'RSA-OAEP-512': {
-            cek = providedCek || (0, cek_js_1.default)(enc);
-            encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek);
-            break;
-        }
-        case 'PBES2-HS256+A128KW':
-        case 'PBES2-HS384+A192KW':
-        case 'PBES2-HS512+A256KW': {
-            cek = providedCek || (0, cek_js_1.default)(enc);
-            const { p2c, p2s } = providedParameters;
-            ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s));
-            break;
-        }
-        case 'A128KW':
-        case 'A192KW':
-        case 'A256KW': {
-            cek = providedCek || (0, cek_js_1.default)(enc);
-            encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek);
-            break;
-        }
-        case 'A128GCMKW':
-        case 'A192GCMKW':
-        case 'A256GCMKW': {
-            cek = providedCek || (0, cek_js_1.default)(enc);
-            const { iv } = providedParameters;
-            ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv));
-            break;
+    // (protected) copy this to r
+    function bnpCopyTo(r) {
+      for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
+      r.t = this.t;
+      r.s = this.s;
+    }
+
+    // (protected) set from integer value x, -DV <= x < DV
+    function bnpFromInt(x) {
+      this.t = 1;
+      this.s = (x<0)?-1:0;
+      if(x > 0) this[0] = x;
+      else if(x < -1) this[0] = x+this.DV;
+      else this.t = 0;
+    }
+
+    // return bigint initialized to value
+    function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
+
+    // (protected) set from string and radix
+    function bnpFromString(s,b) {
+      var k;
+      if(b == 16) k = 4;
+      else if(b == 8) k = 3;
+      else if(b == 256) k = 8; // byte array
+      else if(b == 2) k = 1;
+      else if(b == 32) k = 5;
+      else if(b == 4) k = 2;
+      else { this.fromRadix(s,b); return; }
+      this.t = 0;
+      this.s = 0;
+      var i = s.length, mi = false, sh = 0;
+      while(--i >= 0) {
+        var x = (k==8)?s[i]&0xff:intAt(s,i);
+        if(x < 0) {
+          if(s.charAt(i) == "-") mi = true;
+          continue;
         }
-        default: {
-            throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+        mi = false;
+        if(sh == 0)
+          this[this.t++] = x;
+        else if(sh+k > this.DB) {
+          this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));
         }
+        else
+          this[this.t-1] |= x<= this.DB) sh -= this.DB;
+      }
+      if(k == 8 && (s[0]&0x80) != 0) {
+        this.s = -1;
+        if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t;
+    }
 
-/***/ }),
+    // (public) return string representation in given radix
+    function bnToString(b) {
+      if(this.s < 0) return "-"+this.negate().toString(b);
+      var k;
+      if(b == 16) k = 4;
+      else if(b == 8) k = 3;
+      else if(b == 2) k = 1;
+      else if(b == 32) k = 5;
+      else if(b == 4) k = 2;
+      else return this.toRadix(b);
+      var km = (1< 0) {
+        if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
+        while(i >= 0) {
+          if(p < k) {
+            d = (this[i]&((1<>(p+=this.DB-k);
+          }
+          else {
+            d = (this[i]>>(p-=k))&km;
+            if(p <= 0) { p += this.DB; --i; }
+          }
+          if(d > 0) m = true;
+          if(m) r += int2char(d);
+        }
+      }
+      return m?r:"0";
+    }
 
-/***/ 40485:
-/***/ ((__unused_webpack_module, exports) => {
+    // (public) -this
+    function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
 
-"use strict";
+    // (public) |this|
+    function bnAbs() { return (this.s<0)?this.negate():this; }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = (date) => Math.floor(date.getTime() / 1000);
+    // (public) return + if this > a, - if this < a, 0 if equal
+    function bnCompareTo(a) {
+      var r = this.s-a.s;
+      if(r != 0) return r;
+      var i = this.t;
+      r = i-a.t;
+      if(r != 0) return (this.s<0)?-r:r;
+      while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
+      return 0;
+    }
 
+    // returns bit length of the integer x
+    function nbits(x) {
+      var r = 1, t;
+      if((t=x>>>16) != 0) { x = t; r += 16; }
+      if((t=x>>8) != 0) { x = t; r += 8; }
+      if((t=x>>4) != 0) { x = t; r += 4; }
+      if((t=x>>2) != 0) { x = t; r += 2; }
+      if((t=x>>1) != 0) { x = t; r += 1; }
+      return r;
+    }
 
-/***/ }),
+    // (public) return the number of bits in "this"
+    function bnBitLength() {
+      if(this.t <= 0) return 0;
+      return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
+    }
 
-/***/ 16632:
-/***/ ((__unused_webpack_module, exports) => {
+    // (protected) r = this << n*DB
+    function bnpDLShiftTo(n,r) {
+      var i;
+      for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
+      for(i = n-1; i >= 0; --i) r[i] = 0;
+      r.t = this.t+n;
+      r.s = this.s;
+    }
 
-"use strict";
+    // (protected) r = this >> n*DB
+    function bnpDRShiftTo(n,r) {
+      for(var i = n; i < this.t; ++i) r[i-n] = this[i];
+      r.t = Math.max(this.t-n,0);
+      r.s = this.s;
+    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.withAlg = withAlg;
-function message(msg, actual, ...types) {
-    types = types.filter(Boolean);
-    if (types.length > 2) {
-        const last = types.pop();
-        msg += `one of type ${types.join(', ')}, or ${last}.`;
+    // (protected) r = this << n
+    function bnpLShiftTo(n,r) {
+      var bs = n%this.DB;
+      var cbs = this.DB-bs;
+      var bm = (1<= 0; --i) {
+        r[i+ds+1] = (this[i]>>cbs)|c;
+        c = (this[i]&bm)<= 0; --i) r[i] = 0;
+      r[ds] = c;
+      r.t = this.t+ds+1;
+      r.s = this.s;
+      r.clamp();
     }
-    else if (types.length === 2) {
-        msg += `one of type ${types[0]} or ${types[1]}.`;
+
+    // (protected) r = this >> n
+    function bnpRShiftTo(n,r) {
+      r.s = this.s;
+      var ds = Math.floor(n/this.DB);
+      if(ds >= this.t) { r.t = 0; return; }
+      var bs = n%this.DB;
+      var cbs = this.DB-bs;
+      var bm = (1<>bs;
+      for(var i = ds+1; i < this.t; ++i) {
+        r[i-ds-1] |= (this[i]&bm)<>bs;
+      }
+      if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB;
+      }
+      if(a.t < this.t) {
+        c -= a.s;
+        while(i < this.t) {
+          c += this[i];
+          r[i++] = c&this.DM;
+          c >>= this.DB;
+        }
+        c += this.s;
+      }
+      else {
+        c += this.s;
+        while(i < a.t) {
+          c -= a[i];
+          r[i++] = c&this.DM;
+          c >>= this.DB;
+        }
+        c -= a.s;
+      }
+      r.s = (c<0)?-1:0;
+      if(c < -1) r[i++] = this.DV+c;
+      else if(c > 0) r[i++] = c;
+      r.t = i;
+      r.clamp();
     }
-    if (actual == null) {
-        msg += ` Received ${actual}`;
+
+    // (protected) r = this * a, r != this,a (HAC 14.12)
+    // "this" should be the larger one if appropriate.
+    function bnpMultiplyTo(a,r) {
+      var x = this.abs(), y = a.abs();
+      var i = x.t;
+      r.t = i+y.t;
+      while(--i >= 0) r[i] = 0;
+      for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
+      r.s = 0;
+      r.clamp();
+      if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
     }
-    else if (typeof actual === 'function' && actual.name) {
-        msg += ` Received function ${actual.name}`;
+
+    // (protected) r = this^2, r != this (HAC 14.16)
+    function bnpSquareTo(r) {
+      var x = this.abs();
+      var i = r.t = 2*x.t;
+      while(--i >= 0) r[i] = 0;
+      for(i = 0; i < x.t-1; ++i) {
+        var c = x.am(i,x[i],r,2*i,0,1);
+        if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
+          r[i+x.t] -= x.DV;
+          r[i+x.t+1] = 1;
+        }
+      }
+      if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
+      r.s = 0;
+      r.clamp();
     }
-    else if (typeof actual === 'object' && actual != null) {
-        if (actual.constructor?.name) {
-            msg += ` Received an instance of ${actual.constructor.name}`;
+
+    // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
+    // r != q, this != m.  q or r may be null.
+    function bnpDivRemTo(m,q,r) {
+      var pm = m.abs();
+      if(pm.t <= 0) return;
+      var pt = this.abs();
+      if(pt.t < pm.t) {
+        if(q != null) q.fromInt(0);
+        if(r != null) this.copyTo(r);
+        return;
+      }
+      if(r == null) r = nbi();
+      var y = nbi(), ts = this.s, ms = m.s;
+      var nsh = this.DB-nbits(pm[pm.t-1]);   // normalize modulus
+      if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
+      else { pm.copyTo(y); pt.copyTo(r); }
+      var ys = y.t;
+      var y0 = y[ys-1];
+      if(y0 == 0) return;
+      var yt = y0*(1<1)?y[ys-2]>>this.F2:0);
+      var d1 = this.FV/yt, d2 = (1<= 0) {
+        r[r.t++] = 1;
+        r.subTo(t,r);
+      }
+      BigInteger.ONE.dlShiftTo(ys,t);
+      t.subTo(y,y);  // "negative" y so we can replace sub with am later
+      while(y.t < ys) y[y.t++] = 0;
+      while(--j >= 0) {
+        // Estimate quotient digit
+        var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
+        if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) {   // Try it out
+          y.dlShiftTo(j,t);
+          r.subTo(t,r);
+          while(r[i] < --qd) r.subTo(t,r);
         }
+      }
+      if(q != null) {
+        r.drShiftTo(ys,q);
+        if(ts != ms) BigInteger.ZERO.subTo(q,q);
+      }
+      r.t = ys;
+      r.clamp();
+      if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
+      if(ts < 0) BigInteger.ZERO.subTo(r,r);
+    }
+
+    // (public) this mod a
+    function bnMod(a) {
+      var r = nbi();
+      this.abs().divRemTo(a,null,r);
+      if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
+      return r;
+    }
+
+    // Modular reduction using "classic" algorithm
+    function Classic(m) { this.m = m; }
+    function cConvert(x) {
+      if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
+      else return x;
+    }
+    function cRevert(x) { return x; }
+    function cReduce(x) { x.divRemTo(this.m,null,x); }
+    function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
+    function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+
+    Classic.prototype.convert = cConvert;
+    Classic.prototype.revert = cRevert;
+    Classic.prototype.reduce = cReduce;
+    Classic.prototype.mulTo = cMulTo;
+    Classic.prototype.sqrTo = cSqrTo;
+
+    // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
+    // justification:
+    //         xy == 1 (mod m)
+    //         xy =  1+km
+    //   xy(2-xy) = (1+km)(1-km)
+    // x[y(2-xy)] = 1-k^2m^2
+    // x[y(2-xy)] == 1 (mod m^2)
+    // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
+    // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
+    // JS multiply "overflows" differently from C/C++, so care is needed here.
+    function bnpInvDigit() {
+      if(this.t < 1) return 0;
+      var x = this[0];
+      if((x&1) == 0) return 0;
+      var y = x&3;       // y == 1/x mod 2^2
+      y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
+      y = (y*(2-(x&0xff)*y))&0xff;   // y == 1/x mod 2^8
+      y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;    // y == 1/x mod 2^16
+      // last step - calculate inverse mod DV directly;
+      // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
+      y = (y*(2-x*y%this.DV))%this.DV;       // y == 1/x mod 2^dbits
+      // we really want the negative inverse, and -DV < y < DV
+      return (y>0)?this.DV-y:-y;
+    }
+
+    // Montgomery reduction
+    function Montgomery(m) {
+      this.m = m;
+      this.mp = m.invDigit();
+      this.mpl = this.mp&0x7fff;
+      this.mph = this.mp>>15;
+      this.um = (1<<(m.DB-15))-1;
+      this.mt2 = 2*m.t;
+    }
+
+    // xR mod m
+    function montConvert(x) {
+      var r = nbi();
+      x.abs().dlShiftTo(this.m.t,r);
+      r.divRemTo(this.m,null,r);
+      if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
+      return r;
+    }
+
+    // x/R mod m
+    function montRevert(x) {
+      var r = nbi();
+      x.copyTo(r);
+      this.reduce(r);
+      return r;
+    }
+
+    // x = x/R mod m (HAC 14.32)
+    function montReduce(x) {
+      while(x.t <= this.mt2) // pad x so am has enough room later
+        x[x.t++] = 0;
+      for(var i = 0; i < this.m.t; ++i) {
+        // faster way of calculating u0 = x[i]*mp mod DV
+        var j = x[i]&0x7fff;
+        var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
+        // use am to combine the multiply-shift-add into one call
+        j = i+this.m.t;
+        x[j] += this.m.am(0,u0,x,i,0,this.m.t);
+        // propagate carry
+        while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
+      }
+      x.clamp();
+      x.drShiftTo(this.m.t,x);
+      if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
     }
-    return msg;
-}
-exports["default"] = (actual, ...types) => {
-    return message('Key must be ', actual, ...types);
-};
-function withAlg(alg, actual, ...types) {
-    return message(`Key for the ${alg} algorithm must be `, actual, ...types);
-}
 
+    // r = "x^2/R mod m"; x != r
+    function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
 
-/***/ }),
+    // r = "xy/R mod m"; x,y != r
+    function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
 
-/***/ 21853:
-/***/ ((__unused_webpack_module, exports) => {
+    Montgomery.prototype.convert = montConvert;
+    Montgomery.prototype.revert = montRevert;
+    Montgomery.prototype.reduce = montReduce;
+    Montgomery.prototype.mulTo = montMulTo;
+    Montgomery.prototype.sqrTo = montSqrTo;
 
-"use strict";
+    // (protected) true iff this is even
+    function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const isDisjoint = (...headers) => {
-    const sources = headers.filter(Boolean);
-    if (sources.length === 0 || sources.length === 1) {
-        return true;
-    }
-    let acc;
-    for (const header of sources) {
-        const parameters = Object.keys(header);
-        if (!acc || acc.size === 0) {
-            acc = new Set(parameters);
-            continue;
-        }
-        for (const parameter of parameters) {
-            if (acc.has(parameter)) {
-                return false;
-            }
-            acc.add(parameter);
-        }
+    // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
+    function bnpExp(e,z) {
+      if(e > 0xffffffff || e < 1) return BigInteger.ONE;
+      var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
+      g.copyTo(r);
+      while(--i >= 0) {
+        z.sqrTo(r,r2);
+        if((e&(1< 0) z.mulTo(r2,g,r);
+        else { var t = r; r = r2; r2 = t; }
+      }
+      return z.revert(r);
     }
-    return true;
-};
-exports["default"] = isDisjoint;
-
 
-/***/ }),
+    // (public) this^e % m, 0 <= e < 2^32
+    function bnModPowInt(e,m) {
+      var z;
+      if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
+      return this.exp(e,z);
+    }
 
-/***/ 91229:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    // protected
+    BigInteger.prototype.copyTo = bnpCopyTo;
+    BigInteger.prototype.fromInt = bnpFromInt;
+    BigInteger.prototype.fromString = bnpFromString;
+    BigInteger.prototype.clamp = bnpClamp;
+    BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
+    BigInteger.prototype.drShiftTo = bnpDRShiftTo;
+    BigInteger.prototype.lShiftTo = bnpLShiftTo;
+    BigInteger.prototype.rShiftTo = bnpRShiftTo;
+    BigInteger.prototype.subTo = bnpSubTo;
+    BigInteger.prototype.multiplyTo = bnpMultiplyTo;
+    BigInteger.prototype.squareTo = bnpSquareTo;
+    BigInteger.prototype.divRemTo = bnpDivRemTo;
+    BigInteger.prototype.invDigit = bnpInvDigit;
+    BigInteger.prototype.isEven = bnpIsEven;
+    BigInteger.prototype.exp = bnpExp;
 
-"use strict";
+    // public
+    BigInteger.prototype.toString = bnToString;
+    BigInteger.prototype.negate = bnNegate;
+    BigInteger.prototype.abs = bnAbs;
+    BigInteger.prototype.compareTo = bnCompareTo;
+    BigInteger.prototype.bitLength = bnBitLength;
+    BigInteger.prototype.mod = bnMod;
+    BigInteger.prototype.modPowInt = bnModPowInt;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isJWK = isJWK;
-exports.isPrivateJWK = isPrivateJWK;
-exports.isPublicJWK = isPublicJWK;
-exports.isSecretJWK = isSecretJWK;
-const is_object_js_1 = __nccwpck_require__(92242);
-function isJWK(key) {
-    return (0, is_object_js_1.default)(key) && typeof key.kty === 'string';
-}
-function isPrivateJWK(key) {
-    return key.kty !== 'oct' && typeof key.d === 'string';
-}
-function isPublicJWK(key) {
-    return key.kty !== 'oct' && typeof key.d === 'undefined';
-}
-function isSecretJWK(key) {
-    return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';
-}
+    // "constants"
+    BigInteger.ZERO = nbv(0);
+    BigInteger.ONE = nbv(1);
 
+    // Copyright (c) 2005-2009  Tom Wu
+    // All Rights Reserved.
+    // See "LICENSE" for details.
 
-/***/ }),
+    // Extended JavaScript BN functions, required for RSA private ops.
 
-/***/ 92242:
-/***/ ((__unused_webpack_module, exports) => {
+    // Version 1.1: new BigInteger("0", 10) returns "proper" zero
+    // Version 1.2: square() API, isProbablePrime fix
 
-"use strict";
+    // (public)
+    function bnClone() { var r = nbi(); this.copyTo(r); return r; }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = isObject;
-function isObjectLike(value) {
-    return typeof value === 'object' && value !== null;
-}
-function isObject(input) {
-    if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
-        return false;
-    }
-    if (Object.getPrototypeOf(input) === null) {
-        return true;
-    }
-    let proto = input;
-    while (Object.getPrototypeOf(proto) !== null) {
-        proto = Object.getPrototypeOf(proto);
+    // (public) return value as integer
+    function bnIntValue() {
+      if(this.s < 0) {
+        if(this.t == 1) return this[0]-this.DV;
+        else if(this.t == 0) return -1;
+      }
+      else if(this.t == 1) return this[0];
+      else if(this.t == 0) return 0;
+      // assumes 16 < DB < 32
+      return ((this[1]&((1<<(32-this.DB))-1))<>24; }
 
-/***/ }),
-
-/***/ 56565:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    // (public) return value as short (assumes DB>=16)
+    function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
 
-"use strict";
+    // (protected) return x s.t. r^x < DV
+    function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.bitLength = bitLength;
-const errors_js_1 = __nccwpck_require__(15974);
-const random_js_1 = __nccwpck_require__(23376);
-function bitLength(alg) {
-    switch (alg) {
-        case 'A128GCM':
-        case 'A128GCMKW':
-        case 'A192GCM':
-        case 'A192GCMKW':
-        case 'A256GCM':
-        case 'A256GCMKW':
-            return 96;
-        case 'A128CBC-HS256':
-        case 'A192CBC-HS384':
-        case 'A256CBC-HS512':
-            return 128;
-        default:
-            throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+    // (public) 0 if this == 0, 1 if this > 0
+    function bnSigNum() {
+      if(this.s < 0) return -1;
+      else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
+      else return 1;
     }
-}
-exports["default"] = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3));
-
 
-/***/ }),
-
-/***/ 13354:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const epoch_js_1 = __nccwpck_require__(40485);
-const secs_js_1 = __nccwpck_require__(40556);
-const is_object_js_1 = __nccwpck_require__(92242);
-const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '');
-const checkAudiencePresence = (audPayload, audOption) => {
-    if (typeof audPayload === 'string') {
-        return audOption.includes(audPayload);
-    }
-    if (Array.isArray(audPayload)) {
-        return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
-    }
-    return false;
-};
-exports["default"] = (protectedHeader, encodedPayload, options = {}) => {
-    let payload;
-    try {
-        payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload));
-    }
-    catch {
-    }
-    if (!(0, is_object_js_1.default)(payload)) {
-        throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object');
-    }
-    const { typ } = options;
-    if (typ &&
-        (typeof protectedHeader.typ !== 'string' ||
-            normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
-        throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
-    }
-    const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
-    const presenceCheck = [...requiredClaims];
-    if (maxTokenAge !== undefined)
-        presenceCheck.push('iat');
-    if (audience !== undefined)
-        presenceCheck.push('aud');
-    if (subject !== undefined)
-        presenceCheck.push('sub');
-    if (issuer !== undefined)
-        presenceCheck.push('iss');
-    for (const claim of new Set(presenceCheck.reverse())) {
-        if (!(claim in payload)) {
-            throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
-        }
-    }
-    if (issuer &&
-        !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
-        throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
-    }
-    if (subject && payload.sub !== subject) {
-        throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
-    }
-    if (audience &&
-        !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
-        throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
-    }
-    let tolerance;
-    switch (typeof options.clockTolerance) {
-        case 'string':
-            tolerance = (0, secs_js_1.default)(options.clockTolerance);
-            break;
-        case 'number':
-            tolerance = options.clockTolerance;
-            break;
-        case 'undefined':
-            tolerance = 0;
-            break;
-        default:
-            throw new TypeError('Invalid clockTolerance option type');
-    }
-    const { currentDate } = options;
-    const now = (0, epoch_js_1.default)(currentDate || new Date());
-    if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
-        throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
+    // (protected) convert to radix string
+    function bnpToRadix(b) {
+      if(b == null) b = 10;
+      if(this.signum() == 0 || b < 2 || b > 36) return "0";
+      var cs = this.chunkSize(b);
+      var a = Math.pow(b,cs);
+      var d = nbv(a), y = nbi(), z = nbi(), r = "";
+      this.divRemTo(d,y,z);
+      while(y.signum() > 0) {
+        r = (a+z.intValue()).toString(b).substr(1) + r;
+        y.divRemTo(d,y,z);
+      }
+      return z.intValue().toString(b) + r;
     }
-    if (payload.nbf !== undefined) {
-        if (typeof payload.nbf !== 'number') {
-            throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
+
+    // (protected) convert from radix string
+    function bnpFromRadix(s,b) {
+      this.fromInt(0);
+      if(b == null) b = 10;
+      var cs = this.chunkSize(b);
+      var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
+      for(var i = 0; i < s.length; ++i) {
+        var x = intAt(s,i);
+        if(x < 0) {
+          if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
+          continue;
         }
-        if (payload.nbf > now + tolerance) {
-            throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
+        w = b*w+x;
+        if(++j >= cs) {
+          this.dMultiply(d);
+          this.dAddOffset(w,0);
+          j = 0;
+          w = 0;
         }
+      }
+      if(j > 0) {
+        this.dMultiply(Math.pow(b,j));
+        this.dAddOffset(w,0);
+      }
+      if(mi) BigInteger.ZERO.subTo(this,this);
     }
-    if (payload.exp !== undefined) {
-        if (typeof payload.exp !== 'number') {
-            throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
-        }
-        if (payload.exp <= now - tolerance) {
-            throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
+
+    // (protected) alternate constructor
+    function bnpFromNumber(a,b,c) {
+      if("number" == typeof b) {
+        // new BigInteger(int,int,RNG)
+        if(a < 2) this.fromInt(1);
+        else {
+          this.fromNumber(a,c);
+          if(!this.testBit(a-1))    // force MSB set
+            this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
+          if(this.isEven()) this.dAddOffset(1,0); // force odd
+          while(!this.isProbablePrime(b)) {
+            this.dAddOffset(2,0);
+            if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
+          }
         }
+      }
+      else {
+        // new BigInteger(int,RNG)
+        var x = new Array(), t = a&7;
+        x.length = (a>>3)+1;
+        b.nextBytes(x);
+        if(t > 0) x[0] &= ((1< max) {
-            throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
-        }
-        if (age < 0 - tolerance) {
-            throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
+
+    // (public) convert to bigendian byte array
+    function bnToByteArray() {
+      var i = this.t, r = new Array();
+      r[0] = this.s;
+      var p = this.DB-(i*this.DB)%8, d, k = 0;
+      if(i-- > 0) {
+        if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
+          r[k++] = d|(this.s<<(this.DB-p));
+        while(i >= 0) {
+          if(p < 8) {
+            d = (this[i]&((1<>(p+=this.DB-8);
+          }
+          else {
+            d = (this[i]>>(p-=8))&0xff;
+            if(p <= 0) { p += this.DB; --i; }
+          }
+          if((d&0x80) != 0) d |= -256;
+          if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
+          if(k > 0 || d != this.s) r[k++] = d;
         }
+      }
+      return r;
     }
-    return payload;
-};
 
+    function bnEquals(a) { return(this.compareTo(a)==0); }
+    function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
+    function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
 
-/***/ }),
-
-/***/ 46433:
-/***/ ((__unused_webpack_module, exports) => {
+    // (protected) r = this op a (bitwise)
+    function bnpBitwiseTo(a,op,r) {
+      var i, f, m = Math.min(a.t,this.t);
+      for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
+      if(a.t < this.t) {
+        f = a.s&this.DM;
+        for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
+        r.t = this.t;
+      }
+      else {
+        f = this.s&this.DM;
+        for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
+        r.t = a.t;
+      }
+      r.s = op(this.s,a.s);
+      r.clamp();
+    }
 
-"use strict";
+    // (public) this & a
+    function op_and(x,y) { return x&y; }
+    function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.unprotected = void 0;
-exports.unprotected = Symbol();
+    // (public) this | a
+    function op_or(x,y) { return x|y; }
+    function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
 
+    // (public) this ^ a
+    function op_xor(x,y) { return x^y; }
+    function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
 
-/***/ }),
+    // (public) this & ~a
+    function op_andnot(x,y) { return x&~y; }
+    function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
 
-/***/ 40556:
-/***/ ((__unused_webpack_module, exports) => {
+    // (public) ~this
+    function bnNot() {
+      var r = nbi();
+      for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
+      r.t = this.t;
+      r.s = ~this.s;
+      return r;
+    }
 
-"use strict";
+    // (public) this << n
+    function bnShiftLeft(n) {
+      var r = nbi();
+      if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
+      return r;
+    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const minute = 60;
-const hour = minute * 60;
-const day = hour * 24;
-const week = day * 7;
-const year = day * 365.25;
-const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
-exports["default"] = (str) => {
-    const matched = REGEX.exec(str);
-    if (!matched || (matched[4] && matched[1])) {
-        throw new TypeError('Invalid time period format');
+    // (public) this >> n
+    function bnShiftRight(n) {
+      var r = nbi();
+      if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
+      return r;
     }
-    const value = parseFloat(matched[2]);
-    const unit = matched[3].toLowerCase();
-    let numericDate;
-    switch (unit) {
-        case 'sec':
-        case 'secs':
-        case 'second':
-        case 'seconds':
-        case 's':
-            numericDate = Math.round(value);
-            break;
-        case 'minute':
-        case 'minutes':
-        case 'min':
-        case 'mins':
-        case 'm':
-            numericDate = Math.round(value * minute);
-            break;
-        case 'hour':
-        case 'hours':
-        case 'hr':
-        case 'hrs':
-        case 'h':
-            numericDate = Math.round(value * hour);
-            break;
-        case 'day':
-        case 'days':
-        case 'd':
-            numericDate = Math.round(value * day);
-            break;
-        case 'week':
-        case 'weeks':
-        case 'w':
-            numericDate = Math.round(value * week);
-            break;
-        default:
-            numericDate = Math.round(value * year);
-            break;
+
+    // return index of lowest 1-bit in x, x < 2^31
+    function lbit(x) {
+      if(x == 0) return -1;
+      var r = 0;
+      if((x&0xffff) == 0) { x >>= 16; r += 16; }
+      if((x&0xff) == 0) { x >>= 8; r += 8; }
+      if((x&0xf) == 0) { x >>= 4; r += 4; }
+      if((x&3) == 0) { x >>= 2; r += 2; }
+      if((x&1) == 0) ++r;
+      return r;
     }
-    if (matched[1] === '-' || matched[4] === 'ago') {
-        return -numericDate;
+
+    // (public) returns index of lowest 1-bit (or -1 if none)
+    function bnGetLowestSetBit() {
+      for(var i = 0; i < this.t; ++i)
+        if(this[i] != 0) return i*this.DB+lbit(this[i]);
+      if(this.s < 0) return this.t*this.DB;
+      return -1;
     }
-    return numericDate;
-};
-
-
-/***/ }),
-
-/***/ 19917:
-/***/ ((__unused_webpack_module, exports) => {
 
-"use strict";
+    // return number of 1 bits in x
+    function cbit(x) {
+      var r = 0;
+      while(x != 0) { x &= x-1; ++r; }
+      return r;
+    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const validateAlgorithms = (option, algorithms) => {
-    if (algorithms !== undefined &&
-        (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {
-        throw new TypeError(`"${option}" option must be an array of strings`);
+    // (public) return number of set bits
+    function bnBitCount() {
+      var r = 0, x = this.s&this.DM;
+      for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
+      return r;
     }
-    if (!algorithms) {
-        return undefined;
+
+    // (public) true iff nth bit is set
+    function bnTestBit(n) {
+      var j = Math.floor(n/this.DB);
+      if(j >= this.t) return(this.s!=0);
+      return((this[j]&(1<<(n%this.DB)))!=0);
     }
-    return new Set(algorithms);
-};
-exports["default"] = validateAlgorithms;
 
+    // (protected) this op (1< {
+    // (public) this & ~(1< typeof input !== 'string' || input.length === 0)) {
-        throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
-    }
-    let recognized;
-    if (recognizedOption !== undefined) {
-        recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
-    }
-    else {
-        recognized = recognizedDefault;
-    }
-    for (const parameter of protectedHeader.crit) {
-        if (!recognized.has(parameter)) {
-            throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
-        }
-        if (joseHeader[parameter] === undefined) {
-            throw new Err(`Extension Header Parameter "${parameter}" is missing`);
+    // (protected) r = this + a
+    function bnpAddTo(a,r) {
+      var i = 0, c = 0, m = Math.min(a.t,this.t);
+      while(i < m) {
+        c += this[i]+a[i];
+        r[i++] = c&this.DM;
+        c >>= this.DB;
+      }
+      if(a.t < this.t) {
+        c += a.s;
+        while(i < this.t) {
+          c += this[i];
+          r[i++] = c&this.DM;
+          c >>= this.DB;
         }
-        if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
-            throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
+        c += this.s;
+      }
+      else {
+        c += this.s;
+        while(i < a.t) {
+          c += a[i];
+          r[i++] = c&this.DM;
+          c >>= this.DB;
         }
+        c += a.s;
+      }
+      r.s = (c<0)?-1:0;
+      if(c > 0) r[i++] = c;
+      else if(c < -1) r[i++] = this.DV+c;
+      r.t = i;
+      r.clamp();
     }
-    return new Set(protectedHeader.crit);
-}
-exports["default"] = validateCrit;
 
+    // (public) this + a
+    function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
 
-/***/ }),
+    // (public) this - a
+    function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
 
-/***/ 76202:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    // (public) this * a
+    function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
 
-"use strict";
+    // (public) this^2
+    function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.unwrap = exports.wrap = void 0;
-const node_buffer_1 = __nccwpck_require__(4573);
-const node_crypto_1 = __nccwpck_require__(77598);
-const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const ciphers_js_1 = __nccwpck_require__(99271);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-function checkKeySize(key, alg) {
-    if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) {
-        throw new TypeError(`Invalid key size for alg: ${alg}`);
-    }
-}
-function ensureKeyObject(key, alg, usage) {
-    if ((0, is_key_object_js_1.default)(key)) {
-        return key;
-    }
-    if (key instanceof Uint8Array) {
-        return (0, node_crypto_1.createSecretKey)(key);
-    }
-    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage);
-        return node_crypto_1.KeyObject.from(key);
-    }
-    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));
-}
-const wrap = (alg, key, cek) => {
-    const size = parseInt(alg.slice(1, 4), 10);
-    const algorithm = `aes${size}-wrap`;
-    if (!(0, ciphers_js_1.default)(algorithm)) {
-        throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+    // (public) this / a
+    function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
+
+    // (public) this % a
+    function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
+
+    // (public) [this/a,this%a]
+    function bnDivideAndRemainder(a) {
+      var q = nbi(), r = nbi();
+      this.divRemTo(a,q,r);
+      return new Array(q,r);
     }
-    const keyObject = ensureKeyObject(key, alg, 'wrapKey');
-    checkKeySize(keyObject, alg);
-    const cipher = (0, node_crypto_1.createCipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6));
-    return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final());
-};
-exports.wrap = wrap;
-const unwrap = (alg, key, encryptedKey) => {
-    const size = parseInt(alg.slice(1, 4), 10);
-    const algorithm = `aes${size}-wrap`;
-    if (!(0, ciphers_js_1.default)(algorithm)) {
-        throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+
+    // (protected) this *= n, this >= 0, 1 < n < DV
+    function bnpDMultiply(n) {
+      this[this.t] = this.am(0,n-1,this,0,0,this.t);
+      ++this.t;
+      this.clamp();
     }
-    const keyObject = ensureKeyObject(key, alg, 'unwrapKey');
-    checkKeySize(keyObject, alg);
-    const cipher = (0, node_crypto_1.createDecipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6));
-    return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final());
-};
-exports.unwrap = unwrap;
 
+    // (protected) this += n << w words, this >= 0
+    function bnpDAddOffset(n,w) {
+      if(n == 0) return;
+      while(this.t <= w) this[this.t++] = 0;
+      this[w] += n;
+      while(this[w] >= this.DV) {
+        this[w] -= this.DV;
+        if(++w >= this.t) this[this.t++] = 0;
+        ++this[w];
+      }
+    }
 
-/***/ }),
+    // A "null" reducer
+    function NullExp() {}
+    function nNop(x) { return x; }
+    function nMulTo(x,y,r) { x.multiplyTo(y,r); }
+    function nSqrTo(x,r) { x.squareTo(r); }
 
-/***/ 12774:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    NullExp.prototype.convert = nNop;
+    NullExp.prototype.revert = nNop;
+    NullExp.prototype.mulTo = nMulTo;
+    NullExp.prototype.sqrTo = nSqrTo;
 
-"use strict";
+    // (public) this^e
+    function bnPow(e) { return this.exp(e,new NullExp()); }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0;
-const node_crypto_1 = __nccwpck_require__(77598);
-const node_buffer_1 = __nccwpck_require__(4573);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const genericExport = (keyType, keyFormat, key) => {
-    let keyObject;
-    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
-        if (!key.extractable) {
-            throw new TypeError('CryptoKey is not extractable');
-        }
-        keyObject = node_crypto_1.KeyObject.from(key);
-    }
-    else if ((0, is_key_object_js_1.default)(key)) {
-        keyObject = key;
-    }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
-    }
-    if (keyObject.type !== keyType) {
-        throw new TypeError(`key is not a ${keyType} key`);
+    // (protected) r = lower n words of "this * a", a.t <= n
+    // "this" should be the larger one if appropriate.
+    function bnpMultiplyLowerTo(a,n,r) {
+      var i = Math.min(this.t+a.t,n);
+      r.s = 0; // assumes a,this >= 0
+      r.t = i;
+      while(i > 0) r[--i] = 0;
+      var j;
+      for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
+      for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
+      r.clamp();
     }
-    return keyObject.export({ format: 'pem', type: keyFormat });
-};
-const toSPKI = (key) => {
-    return genericExport('public', 'spki', key);
-};
-exports.toSPKI = toSPKI;
-const toPKCS8 = (key) => {
-    return genericExport('private', 'pkcs8', key);
-};
-exports.toPKCS8 = toPKCS8;
-const fromPKCS8 = (pem) => (0, node_crypto_1.createPrivateKey)({
-    key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'),
-    type: 'pkcs8',
-    format: 'der',
-});
-exports.fromPKCS8 = fromPKCS8;
-const fromSPKI = (pem) => (0, node_crypto_1.createPublicKey)({
-    key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'),
-    type: 'spki',
-    format: 'der',
-});
-exports.fromSPKI = fromSPKI;
-const fromX509 = (pem) => (0, node_crypto_1.createPublicKey)({
-    key: pem,
-    type: 'spki',
-    format: 'pem',
-});
-exports.fromX509 = fromX509;
 
+    // (protected) r = "this * a" without lower n words, n > 0
+    // "this" should be the larger one if appropriate.
+    function bnpMultiplyUpperTo(a,n,r) {
+      --n;
+      var i = r.t = this.t+a.t-n;
+      r.s = 0; // assumes a,this >= 0
+      while(--i >= 0) r[i] = 0;
+      for(i = Math.max(n-this.t,0); i < a.t; ++i)
+        r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
+      r.clamp();
+      r.drShiftTo(1,r);
+    }
 
-/***/ }),
+    // Barrett modular reduction
+    function Barrett(m) {
+      // setup Barrett
+      this.r2 = nbi();
+      this.q3 = nbi();
+      BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
+      this.mu = this.r2.divide(m);
+      this.m = m;
+    }
 
-/***/ 12635:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    function barrettConvert(x) {
+      if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
+      else if(x.compareTo(this.m) < 0) return x;
+      else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
+    }
 
-"use strict";
+    function barrettRevert(x) { return x; }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0;
-const node_buffer_1 = __nccwpck_require__(4573);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-function normalize(input) {
-    let encoded = input;
-    if (encoded instanceof Uint8Array) {
-        encoded = buffer_utils_js_1.decoder.decode(encoded);
+    // x = x mod m (HAC 14.42)
+    function barrettReduce(x) {
+      x.drShiftTo(this.m.t-1,this.r2);
+      if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
+      this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
+      this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
+      while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
+      x.subTo(this.r2,x);
+      while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
     }
-    return encoded;
-}
-const encode = (input) => node_buffer_1.Buffer.from(input).toString('base64url');
-exports.encode = encode;
-const decodeBase64 = (input) => new Uint8Array(node_buffer_1.Buffer.from(input, 'base64'));
-exports.decodeBase64 = decodeBase64;
-const encodeBase64 = (input) => node_buffer_1.Buffer.from(input).toString('base64');
-exports.encodeBase64 = encodeBase64;
-const decode = (input) => new Uint8Array(node_buffer_1.Buffer.from(normalize(input), 'base64url'));
-exports.decode = decode;
 
+    // r = x^2 mod m; x != r
+    function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
 
-/***/ }),
+    // r = x*y mod m; x,y != r
+    function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
 
-/***/ 36910:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    Barrett.prototype.convert = barrettConvert;
+    Barrett.prototype.revert = barrettRevert;
+    Barrett.prototype.reduce = barrettReduce;
+    Barrett.prototype.mulTo = barrettMulTo;
+    Barrett.prototype.sqrTo = barrettSqrTo;
 
-"use strict";
+    // (public) this^e % m (HAC 14.85)
+    function bnModPow(e,m) {
+      var i = e.bitLength(), k, r = nbv(1), z;
+      if(i <= 0) return r;
+      else if(i < 18) k = 1;
+      else if(i < 48) k = 3;
+      else if(i < 144) k = 4;
+      else if(i < 768) k = 5;
+      else k = 6;
+      if(i < 8)
+        z = new Classic(m);
+      else if(m.isEven())
+        z = new Barrett(m);
+      else
+        z = new Montgomery(m);
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = cbcTag;
-const node_crypto_1 = __nccwpck_require__(77598);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {
-    const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3));
-    const hmac = (0, node_crypto_1.createHmac)(`sha${macSize}`, macKey);
-    hmac.update(macData);
-    return hmac.digest().slice(0, keySize >> 3);
-}
+      // precomputation
+      var g = new Array(), n = 3, k1 = k-1, km = (1< 1) {
+        var g2 = nbi();
+        z.sqrTo(g[1],g2);
+        while(n <= km) {
+          g[n] = nbi();
+          z.mulTo(g2,g[n-2],g[n]);
+          n += 2;
+        }
+      }
 
+      var j = e.t-1, w, is1 = true, r2 = nbi(), t;
+      i = nbits(e[j])-1;
+      while(j >= 0) {
+        if(i >= k1) w = (e[j]>>(i-k1))&km;
+        else {
+          w = (e[j]&((1<<(i+1))-1))<<(k1-i);
+          if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
+        }
 
-/***/ }),
+        n = k;
+        while((w&1) == 0) { w >>= 1; --n; }
+        if((i -= n) < 0) { i += this.DB; --j; }
+        if(is1) {    // ret == 1, don't bother squaring or multiplying it
+          g[w].copyTo(r);
+          is1 = false;
+        }
+        else {
+          while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
+          if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
+          z.mulTo(r2,g[w],r);
+        }
 
-/***/ 67000:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+        while(j >= 0 && (e[j]&(1< 0) {
+        x.rShiftTo(g,x);
+        y.rShiftTo(g,y);
+      }
+      while(x.signum() > 0) {
+        if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
+        if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
+        if(x.compareTo(y) >= 0) {
+          x.subTo(y,x);
+          x.rShiftTo(1,x);
+        }
+        else {
+          y.subTo(x,y);
+          y.rShiftTo(1,y);
+        }
+      }
+      if(g > 0) y.lShiftTo(g,y);
+      return y;
+    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const errors_js_1 = __nccwpck_require__(15974);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const checkCekLength = (enc, cek) => {
-    let expected;
-    switch (enc) {
-        case 'A128CBC-HS256':
-        case 'A192CBC-HS384':
-        case 'A256CBC-HS512':
-            expected = parseInt(enc.slice(-3), 10);
-            break;
-        case 'A128GCM':
-        case 'A192GCM':
-        case 'A256GCM':
-            expected = parseInt(enc.slice(1, 4), 10);
-            break;
-        default:
-            throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`);
+    // (protected) this % n, n < 2^26
+    function bnpModInt(n) {
+      if(n <= 0) return 0;
+      var d = this.DV%n, r = (this.s<0)?n-1:0;
+      if(this.t > 0)
+        if(d == 0) r = this[0]%n;
+        else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
+      return r;
     }
-    if (cek instanceof Uint8Array) {
-        const actual = cek.byteLength << 3;
-        if (actual !== expected) {
-            throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
+
+    // (public) 1/this % m (HAC 14.61)
+    function bnModInverse(m) {
+      var ac = m.isEven();
+      if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
+      var u = m.clone(), v = this.clone();
+      var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
+      while(u.signum() != 0) {
+        while(u.isEven()) {
+          u.rShiftTo(1,u);
+          if(ac) {
+            if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
+            a.rShiftTo(1,a);
+          }
+          else if(!b.isEven()) b.subTo(m,b);
+          b.rShiftTo(1,b);
         }
-        return;
-    }
-    if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') {
-        const actual = cek.symmetricKeySize << 3;
-        if (actual !== expected) {
-            throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
+        while(v.isEven()) {
+          v.rShiftTo(1,v);
+          if(ac) {
+            if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
+            c.rShiftTo(1,c);
+          }
+          else if(!d.isEven()) d.subTo(m,d);
+          d.rShiftTo(1,d);
+        }
+        if(u.compareTo(v) >= 0) {
+          u.subTo(v,u);
+          if(ac) a.subTo(c,a);
+          b.subTo(d,b);
         }
-        return;
+        else {
+          v.subTo(u,v);
+          if(ac) c.subTo(a,c);
+          d.subTo(b,d);
+        }
+      }
+      if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
+      if(d.compareTo(m) >= 0) return d.subtract(m);
+      if(d.signum() < 0) d.addTo(m,d); else return d;
+      if(d.signum() < 0) return d.add(m); else return d;
     }
-    throw new TypeError('Invalid Content Encryption Key type');
-};
-exports["default"] = checkCekLength;
 
+    var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
+    var lplim = (1<<26)/lowprimes[lowprimes.length-1];
 
-/***/ }),
-
-/***/ 65142:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
+    // (public) test primality with certainty >= 1-.5^t
+    function bnIsProbablePrime(t) {
+      var i, x = this.abs();
+      if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
+        for(i = 0; i < lowprimes.length; ++i)
+          if(x[0] == lowprimes[i]) return true;
+        return false;
+      }
+      if(x.isEven()) return false;
+      i = 1;
+      while(i < lowprimes.length) {
+        var m = lowprimes[i], j = i+1;
+        while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
+        m = x.modInt(m);
+        while(i < j) if(m%lowprimes[i++] == 0) return false;
+      }
+      return x.millerRabin(t);
+    }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-exports["default"] = (key, alg) => {
-    let modulusLength;
-    try {
-        if (key instanceof node_crypto_1.KeyObject) {
-            modulusLength = key.asymmetricKeyDetails?.modulusLength;
-        }
-        else {
-            modulusLength = Buffer.from(key.n, 'base64url').byteLength << 3;
+    // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
+    function bnpMillerRabin(t) {
+      var n1 = this.subtract(BigInteger.ONE);
+      var k = n1.getLowestSetBit();
+      if(k <= 0) return false;
+      var r = n1.shiftRight(k);
+      t = (t+1)>>1;
+      if(t > lowprimes.length) t = lowprimes.length;
+      var a = nbi();
+      for(var i = 0; i < t; ++i) {
+        //Pick bases at random, instead of starting at 2
+        a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
+        var y = a.modPow(r,this);
+        if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
+          var j = 1;
+          while(j++ < k && y.compareTo(n1) != 0) {
+            y = y.modPowInt(2,this);
+            if(y.compareTo(BigInteger.ONE) == 0) return false;
+          }
+          if(y.compareTo(n1) != 0) return false;
         }
+      }
+      return true;
     }
-    catch { }
-    if (typeof modulusLength !== 'number' || modulusLength < 2048) {
-        throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
-    }
-};
 
+    // protected
+    BigInteger.prototype.chunkSize = bnpChunkSize;
+    BigInteger.prototype.toRadix = bnpToRadix;
+    BigInteger.prototype.fromRadix = bnpFromRadix;
+    BigInteger.prototype.fromNumber = bnpFromNumber;
+    BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
+    BigInteger.prototype.changeBit = bnpChangeBit;
+    BigInteger.prototype.addTo = bnpAddTo;
+    BigInteger.prototype.dMultiply = bnpDMultiply;
+    BigInteger.prototype.dAddOffset = bnpDAddOffset;
+    BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
+    BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
+    BigInteger.prototype.modInt = bnpModInt;
+    BigInteger.prototype.millerRabin = bnpMillerRabin;
 
-/***/ }),
+    // public
+    BigInteger.prototype.clone = bnClone;
+    BigInteger.prototype.intValue = bnIntValue;
+    BigInteger.prototype.byteValue = bnByteValue;
+    BigInteger.prototype.shortValue = bnShortValue;
+    BigInteger.prototype.signum = bnSigNum;
+    BigInteger.prototype.toByteArray = bnToByteArray;
+    BigInteger.prototype.equals = bnEquals;
+    BigInteger.prototype.min = bnMin;
+    BigInteger.prototype.max = bnMax;
+    BigInteger.prototype.and = bnAnd;
+    BigInteger.prototype.or = bnOr;
+    BigInteger.prototype.xor = bnXor;
+    BigInteger.prototype.andNot = bnAndNot;
+    BigInteger.prototype.not = bnNot;
+    BigInteger.prototype.shiftLeft = bnShiftLeft;
+    BigInteger.prototype.shiftRight = bnShiftRight;
+    BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
+    BigInteger.prototype.bitCount = bnBitCount;
+    BigInteger.prototype.testBit = bnTestBit;
+    BigInteger.prototype.setBit = bnSetBit;
+    BigInteger.prototype.clearBit = bnClearBit;
+    BigInteger.prototype.flipBit = bnFlipBit;
+    BigInteger.prototype.add = bnAdd;
+    BigInteger.prototype.subtract = bnSubtract;
+    BigInteger.prototype.multiply = bnMultiply;
+    BigInteger.prototype.divide = bnDivide;
+    BigInteger.prototype.remainder = bnRemainder;
+    BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
+    BigInteger.prototype.modPow = bnModPow;
+    BigInteger.prototype.modInverse = bnModInverse;
+    BigInteger.prototype.pow = bnPow;
+    BigInteger.prototype.gcd = bnGCD;
+    BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
 
-/***/ 99271:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    // JSBN-specific extension
+    BigInteger.prototype.square = bnSquare;
 
-"use strict";
+    // Expose the Barrett function
+    BigInteger.prototype.Barrett = Barrett
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-let ciphers;
-exports["default"] = (algorithm) => {
-    ciphers ||= new Set((0, node_crypto_1.getCiphers)());
-    return ciphers.has(algorithm);
-};
+    // BigInteger interfaces not implemented in jsbn:
 
+    // BigInteger(int signum, byte[] magnitude)
+    // double doubleValue()
+    // float floatValue()
+    // int hashCode()
+    // long longValue()
+    // static BigInteger valueOf(long val)
 
-/***/ }),
+    // Random number generator - requires a PRNG backend, e.g. prng4.js
 
-/***/ 52806:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    // For best results, put code like
+    // 
+    // in your main HTML document.
 
-"use strict";
+    var rng_state;
+    var rng_pool;
+    var rng_pptr;
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-const check_iv_length_js_1 = __nccwpck_require__(63351);
-const check_cek_length_js_1 = __nccwpck_require__(67000);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const errors_js_1 = __nccwpck_require__(15974);
-const timing_safe_equal_js_1 = __nccwpck_require__(39106);
-const cbc_tag_js_1 = __nccwpck_require__(36910);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const ciphers_js_1 = __nccwpck_require__(99271);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
-    const keySize = parseInt(enc.slice(1, 4), 10);
-    if ((0, is_key_object_js_1.default)(cek)) {
-        cek = cek.export();
-    }
-    const encKey = cek.subarray(keySize >> 3);
-    const macKey = cek.subarray(0, keySize >> 3);
-    const macSize = parseInt(enc.slice(-3), 10);
-    const algorithm = `aes-${keySize}-cbc`;
-    if (!(0, ciphers_js_1.default)(algorithm)) {
-        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
-    }
-    const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize);
-    let macCheckPassed;
-    try {
-        macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag);
-    }
-    catch {
-    }
-    if (!macCheckPassed) {
-        throw new errors_js_1.JWEDecryptionFailed();
-    }
-    let plaintext;
-    try {
-        const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, encKey, iv);
-        plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final());
-    }
-    catch {
-    }
-    if (!plaintext) {
-        throw new errors_js_1.JWEDecryptionFailed();
+    // Mix in a 32-bit integer into the pool
+    function rng_seed_int(x) {
+      rng_pool[rng_pptr++] ^= x & 255;
+      rng_pool[rng_pptr++] ^= (x >> 8) & 255;
+      rng_pool[rng_pptr++] ^= (x >> 16) & 255;
+      rng_pool[rng_pptr++] ^= (x >> 24) & 255;
+      if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
     }
-    return plaintext;
-}
-function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
-    const keySize = parseInt(enc.slice(1, 4), 10);
-    const algorithm = `aes-${keySize}-gcm`;
-    if (!(0, ciphers_js_1.default)(algorithm)) {
-        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
+
+    // Mix in the current time (w/milliseconds) into the pool
+    function rng_seed_time() {
+      rng_seed_int(new Date().getTime());
     }
-    try {
-        const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 });
-        decipher.setAuthTag(tag);
-        if (aad.byteLength) {
-            decipher.setAAD(aad, { plaintextLength: ciphertext.length });
+
+    // Initialize the pool with junk if needed.
+    if(rng_pool == null) {
+      rng_pool = new Array();
+      rng_pptr = 0;
+      var t;
+      if(typeof window !== "undefined" && window.crypto) {
+        if (window.crypto.getRandomValues) {
+          // Use webcrypto if available
+          var ua = new Uint8Array(32);
+          window.crypto.getRandomValues(ua);
+          for(t = 0; t < 32; ++t)
+            rng_pool[rng_pptr++] = ua[t];
         }
-        const plaintext = decipher.update(ciphertext);
-        decipher.final();
-        return plaintext;
-    }
-    catch {
-        throw new errors_js_1.JWEDecryptionFailed();
-    }
-}
-const decrypt = (enc, cek, ciphertext, iv, tag, aad) => {
-    let key;
-    if ((0, webcrypto_js_1.isCryptoKey)(cek)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt');
-        key = node_crypto_1.KeyObject.from(cek);
+        else if(navigator.appName == "Netscape" && navigator.appVersion < "5") {
+          // Extract entropy (256 bits) from NS4 RNG if available
+          var z = window.crypto.random(32);
+          for(t = 0; t < z.length; ++t)
+            rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
+        }
+      }
+      while(rng_pptr < rng_psize) {  // extract some randomness from Math.random()
+        t = Math.floor(65536 * Math.random());
+        rng_pool[rng_pptr++] = t >>> 8;
+        rng_pool[rng_pptr++] = t & 255;
+      }
+      rng_pptr = 0;
+      rng_seed_time();
+      //rng_seed_int(window.screenX);
+      //rng_seed_int(window.screenY);
     }
-    else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) {
-        key = cek;
+
+    function rng_get_byte() {
+      if(rng_state == null) {
+        rng_seed_time();
+        rng_state = prng_newstate();
+        rng_state.init(rng_pool);
+        for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
+          rng_pool[rng_pptr] = 0;
+        rng_pptr = 0;
+        //rng_pool = null;
+      }
+      // TODO: allow reseeding after first request
+      return rng_state.next();
     }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array'));
+
+    function rng_get_bytes(ba) {
+      var i;
+      for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
     }
-    if (!iv) {
-        throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing');
+
+    function SecureRandom() {}
+
+    SecureRandom.prototype.nextBytes = rng_get_bytes;
+
+    // prng4.js - uses Arcfour as a PRNG
+
+    function Arcfour() {
+      this.i = 0;
+      this.j = 0;
+      this.S = new Array();
     }
-    if (!tag) {
-        throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing');
+
+    // Initialize arcfour context from key, an array of ints, each from [0..255]
+    function ARC4init(key) {
+      var i, j, t;
+      for(i = 0; i < 256; ++i)
+        this.S[i] = i;
+      j = 0;
+      for(i = 0; i < 256; ++i) {
+        j = (j + this.S[i] + key[i % key.length]) & 255;
+        t = this.S[i];
+        this.S[i] = this.S[j];
+        this.S[j] = t;
+      }
+      this.i = 0;
+      this.j = 0;
     }
-    (0, check_cek_length_js_1.default)(enc, key);
-    (0, check_iv_length_js_1.default)(enc, iv);
-    switch (enc) {
-        case 'A128CBC-HS256':
-        case 'A192CBC-HS384':
-        case 'A256CBC-HS512':
-            return cbcDecrypt(enc, key, ciphertext, iv, tag, aad);
-        case 'A128GCM':
-        case 'A192GCM':
-        case 'A256GCM':
-            return gcmDecrypt(enc, key, ciphertext, iv, tag, aad);
-        default:
-            throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
+
+    function ARC4next() {
+      var t;
+      this.i = (this.i + 1) & 255;
+      this.j = (this.j + this.S[this.i]) & 255;
+      t = this.S[this.i];
+      this.S[this.i] = this.S[this.j];
+      this.S[this.j] = t;
+      return this.S[(t + this.S[this.i]) & 255];
     }
-};
-exports["default"] = decrypt;
 
+    Arcfour.prototype.init = ARC4init;
+    Arcfour.prototype.next = ARC4next;
 
-/***/ }),
+    // Plug in your RNG constructor here
+    function prng_newstate() {
+      return new Arcfour();
+    }
 
-/***/ 12931:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+    // Pool size must be a multiple of 4 and greater than 32.
+    // An array of bytes the size of the pool will be passed to init()
+    var rng_psize = 256;
 
-"use strict";
+    if (true) {
+        exports = module.exports = {
+            default: BigInteger,
+            BigInteger: BigInteger,
+            SecureRandom: SecureRandom,
+        };
+    } else {}
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-const digest = (algorithm, data) => (0, node_crypto_1.createHash)(algorithm).update(data).digest();
-exports["default"] = digest;
+}).call(this);
 
 
 /***/ }),
 
-/***/ 74510:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 85743:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const { Request, Response } = __nccwpck_require__(88483)
+const { Minipass } = __nccwpck_require__(78275)
+const MinipassFlush = __nccwpck_require__(37633)
+const cacache = __nccwpck_require__(85742)
+const url = __nccwpck_require__(87016)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = dsaDigest;
-const errors_js_1 = __nccwpck_require__(15974);
-function dsaDigest(alg) {
-    switch (alg) {
-        case 'PS256':
-        case 'RS256':
-        case 'ES256':
-        case 'ES256K':
-            return 'sha256';
-        case 'PS384':
-        case 'RS384':
-        case 'ES384':
-            return 'sha384';
-        case 'PS512':
-        case 'RS512':
-        case 'ES512':
-            return 'sha512';
-        case 'EdDSA':
-            return undefined;
-        default:
-            throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
-    }
-}
+const CachingMinipassPipeline = __nccwpck_require__(22314)
+const CachePolicy = __nccwpck_require__(15281)
+const cacheKey = __nccwpck_require__(45808)
+const remote = __nccwpck_require__(20766)
 
+const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop)
 
-/***/ }),
+// allow list for request headers that will be written to the cache index
+// note: we will also store any request headers
+// that are named in a response's vary header
+const KEEP_REQUEST_HEADERS = [
+  'accept-charset',
+  'accept-encoding',
+  'accept-language',
+  'accept',
+  'cache-control',
+]
 
-/***/ 43359:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// allow list for response headers that will be written to the cache index
+// note: we must not store the real response's age header, or when we load
+// a cache policy based on the metadata it will think the cached response
+// is always stale
+const KEEP_RESPONSE_HEADERS = [
+  'cache-control',
+  'content-encoding',
+  'content-language',
+  'content-type',
+  'date',
+  'etag',
+  'expires',
+  'last-modified',
+  'link',
+  'location',
+  'pragma',
+  'vary',
+]
 
-"use strict";
+// return an object containing all metadata to be written to the index
+const getMetadata = (request, response, options) => {
+  const metadata = {
+    time: Date.now(),
+    url: request.url,
+    reqHeaders: {},
+    resHeaders: {},
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ecdhAllowed = void 0;
-exports.deriveKey = deriveKey;
-exports.generateEpk = generateEpk;
-const node_crypto_1 = __nccwpck_require__(77598);
-const node_util_1 = __nccwpck_require__(57975);
-const get_named_curve_js_1 = __nccwpck_require__(65661);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const errors_js_1 = __nccwpck_require__(15974);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const generateKeyPair = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair);
-async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
-    let publicKey;
-    if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH');
-        publicKey = node_crypto_1.KeyObject.from(publicKee);
-    }
-    else if ((0, is_key_object_js_1.default)(publicKee)) {
-        publicKey = publicKee;
-    }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types));
+    // options on which we must match the request and vary the response
+    options: {
+      compress: options.compress != null ? options.compress : request.compress,
+    },
+  }
+
+  // only save the status if it's not a 200 or 304
+  if (response.status !== 200 && response.status !== 304) {
+    metadata.status = response.status
+  }
+
+  for (const name of KEEP_REQUEST_HEADERS) {
+    if (request.headers.has(name)) {
+      metadata.reqHeaders[name] = request.headers.get(name)
     }
-    let privateKey;
-    if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits');
-        privateKey = node_crypto_1.KeyObject.from(privateKee);
+  }
+
+  // if the request's host header differs from the host in the url
+  // we need to keep it, otherwise it's just noise and we ignore it
+  const host = request.headers.get('host')
+  const parsedUrl = new url.URL(request.url)
+  if (host && parsedUrl.host !== host) {
+    metadata.reqHeaders.host = host
+  }
+
+  // if the response has a vary header, make sure
+  // we store the relevant request headers too
+  if (response.headers.has('vary')) {
+    const vary = response.headers.get('vary')
+    // a vary of "*" means every header causes a different response.
+    // in that scenario, we do not include any additional headers
+    // as the freshness check will always fail anyway and we don't
+    // want to bloat the cache indexes
+    if (vary !== '*') {
+      // copy any other request headers that will vary the response
+      const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/)
+      for (const name of varyHeaders) {
+        if (request.headers.has(name)) {
+          metadata.reqHeaders[name] = request.headers.get(name)
+        }
+      }
     }
-    else if ((0, is_key_object_js_1.default)(privateKee)) {
-        privateKey = privateKee;
+  }
+
+  for (const name of KEEP_RESPONSE_HEADERS) {
+    if (response.headers.has(name)) {
+      metadata.resHeaders[name] = response.headers.get(name)
     }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types));
+  }
+
+  for (const name of options.cacheAdditionalHeaders) {
+    if (response.headers.has(name)) {
+      metadata.resHeaders[name] = response.headers.get(name)
     }
-    const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength));
-    const sharedSecret = (0, node_crypto_1.diffieHellman)({ privateKey, publicKey });
-    return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value);
+  }
+
+  return metadata
 }
-async function generateEpk(kee) {
-    let key;
-    if ((0, webcrypto_js_1.isCryptoKey)(kee)) {
-        key = node_crypto_1.KeyObject.from(kee);
-    }
-    else if ((0, is_key_object_js_1.default)(kee)) {
-        key = kee;
-    }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types));
-    }
-    switch (key.asymmetricKeyType) {
-        case 'x25519':
-            return generateKeyPair('x25519');
-        case 'x448': {
-            return generateKeyPair('x448');
-        }
-        case 'ec': {
-            const namedCurve = (0, get_named_curve_js_1.default)(key);
-            return generateKeyPair('ec', { namedCurve });
-        }
-        default:
-            throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK');
+
+// symbols used to hide objects that may be lazily evaluated in a getter
+const _request = Symbol('request')
+const _response = Symbol('response')
+const _policy = Symbol('policy')
+
+class CacheEntry {
+  constructor ({ entry, request, response, options }) {
+    if (entry) {
+      this.key = entry.key
+      this.entry = entry
+      // previous versions of this module didn't write an explicit timestamp in
+      // the metadata, so fall back to the entry's timestamp. we can't use the
+      // entry timestamp to determine staleness because cacache will update it
+      // when it verifies its data
+      this.entry.metadata.time = this.entry.metadata.time || this.entry.time
+    } else {
+      this.key = cacheKey(request)
     }
-}
-const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key));
-exports.ecdhAllowed = ecdhAllowed;
 
+    this.options = options
 
-/***/ }),
+    // these properties are behind getters that lazily evaluate
+    this[_request] = request
+    this[_response] = response
+    this[_policy] = null
+  }
 
-/***/ 36286:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  // returns a CacheEntry instance that satisfies the given request
+  // or undefined if no existing entry satisfies
+  static async find (request, options) {
+    try {
+      // compacts the index and returns an array of unique entries
+      var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => {
+        const entryA = new CacheEntry({ entry: A, options })
+        const entryB = new CacheEntry({ entry: B, options })
+        return entryA.policy.satisfies(entryB.request)
+      }, {
+        validateEntry: (entry) => {
+          // clean out entries with a buggy content-encoding value
+          if (entry.metadata &&
+              entry.metadata.resHeaders &&
+              entry.metadata.resHeaders['content-encoding'] === null) {
+            return false
+          }
 
-"use strict";
+          // if an integrity is null, it needs to have a status specified
+          if (entry.integrity === null) {
+            return !!(entry.metadata && entry.metadata.status)
+          }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-const check_iv_length_js_1 = __nccwpck_require__(63351);
-const check_cek_length_js_1 = __nccwpck_require__(67000);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const cbc_tag_js_1 = __nccwpck_require__(36910);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const iv_js_1 = __nccwpck_require__(56565);
-const errors_js_1 = __nccwpck_require__(15974);
-const ciphers_js_1 = __nccwpck_require__(99271);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-function cbcEncrypt(enc, plaintext, cek, iv, aad) {
-    const keySize = parseInt(enc.slice(1, 4), 10);
-    if ((0, is_key_object_js_1.default)(cek)) {
-        cek = cek.export();
-    }
-    const encKey = cek.subarray(keySize >> 3);
-    const macKey = cek.subarray(0, keySize >> 3);
-    const algorithm = `aes-${keySize}-cbc`;
-    if (!(0, ciphers_js_1.default)(algorithm)) {
-        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
-    }
-    const cipher = (0, node_crypto_1.createCipheriv)(algorithm, encKey, iv);
-    const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final());
-    const macSize = parseInt(enc.slice(-3), 10);
-    const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize);
-    return { ciphertext, tag, iv };
-}
-function gcmEncrypt(enc, plaintext, cek, iv, aad) {
-    const keySize = parseInt(enc.slice(1, 4), 10);
-    const algorithm = `aes-${keySize}-gcm`;
-    if (!(0, ciphers_js_1.default)(algorithm)) {
-        throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
+          return true
+        },
+      })
+    } catch (err) {
+      // if the compact request fails, ignore the error and return
+      return
     }
-    const cipher = (0, node_crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 });
-    if (aad.byteLength) {
-        cipher.setAAD(aad, { plaintextLength: plaintext.length });
+
+    // a cache mode of 'reload' means to behave as though we have no cache
+    // on the way to the network. return undefined to allow cacheFetch to
+    // create a brand new request no matter what.
+    if (options.cache === 'reload') {
+      return
     }
-    const ciphertext = cipher.update(plaintext);
-    cipher.final();
-    const tag = cipher.getAuthTag();
-    return { ciphertext, tag, iv };
-}
-const encrypt = (enc, plaintext, cek, iv, aad) => {
-    let key;
-    if ((0, webcrypto_js_1.isCryptoKey)(cek)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt');
-        key = node_crypto_1.KeyObject.from(cek);
+
+    // find the specific entry that satisfies the request
+    let match
+    for (const entry of matches) {
+      const _entry = new CacheEntry({
+        entry,
+        options,
+      })
+
+      if (_entry.policy.satisfies(request)) {
+        match = _entry
+        break
+      }
     }
-    else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) {
-        key = cek;
+
+    return match
+  }
+
+  // if the user made a PUT/POST/PATCH then we invalidate our
+  // cache for the same url by deleting the index entirely
+  static async invalidate (request, options) {
+    const key = cacheKey(request)
+    try {
+      await cacache.rm.entry(options.cachePath, key, { removeFully: true })
+    } catch (err) {
+      // ignore errors
     }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array'));
+  }
+
+  get request () {
+    if (!this[_request]) {
+      this[_request] = new Request(this.entry.metadata.url, {
+        method: 'GET',
+        headers: this.entry.metadata.reqHeaders,
+        ...this.entry.metadata.options,
+      })
     }
-    (0, check_cek_length_js_1.default)(enc, key);
-    if (iv) {
-        (0, check_iv_length_js_1.default)(enc, iv);
+
+    return this[_request]
+  }
+
+  get response () {
+    if (!this[_response]) {
+      this[_response] = new Response(null, {
+        url: this.entry.metadata.url,
+        counter: this.options.counter,
+        status: this.entry.metadata.status || 200,
+        headers: {
+          ...this.entry.metadata.resHeaders,
+          'content-length': this.entry.size,
+        },
+      })
     }
-    else {
-        iv = (0, iv_js_1.default)(enc);
+
+    return this[_response]
+  }
+
+  get policy () {
+    if (!this[_policy]) {
+      this[_policy] = new CachePolicy({
+        entry: this.entry,
+        request: this.request,
+        response: this.response,
+        options: this.options,
+      })
     }
-    switch (enc) {
-        case 'A128CBC-HS256':
-        case 'A192CBC-HS384':
-        case 'A256CBC-HS512':
-            return cbcEncrypt(enc, plaintext, key, iv, aad);
-        case 'A128GCM':
-        case 'A192GCM':
-        case 'A256GCM':
-            return gcmEncrypt(enc, plaintext, key, iv, aad);
-        default:
-            throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
+
+    return this[_policy]
+  }
+
+  // wraps the response in a pipeline that stores the data
+  // in the cache while the user consumes it
+  async store (status) {
+    // if we got a status other than 200, 301, or 308,
+    // or the CachePolicy forbid storage, append the
+    // cache status header and return it untouched
+    if (
+      this.request.method !== 'GET' ||
+      ![200, 301, 308].includes(this.response.status) ||
+      !this.policy.storable()
+    ) {
+      this.response.headers.set('x-local-cache-status', 'skip')
+      return this.response
     }
-};
-exports["default"] = encrypt;
 
+    const size = this.response.headers.get('content-length')
+    const cacheOpts = {
+      algorithms: this.options.algorithms,
+      metadata: getMetadata(this.request, this.response, this.options),
+      size,
+      integrity: this.options.integrity,
+      integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body,
+    }
 
-/***/ }),
+    let body = null
+    // we only set a body if the status is a 200, redirects are
+    // stored as metadata only
+    if (this.response.status === 200) {
+      let cacheWriteResolve, cacheWriteReject
+      const cacheWritePromise = new Promise((resolve, reject) => {
+        cacheWriteResolve = resolve
+        cacheWriteReject = reject
+      }).catch((err) => {
+        body.emit('error', err)
+      })
 
-/***/ 20311:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+      body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({
+        flush () {
+          return cacheWritePromise
+        },
+      }))
+      // this is always true since if we aren't reusing the one from the remote fetch, we
+      // are using the one from cacache
+      body.hasIntegrityEmitter = true
 
-"use strict";
+      const onResume = () => {
+        const tee = new Minipass()
+        const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts)
+        // re-emit the integrity and size events on our new response body so they can be reused
+        cacheStream.on('integrity', i => body.emit('integrity', i))
+        cacheStream.on('size', s => body.emit('size', s))
+        // stick a flag on here so downstream users will know if they can expect integrity events
+        tee.pipe(cacheStream)
+        // TODO if the cache write fails, log a warning but return the response anyway
+        // eslint-disable-next-line promise/catch-or-return
+        cacheStream.promise().then(cacheWriteResolve, cacheWriteReject)
+        body.unshift(tee)
+        body.unshift(this.response.body)
+      }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const http = __nccwpck_require__(37067);
-const https = __nccwpck_require__(44708);
-const node_events_1 = __nccwpck_require__(78474);
-const errors_js_1 = __nccwpck_require__(15974);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const fetchJwks = async (url, timeout, options) => {
-    let get;
-    switch (url.protocol) {
-        case 'https:':
-            get = https.get;
-            break;
-        case 'http:':
-            get = http.get;
-            break;
-        default:
-            throw new TypeError('Unsupported URL protocol.');
-    }
-    const { agent, headers } = options;
-    const req = get(url.href, {
-        agent,
-        timeout,
-        headers,
-    });
-    const [response] = (await Promise.race([(0, node_events_1.once)(req, 'response'), (0, node_events_1.once)(req, 'timeout')]));
-    if (!response) {
-        req.destroy();
-        throw new errors_js_1.JWKSTimeout();
-    }
-    if (response.statusCode !== 200) {
-        throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
-    }
-    const parts = [];
-    for await (const part of response) {
-        parts.push(part);
-    }
-    try {
-        return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts)));
-    }
-    catch {
-        throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
+      body.once('resume', onResume)
+      body.once('end', () => body.removeListener('resume', onResume))
+    } else {
+      await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts)
     }
-};
-exports["default"] = fetchJwks;
 
+    // note: we do not set the x-local-cache-hash header because we do not know
+    // the hash value until after the write to the cache completes, which doesn't
+    // happen until after the response has been sent and it's too late to write
+    // the header anyway
+    this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath))
+    this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key))
+    this.response.headers.set('x-local-cache-mode', 'stream')
+    this.response.headers.set('x-local-cache-status', status)
+    this.response.headers.set('x-local-cache-time', new Date().toISOString())
+    const newResponse = new Response(body, {
+      url: this.response.url,
+      status: this.response.status,
+      headers: this.response.headers,
+      counter: this.options.counter,
+    })
+    return newResponse
+  }
 
-/***/ }),
-
-/***/ 10088:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  // use the cached data to create a response and return it
+  async respond (method, options, status) {
+    let response
+    if (method === 'HEAD' || [301, 308].includes(this.response.status)) {
+      // if the request is a HEAD, or the response is a redirect,
+      // then the metadata in the entry already includes everything
+      // we need to build a response
+      response = this.response
+    } else {
+      // we're responding with a full cached response, so create a body
+      // that reads from cacache and attach it to a new Response
+      const body = new Minipass()
+      const headers = { ...this.policy.responseHeaders() }
 
-"use strict";
+      const onResume = () => {
+        const cacheStream = cacache.get.stream.byDigest(
+          this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize }
+        )
+        cacheStream.on('error', async (err) => {
+          cacheStream.pause()
+          if (err.code === 'EINTEGRITY') {
+            await cacache.rm.content(
+              this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize }
+            )
+          }
+          if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') {
+            await CacheEntry.invalidate(this.request, this.options)
+          }
+          body.emit('error', err)
+          cacheStream.resume()
+        })
+        // emit the integrity and size events based on our metadata so we're consistent
+        body.emit('integrity', this.entry.integrity)
+        body.emit('size', Number(headers['content-length']))
+        cacheStream.pipe(body)
+      }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.generateSecret = generateSecret;
-exports.generateKeyPair = generateKeyPair;
-const node_crypto_1 = __nccwpck_require__(77598);
-const node_util_1 = __nccwpck_require__(57975);
-const random_js_1 = __nccwpck_require__(23376);
-const errors_js_1 = __nccwpck_require__(15974);
-const generate = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair);
-async function generateSecret(alg, options) {
-    let length;
-    switch (alg) {
-        case 'HS256':
-        case 'HS384':
-        case 'HS512':
-        case 'A128CBC-HS256':
-        case 'A192CBC-HS384':
-        case 'A256CBC-HS512':
-            length = parseInt(alg.slice(-3), 10);
-            break;
-        case 'A128KW':
-        case 'A192KW':
-        case 'A256KW':
-        case 'A128GCMKW':
-        case 'A192GCMKW':
-        case 'A256GCMKW':
-        case 'A128GCM':
-        case 'A192GCM':
-        case 'A256GCM':
-            length = parseInt(alg.slice(1, 4), 10);
-            break;
-        default:
-            throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
-    }
-    return (0, node_crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3)));
-}
-async function generateKeyPair(alg, options) {
-    switch (alg) {
-        case 'RS256':
-        case 'RS384':
-        case 'RS512':
-        case 'PS256':
-        case 'PS384':
-        case 'PS512':
-        case 'RSA-OAEP':
-        case 'RSA-OAEP-256':
-        case 'RSA-OAEP-384':
-        case 'RSA-OAEP-512':
-        case 'RSA1_5': {
-            const modulusLength = options?.modulusLength ?? 2048;
-            if (typeof modulusLength !== 'number' || modulusLength < 2048) {
-                throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
-            }
-            const keypair = await generate('rsa', {
-                modulusLength,
-                publicExponent: 0x10001,
-            });
-            return keypair;
-        }
-        case 'ES256':
-            return generate('ec', { namedCurve: 'P-256' });
-        case 'ES256K':
-            return generate('ec', { namedCurve: 'secp256k1' });
-        case 'ES384':
-            return generate('ec', { namedCurve: 'P-384' });
-        case 'ES512':
-            return generate('ec', { namedCurve: 'P-521' });
-        case 'EdDSA': {
-            switch (options?.crv) {
-                case undefined:
-                case 'Ed25519':
-                    return generate('ed25519');
-                case 'Ed448':
-                    return generate('ed448');
-                default:
-                    throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448');
-            }
-        }
-        case 'ECDH-ES':
-        case 'ECDH-ES+A128KW':
-        case 'ECDH-ES+A192KW':
-        case 'ECDH-ES+A256KW': {
-            const crv = options?.crv ?? 'P-256';
-            switch (crv) {
-                case undefined:
-                case 'P-256':
-                case 'P-384':
-                case 'P-521':
-                    return generate('ec', { namedCurve: crv });
-                case 'X25519':
-                    return generate('x25519');
-                case 'X448':
-                    return generate('x448');
-                default:
-                    throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
-            }
-        }
-        default:
-            throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+      body.once('resume', onResume)
+      body.once('end', () => body.removeListener('resume', onResume))
+      response = new Response(body, {
+        url: this.entry.metadata.url,
+        counter: options.counter,
+        status: 200,
+        headers,
+      })
     }
-}
 
+    response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath))
+    response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity))
+    response.headers.set('x-local-cache-key', encodeURIComponent(this.key))
+    response.headers.set('x-local-cache-mode', 'stream')
+    response.headers.set('x-local-cache-status', status)
+    response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString())
+    return response
+  }
 
-/***/ }),
-
-/***/ 65661:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  // use the provided request along with this cache entry to
+  // revalidate the stored response. returns a response, either
+  // from the cache or from the update
+  async revalidate (request, options) {
+    const revalidateRequest = new Request(request, {
+      headers: this.policy.revalidationHeaders(request),
+    })
 
-"use strict";
+    try {
+      // NOTE: be sure to remove the headers property from the
+      // user supplied options, since we have already defined
+      // them on the new request object. if they're still in the
+      // options then those will overwrite the ones from the policy
+      var response = await remote(revalidateRequest, {
+        ...options,
+        headers: undefined,
+      })
+    } catch (err) {
+      // if the network fetch fails, return the stale
+      // cached response unless it has a cache-control
+      // of 'must-revalidate'
+      if (!this.policy.mustRevalidate) {
+        return this.respond(request.method, options, 'stale')
+      }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.weakMap = void 0;
-const node_crypto_1 = __nccwpck_require__(77598);
-const errors_js_1 = __nccwpck_require__(15974);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const is_jwk_js_1 = __nccwpck_require__(91229);
-exports.weakMap = new WeakMap();
-const namedCurveToJOSE = (namedCurve) => {
-    switch (namedCurve) {
-        case 'prime256v1':
-            return 'P-256';
-        case 'secp384r1':
-            return 'P-384';
-        case 'secp521r1':
-            return 'P-521';
-        case 'secp256k1':
-            return 'secp256k1';
-        default:
-            throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation');
-    }
-};
-const getNamedCurve = (kee, raw) => {
-    let key;
-    if ((0, webcrypto_js_1.isCryptoKey)(kee)) {
-        key = node_crypto_1.KeyObject.from(kee);
-    }
-    else if ((0, is_key_object_js_1.default)(kee)) {
-        key = kee;
-    }
-    else if ((0, is_jwk_js_1.isJWK)(kee)) {
-        return kee.crv;
-    }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types));
-    }
-    if (key.type === 'secret') {
-        throw new TypeError('only "private" or "public" type keys can be used for this operation');
+      throw err
     }
-    switch (key.asymmetricKeyType) {
-        case 'ed25519':
-        case 'ed448':
-            return `Ed${key.asymmetricKeyType.slice(2)}`;
-        case 'x25519':
-        case 'x448':
-            return `X${key.asymmetricKeyType.slice(1)}`;
-        case 'ec': {
-            const namedCurve = key.asymmetricKeyDetails.namedCurve;
-            if (raw) {
-                return namedCurve;
-            }
-            return namedCurveToJOSE(namedCurve);
+
+    if (this.policy.revalidated(revalidateRequest, response)) {
+      // we got a 304, write a new index to the cache and respond from cache
+      const metadata = getMetadata(request, response, options)
+      // 304 responses do not include headers that are specific to the response data
+      // since they do not include a body, so we copy values for headers that were
+      // in the old cache entry to the new one, if the new metadata does not already
+      // include that header
+      for (const name of KEEP_RESPONSE_HEADERS) {
+        if (
+          !hasOwnProperty(metadata.resHeaders, name) &&
+          hasOwnProperty(this.entry.metadata.resHeaders, name)
+        ) {
+          metadata.resHeaders[name] = this.entry.metadata.resHeaders[name]
         }
-        default:
-            throw new TypeError('Invalid asymmetric key type for this operation');
+      }
+
+      for (const name of options.cacheAdditionalHeaders) {
+        const inMeta = hasOwnProperty(metadata.resHeaders, name)
+        const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name)
+        const inPolicy = hasOwnProperty(this.policy.response.headers, name)
+
+        // if the header is in the existing entry, but it is not in the metadata
+        // then we need to write it to the metadata as this will refresh the on-disk cache
+        if (!inMeta && inEntry) {
+          metadata.resHeaders[name] = this.entry.metadata.resHeaders[name]
+        }
+        // if the header is in the metadata, but not in the policy, then we need to set
+        // it in the policy so that it's included in the immediate response. future
+        // responses will load a new cache entry, so we don't need to change that
+        if (!inPolicy && inMeta) {
+          this.policy.response.headers[name] = metadata.resHeaders[name]
+        }
+      }
+
+      try {
+        await cacache.index.insert(options.cachePath, this.key, this.entry.integrity, {
+          size: this.entry.size,
+          metadata,
+        })
+      } catch (err) {
+        // if updating the cache index fails, we ignore it and
+        // respond anyway
+      }
+      return this.respond(request.method, options, 'revalidated')
     }
-};
-exports["default"] = getNamedCurve;
+
+    // if we got a modified response, create a new entry based on it
+    const newEntry = new CacheEntry({
+      request,
+      response,
+      options,
+    })
+
+    // respond with the new entry while writing it to the cache
+    return newEntry.store('updated')
+  }
+}
+
+module.exports = CacheEntry
 
 
 /***/ }),
 
-/***/ 80723:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 59456:
+/***/ ((module) => {
 
-"use strict";
+class NotCachedError extends Error {
+  constructor (url) {
+    /* eslint-disable-next-line max-len */
+    super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`)
+    this.code = 'ENOTCACHED'
+  }
+}
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = getSignVerifyKey;
-const node_crypto_1 = __nccwpck_require__(77598);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const jwk = __nccwpck_require__(91229);
-function getSignVerifyKey(alg, key, usage) {
-    if (key instanceof Uint8Array) {
-        if (!alg.startsWith('HS')) {
-            throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
-        }
-        return (0, node_crypto_1.createSecretKey)(key);
-    }
-    if (key instanceof node_crypto_1.KeyObject) {
-        return key;
-    }
-    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
-        (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage);
-        return node_crypto_1.KeyObject.from(key);
-    }
-    if (jwk.isJWK(key)) {
-        if (alg.startsWith('HS')) {
-            return (0, node_crypto_1.createSecretKey)(Buffer.from(key.k, 'base64url'));
-        }
-        return key;
-    }
-    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array', 'JSON Web Key'));
+module.exports = {
+  NotCachedError,
 }
 
 
 /***/ }),
 
-/***/ 57399:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 96807:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const { NotCachedError } = __nccwpck_require__(59456)
+const CacheEntry = __nccwpck_require__(85743)
+const remote = __nccwpck_require__(20766)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = hmacDigest;
-const errors_js_1 = __nccwpck_require__(15974);
-function hmacDigest(alg) {
-    switch (alg) {
-        case 'HS256':
-            return 'sha256';
-        case 'HS384':
-            return 'sha384';
-        case 'HS512':
-            return 'sha512';
-        default:
-            throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+// do whatever is necessary to get a Response and return it
+const cacheFetch = async (request, options) => {
+  // try to find a cached entry that satisfies this request
+  const entry = await CacheEntry.find(request, options)
+  if (!entry) {
+    // no cached result, if the cache mode is 'only-if-cached' that's a failure
+    if (options.cache === 'only-if-cached') {
+      throw new NotCachedError(request.url)
     }
-}
 
+    // otherwise, we make a request, store it and return it
+    const response = await remote(request, options)
+    const newEntry = new CacheEntry({ request, response, options })
+    return newEntry.store('miss')
+  }
 
-/***/ }),
+  // we have a cached response that satisfies this request, however if the cache
+  // mode is 'no-cache' then we send the revalidation request no matter what
+  if (options.cache === 'no-cache') {
+    return entry.revalidate(request, options)
+  }
 
-/***/ 7433:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  // if the cached entry is not stale, or if the cache mode is 'force-cache' or
+  // 'only-if-cached' we can respond with the cached entry. set the status
+  // based on the result of needsRevalidation and respond
+  const _needsRevalidation = entry.policy.needsRevalidation(request)
+  if (options.cache === 'force-cache' ||
+      options.cache === 'only-if-cached' ||
+      !_needsRevalidation) {
+    return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit')
+  }
 
-"use strict";
+  // if we got here, the cache entry is stale so revalidate it
+  return entry.revalidate(request, options)
+}
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.types = void 0;
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-exports["default"] = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key);
-const types = ['KeyObject'];
-exports.types = types;
-if (globalThis.CryptoKey || webcrypto_js_1.default?.CryptoKey) {
-    types.push('CryptoKey');
+cacheFetch.invalidate = async (request, options) => {
+  if (!options.cachePath) {
+    return
+  }
+
+  return CacheEntry.invalidate(request, options)
 }
 
+module.exports = cacheFetch
+
 
 /***/ }),
 
-/***/ 68685:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 45808:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const { URL, format } = __nccwpck_require__(87016)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const util = __nccwpck_require__(57975);
-exports["default"] = (obj) => util.types.isKeyObject(obj);
+// options passed to url.format() when generating a key
+const formatOptions = {
+  auth: false,
+  fragment: false,
+  search: true,
+  unicode: false,
+}
+
+// returns a string to be used as the cache key for the Request
+const cacheKey = (request) => {
+  const parsed = new URL(request.url)
+  return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}`
+}
+
+module.exports = cacheKey
 
 
 /***/ }),
 
-/***/ 80939:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 15281:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const CacheSemantics = __nccwpck_require__(12203)
+const Negotiator = __nccwpck_require__(60668)
+const ssri = __nccwpck_require__(68951)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-const parse = (key) => {
-    if (key.d) {
-        return (0, node_crypto_1.createPrivateKey)({ format: 'jwk', key });
-    }
-    return (0, node_crypto_1.createPublicKey)({ format: 'jwk', key });
-};
-exports["default"] = parse;
+// options passed to http-cache-semantics constructor
+const policyOptions = {
+  shared: false,
+  ignoreCargoCult: true,
+}
 
+// a fake empty response, used when only testing the
+// request for storability
+const emptyResponse = { status: 200, headers: {} }
 
-/***/ }),
+// returns a plain object representation of the Request
+const requestObject = (request) => {
+  const _obj = {
+    method: request.method,
+    url: request.url,
+    headers: {},
+    compress: request.compress,
+  }
 
-/***/ 9041:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  request.headers.forEach((value, key) => {
+    _obj.headers[key] = value
+  })
 
-"use strict";
+  return _obj
+}
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-const base64url_js_1 = __nccwpck_require__(12635);
-const errors_js_1 = __nccwpck_require__(15974);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const keyToJWK = (key) => {
-    let keyObject;
-    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
-        if (!key.extractable) {
-            throw new TypeError('CryptoKey is not extractable');
-        }
-        keyObject = node_crypto_1.KeyObject.from(key);
-    }
-    else if ((0, is_key_object_js_1.default)(key)) {
-        keyObject = key;
-    }
-    else if (key instanceof Uint8Array) {
-        return {
-            kty: 'oct',
-            k: (0, base64url_js_1.encode)(key),
-        };
-    }
-    else {
-        throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));
-    }
-    if (keyObject.type !== 'secret' &&
-        !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
-        throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType');
-    }
-    return keyObject.export({ format: 'jwk' });
-};
-exports["default"] = keyToJWK;
+// returns a plain object representation of the Response
+const responseObject = (response) => {
+  const _obj = {
+    status: response.status,
+    headers: {},
+  }
 
+  response.headers.forEach((value, key) => {
+    _obj.headers[key] = value
+  })
 
-/***/ }),
+  return _obj
+}
 
-/***/ 70363:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+class CachePolicy {
+  constructor ({ entry, request, response, options }) {
+    this.entry = entry
+    this.request = requestObject(request)
+    this.response = responseObject(response)
+    this.options = options
+    this.policy = new CacheSemantics(this.request, this.response, policyOptions)
 
-"use strict";
+    if (this.entry) {
+      // if we have an entry, copy the timestamp to the _responseTime
+      // this is necessary because the CacheSemantics constructor forces
+      // the value to Date.now() which means a policy created from a
+      // cache entry is likely to always identify itself as stale
+      this.policy._responseTime = this.entry.metadata.time
+    }
+  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = keyForCrypto;
-const node_crypto_1 = __nccwpck_require__(77598);
-const get_named_curve_js_1 = __nccwpck_require__(65661);
-const errors_js_1 = __nccwpck_require__(15974);
-const check_key_length_js_1 = __nccwpck_require__(65142);
-const ecCurveAlgMap = new Map([
-    ['ES256', 'P-256'],
-    ['ES256K', 'secp256k1'],
-    ['ES384', 'P-384'],
-    ['ES512', 'P-521'],
-]);
-function keyForCrypto(alg, key) {
-    let asymmetricKeyType;
-    let asymmetricKeyDetails;
-    let isJWK;
-    if (key instanceof node_crypto_1.KeyObject) {
-        asymmetricKeyType = key.asymmetricKeyType;
-        asymmetricKeyDetails = key.asymmetricKeyDetails;
+  // static method to quickly determine if a request alone is storable
+  static storable (request, options) {
+    // no cachePath means no caching
+    if (!options.cachePath) {
+      return false
     }
-    else {
-        isJWK = true;
-        switch (key.kty) {
-            case 'RSA':
-                asymmetricKeyType = 'rsa';
-                break;
-            case 'EC':
-                asymmetricKeyType = 'ec';
-                break;
-            case 'OKP': {
-                if (key.crv === 'Ed25519') {
-                    asymmetricKeyType = 'ed25519';
-                    break;
-                }
-                if (key.crv === 'Ed448') {
-                    asymmetricKeyType = 'ed448';
-                    break;
-                }
-                throw new TypeError('Invalid key for this operation, its crv must be Ed25519 or Ed448');
-            }
-            default:
-                throw new TypeError('Invalid key for this operation, its kty must be RSA, OKP, or EC');
-        }
+
+    // user explicitly asked not to cache
+    if (options.cache === 'no-store') {
+      return false
     }
-    let options;
-    switch (alg) {
-        case 'EdDSA':
-            if (!['ed25519', 'ed448'].includes(asymmetricKeyType)) {
-                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448');
-            }
-            break;
-        case 'RS256':
-        case 'RS384':
-        case 'RS512':
-            if (asymmetricKeyType !== 'rsa') {
-                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
-            }
-            (0, check_key_length_js_1.default)(key, alg);
-            break;
-        case 'PS256':
-        case 'PS384':
-        case 'PS512':
-            if (asymmetricKeyType === 'rsa-pss') {
-                const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails;
-                const length = parseInt(alg.slice(-3), 10);
-                if (hashAlgorithm !== undefined &&
-                    (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {
-                    throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`);
-                }
-                if (saltLength !== undefined && saltLength > length >> 3) {
-                    throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`);
-                }
-            }
-            else if (asymmetricKeyType !== 'rsa') {
-                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss');
-            }
-            (0, check_key_length_js_1.default)(key, alg);
-            options = {
-                padding: node_crypto_1.constants.RSA_PKCS1_PSS_PADDING,
-                saltLength: node_crypto_1.constants.RSA_PSS_SALTLEN_DIGEST,
-            };
-            break;
-        case 'ES256':
-        case 'ES256K':
-        case 'ES384':
-        case 'ES512': {
-            if (asymmetricKeyType !== 'ec') {
-                throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec');
-            }
-            const actual = (0, get_named_curve_js_1.default)(key);
-            const expected = ecCurveAlgMap.get(alg);
-            if (actual !== expected) {
-                throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);
-            }
-            options = { dsaEncoding: 'ieee-p1363' };
-            break;
-        }
-        default:
-            throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+
+    // we only cache GET and HEAD requests
+    if (!['GET', 'HEAD'].includes(request.method)) {
+      return false
     }
-    if (isJWK) {
-        return { format: 'jwk', key, ...options };
+
+    // otherwise, let http-cache-semantics make the decision
+    // based on the request's headers
+    const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions)
+    return policy.storable()
+  }
+
+  // returns true if the policy satisfies the request
+  satisfies (request) {
+    const _req = requestObject(request)
+    if (this.request.headers.host !== _req.headers.host) {
+      return false
     }
-    return options ? { ...options, key } : key;
+
+    if (this.request.compress !== _req.compress) {
+      return false
+    }
+
+    const negotiatorA = new Negotiator(this.request)
+    const negotiatorB = new Negotiator(_req)
+
+    if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) {
+      return false
+    }
+
+    if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) {
+      return false
+    }
+
+    if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) {
+      return false
+    }
+
+    if (this.options.integrity) {
+      return ssri.parse(this.options.integrity).match(this.entry.integrity)
+    }
+
+    return true
+  }
+
+  // returns true if the request and response allow caching
+  storable () {
+    return this.policy.storable()
+  }
+
+  // NOTE: this is a hack to avoid parsing the cache-control
+  // header ourselves, it returns true if the response's
+  // cache-control contains must-revalidate
+  get mustRevalidate () {
+    return !!this.policy._rescc['must-revalidate']
+  }
+
+  // returns true if the cached response requires revalidation
+  // for the given request
+  needsRevalidation (request) {
+    const _req = requestObject(request)
+    // force method to GET because we only cache GETs
+    // but can serve a HEAD from a cached GET
+    _req.method = 'GET'
+    return !this.policy.satisfiesWithoutRevalidation(_req)
+  }
+
+  responseHeaders () {
+    return this.policy.responseHeaders()
+  }
+
+  // returns a new object containing the appropriate headers
+  // to send a revalidation request
+  revalidationHeaders (request) {
+    const _req = requestObject(request)
+    return this.policy.revalidationHeaders(_req)
+  }
+
+  // returns true if the request/response was revalidated
+  // successfully. returns false if a new response was received
+  revalidated (request, response) {
+    const _req = requestObject(request)
+    const _res = responseObject(response)
+    const policy = this.policy.revalidatedPolicy(_req, _res)
+    return !policy.modified
+  }
 }
 
+module.exports = CachePolicy
+
 
 /***/ }),
 
-/***/ 51276:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 67242:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = {};
 
+const { FetchError, Request, isRedirect } = __nccwpck_require__(88483)
+const url = __nccwpck_require__(87016)
 
-/***/ }),
+const CachePolicy = __nccwpck_require__(15281)
+const cache = __nccwpck_require__(96807)
+const remote = __nccwpck_require__(20766)
 
-/***/ 52741:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// given a Request, a Response and user options
+// return true if the response is a redirect that
+// can be followed. we throw errors that will result
+// in the fetch being rejected if the redirect is
+// possible but invalid for some reason
+const canFollowRedirect = (request, response, options) => {
+  if (!isRedirect(response.status)) {
+    return false
+  }
 
-"use strict";
+  if (options.redirect === 'manual') {
+    return false
+  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decrypt = exports.encrypt = void 0;
-const node_util_1 = __nccwpck_require__(57975);
-const node_crypto_1 = __nccwpck_require__(77598);
-const random_js_1 = __nccwpck_require__(23376);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const base64url_js_1 = __nccwpck_require__(12635);
-const aeskw_js_1 = __nccwpck_require__(76202);
-const check_p2s_js_1 = __nccwpck_require__(88040);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const pbkdf2 = (0, node_util_1.promisify)(node_crypto_1.pbkdf2);
-function getPassword(key, alg) {
-    if ((0, is_key_object_js_1.default)(key)) {
-        return key.export();
-    }
-    if (key instanceof Uint8Array) {
-        return key;
-    }
-    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey');
-        return node_crypto_1.KeyObject.from(key).export();
-    }
-    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));
+  if (options.redirect === 'error') {
+    throw new FetchError(`redirect mode is set to error: ${request.url}`,
+      'no-redirect', { code: 'ENOREDIRECT' })
+  }
+
+  if (!response.headers.has('location')) {
+    throw new FetchError(`redirect location header missing for: ${request.url}`,
+      'no-location', { code: 'EINVALIDREDIRECT' })
+  }
+
+  if (request.counter >= request.follow) {
+    throw new FetchError(`maximum redirect reached at: ${request.url}`,
+      'max-redirect', { code: 'EMAXREDIRECT' })
+  }
+
+  return true
 }
-const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => {
-    (0, check_p2s_js_1.default)(p2s);
-    const salt = (0, buffer_utils_js_1.p2s)(alg, p2s);
-    const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
-    const password = getPassword(key, alg);
-    const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
-    const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek);
-    return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) };
-};
-exports.encrypt = encrypt;
-const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
-    (0, check_p2s_js_1.default)(p2s);
-    const salt = (0, buffer_utils_js_1.p2s)(alg, p2s);
-    const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
-    const password = getPassword(key, alg);
-    const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
-    return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey);
-};
-exports.decrypt = decrypt;
 
+// given a Request, a Response, and the user's options return an object
+// with a new Request and a new options object that will be used for
+// following the redirect
+const getRedirect = (request, response, options) => {
+  const _opts = { ...options }
+  const location = response.headers.get('location')
+  const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url)
+  // Comment below is used under the following license:
+  /**
+   * @license
+   * Copyright (c) 2010-2012 Mikeal Rogers
+   * Licensed under the Apache License, Version 2.0 (the "License");
+   * you may not use this file except in compliance with the License.
+   * You may obtain a copy of the License at
+   * http://www.apache.org/licenses/LICENSE-2.0
+   * Unless required by applicable law or agreed to in writing,
+   * software distributed under the License is distributed on an "AS
+   * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+   * express or implied. See the License for the specific language
+   * governing permissions and limitations under the License.
+   */
+
+  // Remove authorization if changing hostnames (but not if just
+  // changing ports or protocols).  This matches the behavior of request:
+  // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138
+  if (new url.URL(request.url).hostname !== redirectUrl.hostname) {
+    request.headers.delete('authorization')
+    request.headers.delete('cookie')
+  }
 
-/***/ }),
+  // for POST request with 301/302 response, or any request with 303 response,
+  // use GET when following redirect
+  if (
+    response.status === 303 ||
+    (request.method === 'POST' && [301, 302].includes(response.status))
+  ) {
+    _opts.method = 'GET'
+    _opts.body = null
+    request.headers.delete('content-length')
+  }
 
-/***/ 23376:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  _opts.headers = {}
+  request.headers.forEach((value, key) => {
+    _opts.headers[key] = value
+  })
 
-"use strict";
+  _opts.counter = ++request.counter
+  const redirectReq = new Request(url.format(redirectUrl), _opts)
+  return {
+    request: redirectReq,
+    options: _opts,
+  }
+}
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = void 0;
-var node_crypto_1 = __nccwpck_require__(77598);
-Object.defineProperty(exports, "default", ({ enumerable: true, get: function () { return node_crypto_1.randomFillSync; } }));
+const fetch = async (request, options) => {
+  const response = CachePolicy.storable(request, options)
+    ? await cache(request, options)
+    : await remote(request, options)
+
+  // if the request wasn't a GET or HEAD, and the response
+  // status is between 200 and 399 inclusive, invalidate the
+  // request url
+  if (!['GET', 'HEAD'].includes(request.method) &&
+      response.status >= 200 &&
+      response.status <= 399) {
+    await cache.invalidate(request, options)
+  }
+
+  if (!canFollowRedirect(request, response, options)) {
+    return response
+  }
+
+  const redirect = getRedirect(request, response, options)
+  return fetch(redirect.request, redirect.options)
+}
+
+module.exports = fetch
 
 
 /***/ }),
 
-/***/ 61129:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 39310:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const { FetchError, Headers, Request, Response } = __nccwpck_require__(88483)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decrypt = exports.encrypt = void 0;
-const node_crypto_1 = __nccwpck_require__(77598);
-const node_util_1 = __nccwpck_require__(57975);
-const check_key_length_js_1 = __nccwpck_require__(65142);
-const webcrypto_js_1 = __nccwpck_require__(59044);
-const crypto_key_js_1 = __nccwpck_require__(26319);
-const is_key_object_js_1 = __nccwpck_require__(68685);
-const invalid_key_input_js_1 = __nccwpck_require__(16632);
-const is_key_like_js_1 = __nccwpck_require__(7433);
-const checkKey = (key, alg) => {
-    if (key.asymmetricKeyType !== 'rsa') {
-        throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
-    }
-    (0, check_key_length_js_1.default)(key, alg);
-};
-const RSA1_5 = (0, node_util_1.deprecate)(() => node_crypto_1.constants.RSA_PKCS1_PADDING, 'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.');
-const resolvePadding = (alg) => {
-    switch (alg) {
-        case 'RSA-OAEP':
-        case 'RSA-OAEP-256':
-        case 'RSA-OAEP-384':
-        case 'RSA-OAEP-512':
-            return node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING;
-        case 'RSA1_5':
-            return RSA1_5();
-        default:
-            return undefined;
-    }
-};
-const resolveOaepHash = (alg) => {
-    switch (alg) {
-        case 'RSA-OAEP':
-            return 'sha1';
-        case 'RSA-OAEP-256':
-            return 'sha256';
-        case 'RSA-OAEP-384':
-            return 'sha384';
-        case 'RSA-OAEP-512':
-            return 'sha512';
-        default:
-            return undefined;
-    }
-};
-function ensureKeyObject(key, alg, ...usages) {
-    if ((0, is_key_object_js_1.default)(key)) {
-        return key;
-    }
-    if ((0, webcrypto_js_1.isCryptoKey)(key)) {
-        (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages);
-        return node_crypto_1.KeyObject.from(key);
+const configureOptions = __nccwpck_require__(99824)
+const fetch = __nccwpck_require__(67242)
+
+const makeFetchHappen = (url, opts) => {
+  const options = configureOptions(opts)
+
+  const request = new Request(url, options)
+  return fetch(request, options)
+}
+
+makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => {
+  if (typeof defaultUrl === 'object') {
+    defaultOptions = defaultUrl
+    defaultUrl = null
+  }
+
+  const defaultedFetch = (url, options = {}) => {
+    const finalUrl = url || defaultUrl
+    const finalOptions = {
+      ...defaultOptions,
+      ...options,
+      headers: {
+        ...defaultOptions.headers,
+        ...options.headers,
+      },
     }
-    throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
+    return wrappedFetch(finalUrl, finalOptions)
+  }
+
+  defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) =>
+    makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch)
+  return defaultedFetch
 }
-const encrypt = (alg, key, cek) => {
-    const padding = resolvePadding(alg);
-    const oaepHash = resolveOaepHash(alg);
-    const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt');
-    checkKey(keyObject, alg);
-    return (0, node_crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek);
-};
-exports.encrypt = encrypt;
-const decrypt = (alg, key, encryptedKey) => {
-    const padding = resolvePadding(alg);
-    const oaepHash = resolveOaepHash(alg);
-    const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt');
-    checkKey(keyObject, alg);
-    return (0, node_crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey);
-};
-exports.decrypt = decrypt;
+
+module.exports = makeFetchHappen
+module.exports.FetchError = FetchError
+module.exports.Headers = Headers
+module.exports.Request = Request
+module.exports.Response = Response
 
 
 /***/ }),
 
-/***/ 95527:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 99824:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const dns = __nccwpck_require__(72250)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports["default"] = 'node:crypto';
+const conditionalHeaders = [
+  'if-modified-since',
+  'if-none-match',
+  'if-unmodified-since',
+  'if-match',
+  'if-range',
+]
 
+const configureOptions = (opts) => {
+  const { strictSSL, ...options } = { ...opts }
+  options.method = options.method ? options.method.toUpperCase() : 'GET'
 
-/***/ }),
+  if (strictSSL === undefined || strictSSL === null) {
+    options.rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'
+  } else {
+    options.rejectUnauthorized = strictSSL !== false
+  }
 
-/***/ 26966:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  if (!options.retry) {
+    options.retry = { retries: 0 }
+  } else if (typeof options.retry === 'string') {
+    const retries = parseInt(options.retry, 10)
+    if (isFinite(retries)) {
+      options.retry = { retries }
+    } else {
+      options.retry = { retries: 0 }
+    }
+  } else if (typeof options.retry === 'number') {
+    options.retry = { retries: options.retry }
+  } else {
+    options.retry = { retries: 0, ...options.retry }
+  }
 
-"use strict";
+  options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const crypto = __nccwpck_require__(77598);
-const node_util_1 = __nccwpck_require__(57975);
-const dsa_digest_js_1 = __nccwpck_require__(74510);
-const hmac_digest_js_1 = __nccwpck_require__(57399);
-const node_key_js_1 = __nccwpck_require__(70363);
-const get_sign_verify_key_js_1 = __nccwpck_require__(80723);
-const oneShotSign = (0, node_util_1.promisify)(crypto.sign);
-const sign = async (alg, key, data) => {
-    const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign');
-    if (alg.startsWith('HS')) {
-        const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), k);
-        hmac.update(data);
-        return hmac.digest();
+  options.cache = options.cache || 'default'
+  if (options.cache === 'default') {
+    const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => {
+      return conditionalHeaders.includes(name.toLowerCase())
+    })
+    if (hasConditionalHeader) {
+      options.cache = 'no-store'
     }
-    return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, k));
-};
-exports["default"] = sign;
-
+  }
 
-/***/ }),
+  options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || []
 
-/***/ 39106:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+  // cacheManager is deprecated, but if it's set and
+  // cachePath is not we should copy it to the new field
+  if (options.cacheManager && !options.cachePath) {
+    options.cachePath = options.cacheManager
+  }
 
-"use strict";
+  return options
+}
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const node_crypto_1 = __nccwpck_require__(77598);
-const timingSafeEqual = node_crypto_1.timingSafeEqual;
-exports["default"] = timingSafeEqual;
+module.exports = configureOptions
 
 
 /***/ }),
 
-/***/ 11242:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 22314:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const crypto = __nccwpck_require__(77598);
-const node_util_1 = __nccwpck_require__(57975);
-const dsa_digest_js_1 = __nccwpck_require__(74510);
-const node_key_js_1 = __nccwpck_require__(70363);
-const sign_js_1 = __nccwpck_require__(26966);
-const get_sign_verify_key_js_1 = __nccwpck_require__(80723);
-const oneShotVerify = (0, node_util_1.promisify)(crypto.verify);
-const verify = async (alg, key, signature, data) => {
-    const k = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify');
-    if (alg.startsWith('HS')) {
-        const expected = await (0, sign_js_1.default)(alg, k, data);
-        const actual = signature;
-        try {
-            return crypto.timingSafeEqual(actual, expected);
-        }
-        catch {
-            return false;
-        }
+
+const MinipassPipeline = __nccwpck_require__(52899)
+
+class CachingMinipassPipeline extends MinipassPipeline {
+  #events = []
+  #data = new Map()
+
+  constructor (opts, ...streams) {
+    // CRITICAL: do NOT pass the streams to the call to super(), this will start
+    // the flow of data and potentially cause the events we need to catch to emit
+    // before we've finished our own setup. instead we call super() with no args,
+    // finish our setup, and then push the streams into ourselves to start the
+    // data flow
+    super()
+    this.#events = opts.events
+
+    /* istanbul ignore next - coverage disabled because this is pointless to test here */
+    if (streams.length) {
+      this.push(...streams)
     }
-    const algorithm = (0, dsa_digest_js_1.default)(alg);
-    const keyInput = (0, node_key_js_1.default)(alg, k);
-    try {
-        return await oneShotVerify(algorithm, data, keyInput, signature);
+  }
+
+  on (event, handler) {
+    if (this.#events.includes(event) && this.#data.has(event)) {
+      return handler(...this.#data.get(event))
     }
-    catch {
-        return false;
+
+    return super.on(event, handler)
+  }
+
+  emit (event, ...data) {
+    if (this.#events.includes(event)) {
+      this.#data.set(event, data)
     }
-};
-exports["default"] = verify;
+
+    return super.emit(event, ...data)
+  }
+}
+
+module.exports = CachingMinipassPipeline
 
 
 /***/ }),
 
-/***/ 59044:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 20766:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const { Minipass } = __nccwpck_require__(78275)
+const fetch = __nccwpck_require__(88483)
+const promiseRetry = __nccwpck_require__(90390)
+const ssri = __nccwpck_require__(68951)
+const { log } = __nccwpck_require__(26687)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isCryptoKey = void 0;
-const crypto = __nccwpck_require__(77598);
-const util = __nccwpck_require__(57975);
-const webcrypto = crypto.webcrypto;
-exports["default"] = webcrypto;
-const isCryptoKey = (key) => util.types.isCryptoKey(key);
-exports.isCryptoKey = isCryptoKey;
+const CachingMinipassPipeline = __nccwpck_require__(22314)
+const { getAgent } = __nccwpck_require__(57995)
+const pkg = __nccwpck_require__(96734)
 
+const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})`
 
-/***/ }),
+const RETRY_ERRORS = [
+  'ECONNRESET', // remote socket closed on us
+  'ECONNREFUSED', // remote host refused to open connection
+  'EADDRINUSE', // failed to bind to a local port (proxy?)
+  'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW
+  // from @npmcli/agent
+  'ECONNECTIONTIMEOUT',
+  'EIDLETIMEOUT',
+  'ERESPONSETIMEOUT',
+  'ETRANSFERTIMEOUT',
+  // Known codes we do NOT retry on:
+  // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline)
+  // EINVALIDPROXY // invalid protocol from @npmcli/agent
+  // EINVALIDRESPONSE // invalid status code from @npmcli/agent
+]
 
-/***/ 78305:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const RETRY_TYPES = [
+  'request-timeout',
+]
 
-"use strict";
+// make a request directly to the remote source,
+// retrying certain classes of errors as well as
+// following redirects (through the cache if necessary)
+// and verifying response integrity
+const remoteFetch = (request, options) => {
+  // options.signal is intended for the fetch itself, not the agent.  Attaching it to the agent will re-use that signal across multiple requests, which prevents any connections beyond the first one.
+  const agent = getAgent(request.url, { ...options, signal: undefined })
+  if (!request.headers.has('connection')) {
+    request.headers.set('connection', agent ? 'keep-alive' : 'close')
+  }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decode = exports.encode = void 0;
-const base64url = __nccwpck_require__(12635);
-exports.encode = base64url.encode;
-exports.decode = base64url.decode;
+  if (!request.headers.has('user-agent')) {
+    request.headers.set('user-agent', USER_AGENT)
+  }
 
+  // keep our own options since we're overriding the agent
+  // and the redirect mode
+  const _opts = {
+    ...options,
+    agent,
+    redirect: 'manual',
+  }
 
-/***/ }),
+  return promiseRetry(async (retryHandler, attemptNum) => {
+    const req = new fetch.Request(request, _opts)
+    try {
+      let res = await fetch(req, _opts)
+      if (_opts.integrity && res.status === 200) {
+        // we got a 200 response and the user has specified an expected
+        // integrity value, so wrap the response in an ssri stream to verify it
+        const integrityStream = ssri.integrityStream({
+          algorithms: _opts.algorithms,
+          integrity: _opts.integrity,
+          size: _opts.size,
+        })
+        const pipeline = new CachingMinipassPipeline({
+          events: ['integrity', 'size'],
+        }, res.body, integrityStream)
+        // we also propagate the integrity and size events out to the pipeline so we can use
+        // this new response body as an integrityEmitter for cacache
+        integrityStream.on('integrity', i => pipeline.emit('integrity', i))
+        integrityStream.on('size', s => pipeline.emit('size', s))
+        res = new fetch.Response(pipeline, res)
+        // set an explicit flag so we know if our response body will emit integrity and size
+        res.body.hasIntegrityEmitter = true
+      }
 
-/***/ 60002:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+      res.headers.set('x-fetch-attempts', attemptNum)
 
-"use strict";
+      // do not retry POST requests, or requests with a streaming body
+      // do retry requests with a 408, 420, 429 or 500+ status in the response
+      const isStream = Minipass.isStream(req.body)
+      const isRetriable = req.method !== 'POST' &&
+          !isStream &&
+          ([408, 420, 429].includes(res.status) || res.status >= 500)
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decodeJwt = decodeJwt;
-const base64url_js_1 = __nccwpck_require__(78305);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const is_object_js_1 = __nccwpck_require__(92242);
-const errors_js_1 = __nccwpck_require__(15974);
-function decodeJwt(jwt) {
-    if (typeof jwt !== 'string')
-        throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
-    const { 1: payload, length } = jwt.split('.');
-    if (length === 5)
-        throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
-    if (length !== 3)
-        throw new errors_js_1.JWTInvalid('Invalid JWT');
-    if (!payload)
-        throw new errors_js_1.JWTInvalid('JWTs must contain a payload');
-    let decoded;
-    try {
-        decoded = (0, base64url_js_1.decode)(payload);
-    }
-    catch {
-        throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload');
-    }
-    let result;
-    try {
-        result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded));
-    }
-    catch {
-        throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON');
-    }
-    if (!(0, is_object_js_1.default)(result))
-        throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set');
-    return result;
-}
+      if (isRetriable) {
+        if (typeof options.onRetry === 'function') {
+          options.onRetry(res)
+        }
 
+        /* eslint-disable-next-line max-len */
+        log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`)
+        return retryHandler(res)
+      }
 
-/***/ }),
+      return res
+    } catch (err) {
+      const code = (err.code === 'EPROMISERETRY')
+        ? err.retried.code
+        : err.code
 
-/***/ 14704:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+      // err.retried will be the thing that was thrown from above
+      // if it's a response, we just got a bad status code and we
+      // can re-throw to allow the retry
+      const isRetryError = err.retried instanceof fetch.Response ||
+        (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type))
 
-"use strict";
+      if (req.method === 'POST' || isRetryError) {
+        throw err
+      }
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decodeProtectedHeader = decodeProtectedHeader;
-const base64url_js_1 = __nccwpck_require__(78305);
-const buffer_utils_js_1 = __nccwpck_require__(45734);
-const is_object_js_1 = __nccwpck_require__(92242);
-function decodeProtectedHeader(token) {
-    let protectedB64u;
-    if (typeof token === 'string') {
-        const parts = token.split('.');
-        if (parts.length === 3 || parts.length === 5) {
-            ;
-            [protectedB64u] = parts;
-        }
-    }
-    else if (typeof token === 'object' && token) {
-        if ('protected' in token) {
-            protectedB64u = token.protected;
-        }
-        else {
-            throw new TypeError('Token does not contain a Protected Header');
-        }
-    }
-    try {
-        if (typeof protectedB64u !== 'string' || !protectedB64u) {
-            throw new Error();
-        }
-        const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u)));
-        if (!(0, is_object_js_1.default)(result)) {
-            throw new Error();
-        }
-        return result;
+      if (typeof options.onRetry === 'function') {
+        options.onRetry(err)
+      }
+
+      log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`)
+      return retryHandler(err)
     }
-    catch {
-        throw new TypeError('Invalid Token or Protected Header formatting');
+  }, options.retry).catch((err) => {
+    // don't reject for http errors, just return them
+    if (err.status >= 400 && err.type !== 'system') {
+      return err
     }
+
+    throw err
+  })
 }
 
+module.exports = remoteFetch
+
 
 /***/ }),
 
-/***/ 15974:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 43772:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+module.exports = minimatch
+minimatch.Minimatch = Minimatch
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0;
-class JOSEError extends Error {
-    static code = 'ERR_JOSE_GENERIC';
-    code = 'ERR_JOSE_GENERIC';
-    constructor(message, options) {
-        super(message, options);
-        this.name = this.constructor.name;
-        Error.captureStackTrace?.(this, this.constructor);
-    }
-}
-exports.JOSEError = JOSEError;
-class JWTClaimValidationFailed extends JOSEError {
-    static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
-    code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
-    claim;
-    reason;
-    payload;
-    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
-        super(message, { cause: { claim, reason, payload } });
-        this.claim = claim;
-        this.reason = reason;
-        this.payload = payload;
-    }
-}
-exports.JWTClaimValidationFailed = JWTClaimValidationFailed;
-class JWTExpired extends JOSEError {
-    static code = 'ERR_JWT_EXPIRED';
-    code = 'ERR_JWT_EXPIRED';
-    claim;
-    reason;
-    payload;
-    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
-        super(message, { cause: { claim, reason, payload } });
-        this.claim = claim;
-        this.reason = reason;
-        this.payload = payload;
-    }
-}
-exports.JWTExpired = JWTExpired;
-class JOSEAlgNotAllowed extends JOSEError {
-    static code = 'ERR_JOSE_ALG_NOT_ALLOWED';
-    code = 'ERR_JOSE_ALG_NOT_ALLOWED';
-}
-exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed;
-class JOSENotSupported extends JOSEError {
-    static code = 'ERR_JOSE_NOT_SUPPORTED';
-    code = 'ERR_JOSE_NOT_SUPPORTED';
-}
-exports.JOSENotSupported = JOSENotSupported;
-class JWEDecryptionFailed extends JOSEError {
-    static code = 'ERR_JWE_DECRYPTION_FAILED';
-    code = 'ERR_JWE_DECRYPTION_FAILED';
-    constructor(message = 'decryption operation failed', options) {
-        super(message, options);
-    }
-}
-exports.JWEDecryptionFailed = JWEDecryptionFailed;
-class JWEInvalid extends JOSEError {
-    static code = 'ERR_JWE_INVALID';
-    code = 'ERR_JWE_INVALID';
-}
-exports.JWEInvalid = JWEInvalid;
-class JWSInvalid extends JOSEError {
-    static code = 'ERR_JWS_INVALID';
-    code = 'ERR_JWS_INVALID';
-}
-exports.JWSInvalid = JWSInvalid;
-class JWTInvalid extends JOSEError {
-    static code = 'ERR_JWT_INVALID';
-    code = 'ERR_JWT_INVALID';
-}
-exports.JWTInvalid = JWTInvalid;
-class JWKInvalid extends JOSEError {
-    static code = 'ERR_JWK_INVALID';
-    code = 'ERR_JWK_INVALID';
-}
-exports.JWKInvalid = JWKInvalid;
-class JWKSInvalid extends JOSEError {
-    static code = 'ERR_JWKS_INVALID';
-    code = 'ERR_JWKS_INVALID';
-}
-exports.JWKSInvalid = JWKSInvalid;
-class JWKSNoMatchingKey extends JOSEError {
-    static code = 'ERR_JWKS_NO_MATCHING_KEY';
-    code = 'ERR_JWKS_NO_MATCHING_KEY';
-    constructor(message = 'no applicable key found in the JSON Web Key Set', options) {
-        super(message, options);
-    }
-}
-exports.JWKSNoMatchingKey = JWKSNoMatchingKey;
-class JWKSMultipleMatchingKeys extends JOSEError {
-    [Symbol.asyncIterator];
-    static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
-    code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
-    constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {
-        super(message, options);
-    }
-}
-exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys;
-class JWKSTimeout extends JOSEError {
-    static code = 'ERR_JWKS_TIMEOUT';
-    code = 'ERR_JWKS_TIMEOUT';
-    constructor(message = 'request timed out', options) {
-        super(message, options);
-    }
+var path = (function () { try { return __nccwpck_require__(16928) } catch (e) {}}()) || {
+  sep: '/'
 }
-exports.JWKSTimeout = JWKSTimeout;
-class JWSSignatureVerificationFailed extends JOSEError {
-    static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
-    code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
-    constructor(message = 'signature verification failed', options) {
-        super(message, options);
-    }
+minimatch.sep = path.sep
+
+var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
+var expand = __nccwpck_require__(94691)
+
+var plTypes = {
+  '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
+  '?': { open: '(?:', close: ')?' },
+  '+': { open: '(?:', close: ')+' },
+  '*': { open: '(?:', close: ')*' },
+  '@': { open: '(?:', close: ')' }
 }
-exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed;
 
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+var qmark = '[^/]'
 
-/***/ }),
+// * => any number of characters
+var star = qmark + '*?'
 
-/***/ 25021:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// ** when dots are allowed.  Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
 
-"use strict";
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const runtime_js_1 = __nccwpck_require__(95527);
-exports["default"] = runtime_js_1.default;
+// characters that need to be escaped in RegExp.
+var reSpecials = charSet('().*{}+?[]^$\\!')
 
+// "abc" -> { a:true, b:true, c:true }
+function charSet (s) {
+  return s.split('').reduce(function (set, c) {
+    set[c] = true
+    return set
+  }, {})
+}
 
-/***/ }),
+// normalizes slashes.
+var slashSplit = /\/+/
 
-/***/ 95947:
-/***/ (function(module, exports) {
+minimatch.filter = filter
+function filter (pattern, options) {
+  options = options || {}
+  return function (p, i, list) {
+    return minimatch(p, pattern, options)
+  }
+}
 
-(function(){
+function ext (a, b) {
+  b = b || {}
+  var t = {}
+  Object.keys(a).forEach(function (k) {
+    t[k] = a[k]
+  })
+  Object.keys(b).forEach(function (k) {
+    t[k] = b[k]
+  })
+  return t
+}
 
-    // Copyright (c) 2005  Tom Wu
-    // All Rights Reserved.
-    // See "LICENSE" for details.
+minimatch.defaults = function (def) {
+  if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+    return minimatch
+  }
 
-    // Basic JavaScript BN library - subset useful for RSA encryption.
+  var orig = minimatch
 
-    // Bits per digit
-    var dbits;
+  var m = function minimatch (p, pattern, options) {
+    return orig(p, pattern, ext(def, options))
+  }
 
-    // JavaScript engine analysis
-    var canary = 0xdeadbeefcafe;
-    var j_lm = ((canary&0xffffff)==0xefcafe);
+  m.Minimatch = function Minimatch (pattern, options) {
+    return new orig.Minimatch(pattern, ext(def, options))
+  }
+  m.Minimatch.defaults = function defaults (options) {
+    return orig.defaults(ext(def, options)).Minimatch
+  }
 
-    // (public) Constructor
-    function BigInteger(a,b,c) {
-      if(a != null)
-        if("number" == typeof a) this.fromNumber(a,b,c);
-        else if(b == null && "string" != typeof a) this.fromString(a,256);
-        else this.fromString(a,b);
-    }
+  m.filter = function filter (pattern, options) {
+    return orig.filter(pattern, ext(def, options))
+  }
 
-    // return new, unset BigInteger
-    function nbi() { return new BigInteger(null); }
+  m.defaults = function defaults (options) {
+    return orig.defaults(ext(def, options))
+  }
 
-    // am: Compute w_j += (x*this_i), propagate carries,
-    // c is initial carry, returns final carry.
-    // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
-    // We need to select the fastest one that works in this environment.
+  m.makeRe = function makeRe (pattern, options) {
+    return orig.makeRe(pattern, ext(def, options))
+  }
 
-    // am1: use a single mult and divide to get the high bits,
-    // max digit bits should be 26 because
-    // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
-    function am1(i,x,w,j,c,n) {
-      while(--n >= 0) {
-        var v = x*this[i++]+w[j]+c;
-        c = Math.floor(v/0x4000000);
-        w[j++] = v&0x3ffffff;
-      }
-      return c;
-    }
-    // am2 avoids a big mult-and-extract completely.
-    // Max digit bits should be <= 30 because we do bitwise ops
-    // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
-    function am2(i,x,w,j,c,n) {
-      var xl = x&0x7fff, xh = x>>15;
-      while(--n >= 0) {
-        var l = this[i]&0x7fff;
-        var h = this[i++]>>15;
-        var m = xh*l+h*xl;
-        l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
-        c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
-        w[j++] = l&0x3fffffff;
-      }
-      return c;
-    }
-    // Alternately, set max digit bits to 28 since some
-    // browsers slow down when dealing with 32-bit numbers.
-    function am3(i,x,w,j,c,n) {
-      var xl = x&0x3fff, xh = x>>14;
-      while(--n >= 0) {
-        var l = this[i]&0x3fff;
-        var h = this[i++]>>14;
-        var m = xh*l+h*xl;
-        l = xl*l+((m&0x3fff)<<14)+w[j]+c;
-        c = (l>>28)+(m>>14)+xh*h;
-        w[j++] = l&0xfffffff;
-      }
-      return c;
-    }
-    var inBrowser = typeof navigator !== "undefined";
-    if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
-      BigInteger.prototype.am = am2;
-      dbits = 30;
-    }
-    else if(inBrowser && j_lm && (navigator.appName != "Netscape")) {
-      BigInteger.prototype.am = am1;
-      dbits = 26;
-    }
-    else { // Mozilla/Netscape seems to prefer am3
-      BigInteger.prototype.am = am3;
-      dbits = 28;
-    }
+  m.braceExpand = function braceExpand (pattern, options) {
+    return orig.braceExpand(pattern, ext(def, options))
+  }
+
+  m.match = function (list, pattern, options) {
+    return orig.match(list, pattern, ext(def, options))
+  }
+
+  return m
+}
 
-    BigInteger.prototype.DB = dbits;
-    BigInteger.prototype.DM = ((1<= 0; --i) r[i] = this[i];
-      r.t = this.t;
-      r.s = this.s;
-    }
+  return new Minimatch(pattern, options).match(p)
+}
 
-    // (protected) set from integer value x, -DV <= x < DV
-    function bnpFromInt(x) {
-      this.t = 1;
-      this.s = (x<0)?-1:0;
-      if(x > 0) this[0] = x;
-      else if(x < -1) this[0] = x+this.DV;
-      else this.t = 0;
-    }
+function Minimatch (pattern, options) {
+  if (!(this instanceof Minimatch)) {
+    return new Minimatch(pattern, options)
+  }
 
-    // return bigint initialized to value
-    function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
+  assertValidPattern(pattern)
 
-    // (protected) set from string and radix
-    function bnpFromString(s,b) {
-      var k;
-      if(b == 16) k = 4;
-      else if(b == 8) k = 3;
-      else if(b == 256) k = 8; // byte array
-      else if(b == 2) k = 1;
-      else if(b == 32) k = 5;
-      else if(b == 4) k = 2;
-      else { this.fromRadix(s,b); return; }
-      this.t = 0;
-      this.s = 0;
-      var i = s.length, mi = false, sh = 0;
-      while(--i >= 0) {
-        var x = (k==8)?s[i]&0xff:intAt(s,i);
-        if(x < 0) {
-          if(s.charAt(i) == "-") mi = true;
-          continue;
-        }
-        mi = false;
-        if(sh == 0)
-          this[this.t++] = x;
-        else if(sh+k > this.DB) {
-          this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh));
-        }
-        else
-          this[this.t-1] |= x<= this.DB) sh -= this.DB;
-      }
-      if(k == 8 && (s[0]&0x80) != 0) {
-        this.s = -1;
-        if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this[this.t-1] == c) --this.t;
-    }
+  pattern = pattern.trim()
 
-    // (public) return string representation in given radix
-    function bnToString(b) {
-      if(this.s < 0) return "-"+this.negate().toString(b);
-      var k;
-      if(b == 16) k = 4;
-      else if(b == 8) k = 3;
-      else if(b == 2) k = 1;
-      else if(b == 32) k = 5;
-      else if(b == 4) k = 2;
-      else return this.toRadix(b);
-      var km = (1< 0) {
-        if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
-        while(i >= 0) {
-          if(p < k) {
-            d = (this[i]&((1<>(p+=this.DB-k);
-          }
-          else {
-            d = (this[i]>>(p-=k))&km;
-            if(p <= 0) { p += this.DB; --i; }
-          }
-          if(d > 0) m = true;
-          if(m) r += int2char(d);
-        }
-      }
-      return m?r:"0";
-    }
+  // windows support: need to use /, not \
+  if (!options.allowWindowsEscape && path.sep !== '/') {
+    pattern = pattern.split(path.sep).join('/')
+  }
 
-    // (public) -this
-    function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
+  this.options = options
+  this.set = []
+  this.pattern = pattern
+  this.regexp = null
+  this.negate = false
+  this.comment = false
+  this.empty = false
+  this.partial = !!options.partial
 
-    // (public) |this|
-    function bnAbs() { return (this.s<0)?this.negate():this; }
+  // make the set of regexps etc.
+  this.make()
+}
 
-    // (public) return + if this > a, - if this < a, 0 if equal
-    function bnCompareTo(a) {
-      var r = this.s-a.s;
-      if(r != 0) return r;
-      var i = this.t;
-      r = i-a.t;
-      if(r != 0) return (this.s<0)?-r:r;
-      while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
-      return 0;
-    }
+Minimatch.prototype.debug = function () {}
 
-    // returns bit length of the integer x
-    function nbits(x) {
-      var r = 1, t;
-      if((t=x>>>16) != 0) { x = t; r += 16; }
-      if((t=x>>8) != 0) { x = t; r += 8; }
-      if((t=x>>4) != 0) { x = t; r += 4; }
-      if((t=x>>2) != 0) { x = t; r += 2; }
-      if((t=x>>1) != 0) { x = t; r += 1; }
-      return r;
-    }
+Minimatch.prototype.make = make
+function make () {
+  var pattern = this.pattern
+  var options = this.options
 
-    // (public) return the number of bits in "this"
-    function bnBitLength() {
-      if(this.t <= 0) return 0;
-      return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
-    }
+  // empty patterns and comments match nothing.
+  if (!options.nocomment && pattern.charAt(0) === '#') {
+    this.comment = true
+    return
+  }
+  if (!pattern) {
+    this.empty = true
+    return
+  }
 
-    // (protected) r = this << n*DB
-    function bnpDLShiftTo(n,r) {
-      var i;
-      for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
-      for(i = n-1; i >= 0; --i) r[i] = 0;
-      r.t = this.t+n;
-      r.s = this.s;
-    }
+  // step 1: figure out negation, etc.
+  this.parseNegate()
 
-    // (protected) r = this >> n*DB
-    function bnpDRShiftTo(n,r) {
-      for(var i = n; i < this.t; ++i) r[i-n] = this[i];
-      r.t = Math.max(this.t-n,0);
-      r.s = this.s;
-    }
+  // step 2: expand braces
+  var set = this.globSet = this.braceExpand()
 
-    // (protected) r = this << n
-    function bnpLShiftTo(n,r) {
-      var bs = n%this.DB;
-      var cbs = this.DB-bs;
-      var bm = (1<= 0; --i) {
-        r[i+ds+1] = (this[i]>>cbs)|c;
-        c = (this[i]&bm)<= 0; --i) r[i] = 0;
-      r[ds] = c;
-      r.t = this.t+ds+1;
-      r.s = this.s;
-      r.clamp();
-    }
+  if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
 
-    // (protected) r = this >> n
-    function bnpRShiftTo(n,r) {
-      r.s = this.s;
-      var ds = Math.floor(n/this.DB);
-      if(ds >= this.t) { r.t = 0; return; }
-      var bs = n%this.DB;
-      var cbs = this.DB-bs;
-      var bm = (1<>bs;
-      for(var i = ds+1; i < this.t; ++i) {
-        r[i-ds-1] |= (this[i]&bm)<>bs;
-      }
-      if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<>= this.DB;
-      }
-      if(a.t < this.t) {
-        c -= a.s;
-        while(i < this.t) {
-          c += this[i];
-          r[i++] = c&this.DM;
-          c >>= this.DB;
-        }
-        c += this.s;
-      }
-      else {
-        c += this.s;
-        while(i < a.t) {
-          c -= a[i];
-          r[i++] = c&this.DM;
-          c >>= this.DB;
-        }
-        c -= a.s;
-      }
-      r.s = (c<0)?-1:0;
-      if(c < -1) r[i++] = this.DV+c;
-      else if(c > 0) r[i++] = c;
-      r.t = i;
-      r.clamp();
-    }
+  // step 3: now we have a set, so turn each one into a series of path-portion
+  // matching patterns.
+  // These will be regexps, except in the case of "**", which is
+  // set to the GLOBSTAR object for globstar behavior,
+  // and will not contain any / characters
+  set = this.globParts = set.map(function (s) {
+    return s.split(slashSplit)
+  })
 
-    // (protected) r = this * a, r != this,a (HAC 14.12)
-    // "this" should be the larger one if appropriate.
-    function bnpMultiplyTo(a,r) {
-      var x = this.abs(), y = a.abs();
-      var i = x.t;
-      r.t = i+y.t;
-      while(--i >= 0) r[i] = 0;
-      for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
-      r.s = 0;
-      r.clamp();
-      if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
-    }
+  this.debug(this.pattern, set)
 
-    // (protected) r = this^2, r != this (HAC 14.16)
-    function bnpSquareTo(r) {
-      var x = this.abs();
-      var i = r.t = 2*x.t;
-      while(--i >= 0) r[i] = 0;
-      for(i = 0; i < x.t-1; ++i) {
-        var c = x.am(i,x[i],r,2*i,0,1);
-        if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
-          r[i+x.t] -= x.DV;
-          r[i+x.t+1] = 1;
-        }
-      }
-      if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
-      r.s = 0;
-      r.clamp();
-    }
+  // glob --> regexps
+  set = set.map(function (s, si, set) {
+    return s.map(this.parse, this)
+  }, this)
 
-    // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
-    // r != q, this != m.  q or r may be null.
-    function bnpDivRemTo(m,q,r) {
-      var pm = m.abs();
-      if(pm.t <= 0) return;
-      var pt = this.abs();
-      if(pt.t < pm.t) {
-        if(q != null) q.fromInt(0);
-        if(r != null) this.copyTo(r);
-        return;
-      }
-      if(r == null) r = nbi();
-      var y = nbi(), ts = this.s, ms = m.s;
-      var nsh = this.DB-nbits(pm[pm.t-1]);   // normalize modulus
-      if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
-      else { pm.copyTo(y); pt.copyTo(r); }
-      var ys = y.t;
-      var y0 = y[ys-1];
-      if(y0 == 0) return;
-      var yt = y0*(1<1)?y[ys-2]>>this.F2:0);
-      var d1 = this.FV/yt, d2 = (1<= 0) {
-        r[r.t++] = 1;
-        r.subTo(t,r);
-      }
-      BigInteger.ONE.dlShiftTo(ys,t);
-      t.subTo(y,y);  // "negative" y so we can replace sub with am later
-      while(y.t < ys) y[y.t++] = 0;
-      while(--j >= 0) {
-        // Estimate quotient digit
-        var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
-        if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) {   // Try it out
-          y.dlShiftTo(j,t);
-          r.subTo(t,r);
-          while(r[i] < --qd) r.subTo(t,r);
-        }
-      }
-      if(q != null) {
-        r.drShiftTo(ys,q);
-        if(ts != ms) BigInteger.ZERO.subTo(q,q);
-      }
-      r.t = ys;
-      r.clamp();
-      if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
-      if(ts < 0) BigInteger.ZERO.subTo(r,r);
-    }
+  this.debug(this.pattern, set)
 
-    // (public) this mod a
-    function bnMod(a) {
-      var r = nbi();
-      this.abs().divRemTo(a,null,r);
-      if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
-      return r;
-    }
+  // filter out everything that didn't compile properly.
+  set = set.filter(function (s) {
+    return s.indexOf(false) === -1
+  })
 
-    // Modular reduction using "classic" algorithm
-    function Classic(m) { this.m = m; }
-    function cConvert(x) {
-      if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
-      else return x;
-    }
-    function cRevert(x) { return x; }
-    function cReduce(x) { x.divRemTo(this.m,null,x); }
-    function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
-    function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+  this.debug(this.pattern, set)
 
-    Classic.prototype.convert = cConvert;
-    Classic.prototype.revert = cRevert;
-    Classic.prototype.reduce = cReduce;
-    Classic.prototype.mulTo = cMulTo;
-    Classic.prototype.sqrTo = cSqrTo;
+  this.set = set
+}
 
-    // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
-    // justification:
-    //         xy == 1 (mod m)
-    //         xy =  1+km
-    //   xy(2-xy) = (1+km)(1-km)
-    // x[y(2-xy)] = 1-k^2m^2
-    // x[y(2-xy)] == 1 (mod m^2)
-    // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
-    // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
-    // JS multiply "overflows" differently from C/C++, so care is needed here.
-    function bnpInvDigit() {
-      if(this.t < 1) return 0;
-      var x = this[0];
-      if((x&1) == 0) return 0;
-      var y = x&3;       // y == 1/x mod 2^2
-      y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
-      y = (y*(2-(x&0xff)*y))&0xff;   // y == 1/x mod 2^8
-      y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;    // y == 1/x mod 2^16
-      // last step - calculate inverse mod DV directly;
-      // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
-      y = (y*(2-x*y%this.DV))%this.DV;       // y == 1/x mod 2^dbits
-      // we really want the negative inverse, and -DV < y < DV
-      return (y>0)?this.DV-y:-y;
-    }
+Minimatch.prototype.parseNegate = parseNegate
+function parseNegate () {
+  var pattern = this.pattern
+  var negate = false
+  var options = this.options
+  var negateOffset = 0
 
-    // Montgomery reduction
-    function Montgomery(m) {
-      this.m = m;
-      this.mp = m.invDigit();
-      this.mpl = this.mp&0x7fff;
-      this.mph = this.mp>>15;
-      this.um = (1<<(m.DB-15))-1;
-      this.mt2 = 2*m.t;
-    }
+  if (options.nonegate) return
 
-    // xR mod m
-    function montConvert(x) {
-      var r = nbi();
-      x.abs().dlShiftTo(this.m.t,r);
-      r.divRemTo(this.m,null,r);
-      if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
-      return r;
-    }
+  for (var i = 0, l = pattern.length
+    ; i < l && pattern.charAt(i) === '!'
+    ; i++) {
+    negate = !negate
+    negateOffset++
+  }
 
-    // x/R mod m
-    function montRevert(x) {
-      var r = nbi();
-      x.copyTo(r);
-      this.reduce(r);
-      return r;
-    }
+  if (negateOffset) this.pattern = pattern.substr(negateOffset)
+  this.negate = negate
+}
 
-    // x = x/R mod m (HAC 14.32)
-    function montReduce(x) {
-      while(x.t <= this.mt2) // pad x so am has enough room later
-        x[x.t++] = 0;
-      for(var i = 0; i < this.m.t; ++i) {
-        // faster way of calculating u0 = x[i]*mp mod DV
-        var j = x[i]&0x7fff;
-        var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
-        // use am to combine the multiply-shift-add into one call
-        j = i+this.m.t;
-        x[j] += this.m.am(0,u0,x,i,0,this.m.t);
-        // propagate carry
-        while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
-      }
-      x.clamp();
-      x.drShiftTo(this.m.t,x);
-      if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+minimatch.braceExpand = function (pattern, options) {
+  return braceExpand(pattern, options)
+}
+
+Minimatch.prototype.braceExpand = braceExpand
+
+function braceExpand (pattern, options) {
+  if (!options) {
+    if (this instanceof Minimatch) {
+      options = this.options
+    } else {
+      options = {}
     }
+  }
+
+  pattern = typeof pattern === 'undefined'
+    ? this.pattern : pattern
+
+  assertValidPattern(pattern)
+
+  // Thanks to Yeting Li  for
+  // improving this regexp to avoid a ReDOS vulnerability.
+  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+    // shortcut. no need to expand.
+    return [pattern]
+  }
+
+  return expand(pattern)
+}
 
-    // r = "x^2/R mod m"; x != r
-    function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+var MAX_PATTERN_LENGTH = 1024 * 64
+var assertValidPattern = function (pattern) {
+  if (typeof pattern !== 'string') {
+    throw new TypeError('invalid pattern')
+  }
 
-    // r = "xy/R mod m"; x,y != r
-    function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
+  if (pattern.length > MAX_PATTERN_LENGTH) {
+    throw new TypeError('pattern is too long')
+  }
+}
 
-    Montgomery.prototype.convert = montConvert;
-    Montgomery.prototype.revert = montRevert;
-    Montgomery.prototype.reduce = montReduce;
-    Montgomery.prototype.mulTo = montMulTo;
-    Montgomery.prototype.sqrTo = montSqrTo;
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion.  Otherwise, any series
+// of * is equivalent to a single *.  Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+Minimatch.prototype.parse = parse
+var SUBPARSE = {}
+function parse (pattern, isSub) {
+  assertValidPattern(pattern)
 
-    // (protected) true iff this is even
-    function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
+  var options = this.options
 
-    // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
-    function bnpExp(e,z) {
-      if(e > 0xffffffff || e < 1) return BigInteger.ONE;
-      var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
-      g.copyTo(r);
-      while(--i >= 0) {
-        z.sqrTo(r,r2);
-        if((e&(1< 0) z.mulTo(r2,g,r);
-        else { var t = r; r = r2; r2 = t; }
+  // shortcuts
+  if (pattern === '**') {
+    if (!options.noglobstar)
+      return GLOBSTAR
+    else
+      pattern = '*'
+  }
+  if (pattern === '') return ''
+
+  var re = ''
+  var hasMagic = !!options.nocase
+  var escaping = false
+  // ? => one single character
+  var patternListStack = []
+  var negativeLists = []
+  var stateChar
+  var inClass = false
+  var reClassStart = -1
+  var classStart = -1
+  // . and .. never match anything that doesn't start with .,
+  // even when options.dot is set.
+  var patternStart = pattern.charAt(0) === '.' ? '' // anything
+  // not (start or / followed by . or .. followed by / or end)
+  : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
+  : '(?!\\.)'
+  var self = this
+
+  function clearStateChar () {
+    if (stateChar) {
+      // we had some state-tracking character
+      // that wasn't consumed by this pass.
+      switch (stateChar) {
+        case '*':
+          re += star
+          hasMagic = true
+        break
+        case '?':
+          re += qmark
+          hasMagic = true
+        break
+        default:
+          re += '\\' + stateChar
+        break
       }
-      return z.revert(r);
+      self.debug('clearStateChar %j %j', stateChar, re)
+      stateChar = false
     }
+  }
 
-    // (public) this^e % m, 0 <= e < 2^32
-    function bnModPowInt(e,m) {
-      var z;
-      if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
-      return this.exp(e,z);
+  for (var i = 0, len = pattern.length, c
+    ; (i < len) && (c = pattern.charAt(i))
+    ; i++) {
+    this.debug('%s\t%s %s %j', pattern, i, re, c)
+
+    // skip over any that are escaped.
+    if (escaping && reSpecials[c]) {
+      re += '\\' + c
+      escaping = false
+      continue
     }
 
-    // protected
-    BigInteger.prototype.copyTo = bnpCopyTo;
-    BigInteger.prototype.fromInt = bnpFromInt;
-    BigInteger.prototype.fromString = bnpFromString;
-    BigInteger.prototype.clamp = bnpClamp;
-    BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
-    BigInteger.prototype.drShiftTo = bnpDRShiftTo;
-    BigInteger.prototype.lShiftTo = bnpLShiftTo;
-    BigInteger.prototype.rShiftTo = bnpRShiftTo;
-    BigInteger.prototype.subTo = bnpSubTo;
-    BigInteger.prototype.multiplyTo = bnpMultiplyTo;
-    BigInteger.prototype.squareTo = bnpSquareTo;
-    BigInteger.prototype.divRemTo = bnpDivRemTo;
-    BigInteger.prototype.invDigit = bnpInvDigit;
-    BigInteger.prototype.isEven = bnpIsEven;
-    BigInteger.prototype.exp = bnpExp;
+    switch (c) {
+      /* istanbul ignore next */
+      case '/': {
+        // completely not allowed, even escaped.
+        // Should already be path-split by now.
+        return false
+      }
 
-    // public
-    BigInteger.prototype.toString = bnToString;
-    BigInteger.prototype.negate = bnNegate;
-    BigInteger.prototype.abs = bnAbs;
-    BigInteger.prototype.compareTo = bnCompareTo;
-    BigInteger.prototype.bitLength = bnBitLength;
-    BigInteger.prototype.mod = bnMod;
-    BigInteger.prototype.modPowInt = bnModPowInt;
+      case '\\':
+        clearStateChar()
+        escaping = true
+      continue
 
-    // "constants"
-    BigInteger.ZERO = nbv(0);
-    BigInteger.ONE = nbv(1);
+      // the various stateChar values
+      // for the "extglob" stuff.
+      case '?':
+      case '*':
+      case '+':
+      case '@':
+      case '!':
+        this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
 
-    // Copyright (c) 2005-2009  Tom Wu
-    // All Rights Reserved.
-    // See "LICENSE" for details.
+        // all of those are literals inside a class, except that
+        // the glob [!a] means [^a] in regexp
+        if (inClass) {
+          this.debug('  in class')
+          if (c === '!' && i === classStart + 1) c = '^'
+          re += c
+          continue
+        }
 
-    // Extended JavaScript BN functions, required for RSA private ops.
+        // if we already have a stateChar, then it means
+        // that there was something like ** or +? in there.
+        // Handle the stateChar, then proceed with this one.
+        self.debug('call clearStateChar %j', stateChar)
+        clearStateChar()
+        stateChar = c
+        // if extglob is disabled, then +(asdf|foo) isn't a thing.
+        // just clear the statechar *now*, rather than even diving into
+        // the patternList stuff.
+        if (options.noext) clearStateChar()
+      continue
 
-    // Version 1.1: new BigInteger("0", 10) returns "proper" zero
-    // Version 1.2: square() API, isProbablePrime fix
+      case '(':
+        if (inClass) {
+          re += '('
+          continue
+        }
 
-    // (public)
-    function bnClone() { var r = nbi(); this.copyTo(r); return r; }
+        if (!stateChar) {
+          re += '\\('
+          continue
+        }
 
-    // (public) return value as integer
-    function bnIntValue() {
-      if(this.s < 0) {
-        if(this.t == 1) return this[0]-this.DV;
-        else if(this.t == 0) return -1;
-      }
-      else if(this.t == 1) return this[0];
-      else if(this.t == 0) return 0;
-      // assumes 16 < DB < 32
-      return ((this[1]&((1<<(32-this.DB))-1))<>24; }
+      case ')':
+        if (inClass || !patternListStack.length) {
+          re += '\\)'
+          continue
+        }
 
-    // (public) return value as short (assumes DB>=16)
-    function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
+        clearStateChar()
+        hasMagic = true
+        var pl = patternListStack.pop()
+        // negation is (?:(?!js)[^/]*)
+        // The others are (?:)
+        re += pl.close
+        if (pl.type === '!') {
+          negativeLists.push(pl)
+        }
+        pl.reEnd = re.length
+      continue
 
-    // (protected) return x s.t. r^x < DV
-    function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
+      case '|':
+        if (inClass || !patternListStack.length || escaping) {
+          re += '\\|'
+          escaping = false
+          continue
+        }
 
-    // (public) 0 if this == 0, 1 if this > 0
-    function bnSigNum() {
-      if(this.s < 0) return -1;
-      else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
-      else return 1;
-    }
+        clearStateChar()
+        re += '|'
+      continue
 
-    // (protected) convert to radix string
-    function bnpToRadix(b) {
-      if(b == null) b = 10;
-      if(this.signum() == 0 || b < 2 || b > 36) return "0";
-      var cs = this.chunkSize(b);
-      var a = Math.pow(b,cs);
-      var d = nbv(a), y = nbi(), z = nbi(), r = "";
-      this.divRemTo(d,y,z);
-      while(y.signum() > 0) {
-        r = (a+z.intValue()).toString(b).substr(1) + r;
-        y.divRemTo(d,y,z);
-      }
-      return z.intValue().toString(b) + r;
-    }
+      // these are mostly the same in regexp and glob
+      case '[':
+        // swallow any state-tracking char before the [
+        clearStateChar()
 
-    // (protected) convert from radix string
-    function bnpFromRadix(s,b) {
-      this.fromInt(0);
-      if(b == null) b = 10;
-      var cs = this.chunkSize(b);
-      var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
-      for(var i = 0; i < s.length; ++i) {
-        var x = intAt(s,i);
-        if(x < 0) {
-          if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
-          continue;
+        if (inClass) {
+          re += '\\' + c
+          continue
         }
-        w = b*w+x;
-        if(++j >= cs) {
-          this.dMultiply(d);
-          this.dAddOffset(w,0);
-          j = 0;
-          w = 0;
+
+        inClass = true
+        classStart = i
+        reClassStart = re.length
+        re += c
+      continue
+
+      case ']':
+        //  a right bracket shall lose its special
+        //  meaning and represent itself in
+        //  a bracket expression if it occurs
+        //  first in the list.  -- POSIX.2 2.8.3.2
+        if (i === classStart + 1 || !inClass) {
+          re += '\\' + c
+          escaping = false
+          continue
         }
-      }
-      if(j > 0) {
-        this.dMultiply(Math.pow(b,j));
-        this.dAddOffset(w,0);
-      }
-      if(mi) BigInteger.ZERO.subTo(this,this);
-    }
 
-    // (protected) alternate constructor
-    function bnpFromNumber(a,b,c) {
-      if("number" == typeof b) {
-        // new BigInteger(int,int,RNG)
-        if(a < 2) this.fromInt(1);
-        else {
-          this.fromNumber(a,c);
-          if(!this.testBit(a-1))    // force MSB set
-            this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
-          if(this.isEven()) this.dAddOffset(1,0); // force odd
-          while(!this.isProbablePrime(b)) {
-            this.dAddOffset(2,0);
-            if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
-          }
+        // handle the case where we left a class open.
+        // "[z-a]" is valid, equivalent to "\[z-a\]"
+        // split where the last [ was, make sure we don't have
+        // an invalid re. if so, re-walk the contents of the
+        // would-be class to re-translate any characters that
+        // were passed through as-is
+        // TODO: It would probably be faster to determine this
+        // without a try/catch and a new RegExp, but it's tricky
+        // to do safely.  For now, this is safe and works.
+        var cs = pattern.substring(classStart + 1, i)
+        try {
+          RegExp('[' + cs + ']')
+        } catch (er) {
+          // not a valid class!
+          var sp = this.parse(cs, SUBPARSE)
+          re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
+          hasMagic = hasMagic || sp[1]
+          inClass = false
+          continue
         }
-      }
-      else {
-        // new BigInteger(int,RNG)
-        var x = new Array(), t = a&7;
-        x.length = (a>>3)+1;
-        b.nextBytes(x);
-        if(t > 0) x[0] &= ((1< 0) {
-        if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
-          r[k++] = d|(this.s<<(this.DB-p));
-        while(i >= 0) {
-          if(p < 8) {
-            d = (this[i]&((1<>(p+=this.DB-8);
-          }
-          else {
-            d = (this[i]>>(p-=8))&0xff;
-            if(p <= 0) { p += this.DB; --i; }
-          }
-          if((d&0x80) != 0) d |= -256;
-          if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
-          if(k > 0 || d != this.s) r[k++] = d;
+        // finish up the class.
+        hasMagic = true
+        inClass = false
+        re += c
+      continue
+
+      default:
+        // swallow any state char that wasn't consumed
+        clearStateChar()
+
+        if (escaping) {
+          // no need
+          escaping = false
+        } else if (reSpecials[c]
+          && !(c === '^' && inClass)) {
+          re += '\\'
         }
-      }
-      return r;
-    }
 
-    function bnEquals(a) { return(this.compareTo(a)==0); }
-    function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
-    function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
+        re += c
 
-    // (protected) r = this op a (bitwise)
-    function bnpBitwiseTo(a,op,r) {
-      var i, f, m = Math.min(a.t,this.t);
-      for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
-      if(a.t < this.t) {
-        f = a.s&this.DM;
-        for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
-        r.t = this.t;
-      }
-      else {
-        f = this.s&this.DM;
-        for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
-        r.t = a.t;
-      }
-      r.s = op(this.s,a.s);
-      r.clamp();
-    }
+    } // switch
+  } // for
 
-    // (public) this & a
-    function op_and(x,y) { return x&y; }
-    function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
+  // handle the case where we left a class open.
+  // "[abc" is valid, equivalent to "\[abc"
+  if (inClass) {
+    // split where the last [ was, and escape it
+    // this is a huge pita.  We now have to re-walk
+    // the contents of the would-be class to re-translate
+    // any characters that were passed through as-is
+    cs = pattern.substr(classStart + 1)
+    sp = this.parse(cs, SUBPARSE)
+    re = re.substr(0, reClassStart) + '\\[' + sp[0]
+    hasMagic = hasMagic || sp[1]
+  }
 
-    // (public) this | a
-    function op_or(x,y) { return x|y; }
-    function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
+  // handle the case where we had a +( thing at the *end*
+  // of the pattern.
+  // each pattern list stack adds 3 chars, and we need to go through
+  // and escape any | chars that were passed through as-is for the regexp.
+  // Go through and escape them, taking care not to double-escape any
+  // | chars that were already escaped.
+  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
+    var tail = re.slice(pl.reStart + pl.open.length)
+    this.debug('setting tail', re, pl)
+    // maybe some even number of \, then maybe 1 \, followed by a |
+    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
+      if (!$2) {
+        // the | isn't already escaped, so escape it.
+        $2 = '\\'
+      }
 
-    // (public) this ^ a
-    function op_xor(x,y) { return x^y; }
-    function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
+      // need to escape all those slashes *again*, without escaping the
+      // one that we need for escaping the | character.  As it works out,
+      // escaping an even number of slashes can be done by simply repeating
+      // it exactly after itself.  That's why this trick works.
+      //
+      // I am sorry that you have to see this.
+      return $1 + $1 + $2 + '|'
+    })
 
-    // (public) this & ~a
-    function op_andnot(x,y) { return x&~y; }
-    function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
+    this.debug('tail=%j\n   %s', tail, tail, pl, re)
+    var t = pl.type === '*' ? star
+      : pl.type === '?' ? qmark
+      : '\\' + pl.type
 
-    // (public) ~this
-    function bnNot() {
-      var r = nbi();
-      for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
-      r.t = this.t;
-      r.s = ~this.s;
-      return r;
-    }
+    hasMagic = true
+    re = re.slice(0, pl.reStart) + t + '\\(' + tail
+  }
 
-    // (public) this << n
-    function bnShiftLeft(n) {
-      var r = nbi();
-      if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
-      return r;
-    }
+  // handle trailing things that only matter at the very end.
+  clearStateChar()
+  if (escaping) {
+    // trailing \\
+    re += '\\\\'
+  }
 
-    // (public) this >> n
-    function bnShiftRight(n) {
-      var r = nbi();
-      if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
-      return r;
-    }
+  // only need to apply the nodot start if the re starts with
+  // something that could conceivably capture a dot
+  var addPatternStart = false
+  switch (re.charAt(0)) {
+    case '[': case '.': case '(': addPatternStart = true
+  }
 
-    // return index of lowest 1-bit in x, x < 2^31
-    function lbit(x) {
-      if(x == 0) return -1;
-      var r = 0;
-      if((x&0xffff) == 0) { x >>= 16; r += 16; }
-      if((x&0xff) == 0) { x >>= 8; r += 8; }
-      if((x&0xf) == 0) { x >>= 4; r += 4; }
-      if((x&3) == 0) { x >>= 2; r += 2; }
-      if((x&1) == 0) ++r;
-      return r;
-    }
+  // Hack to work around lack of negative lookbehind in JS
+  // A pattern like: *.!(x).!(y|z) needs to ensure that a name
+  // like 'a.xyz.yz' doesn't match.  So, the first negative
+  // lookahead, has to look ALL the way ahead, to the end of
+  // the pattern.
+  for (var n = negativeLists.length - 1; n > -1; n--) {
+    var nl = negativeLists[n]
 
-    // (public) returns index of lowest 1-bit (or -1 if none)
-    function bnGetLowestSetBit() {
-      for(var i = 0; i < this.t; ++i)
-        if(this[i] != 0) return i*this.DB+lbit(this[i]);
-      if(this.s < 0) return this.t*this.DB;
-      return -1;
-    }
+    var nlBefore = re.slice(0, nl.reStart)
+    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
+    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
+    var nlAfter = re.slice(nl.reEnd)
 
-    // return number of 1 bits in x
-    function cbit(x) {
-      var r = 0;
-      while(x != 0) { x &= x-1; ++r; }
-      return r;
-    }
+    nlLast += nlAfter
 
-    // (public) return number of set bits
-    function bnBitCount() {
-      var r = 0, x = this.s&this.DM;
-      for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
-      return r;
+    // Handle nested stuff like *(*.js|!(*.json)), where open parens
+    // mean that we should *not* include the ) in the bit that is considered
+    // "after" the negated section.
+    var openParensBefore = nlBefore.split('(').length - 1
+    var cleanAfter = nlAfter
+    for (i = 0; i < openParensBefore; i++) {
+      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
     }
+    nlAfter = cleanAfter
 
-    // (public) true iff nth bit is set
-    function bnTestBit(n) {
-      var j = Math.floor(n/this.DB);
-      if(j >= this.t) return(this.s!=0);
-      return((this[j]&(1<<(n%this.DB)))!=0);
+    var dollar = ''
+    if (nlAfter === '' && isSub !== SUBPARSE) {
+      dollar = '$'
     }
+    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
+    re = newRe
+  }
 
-    // (protected) this op (1<>= this.DB;
-      }
-      if(a.t < this.t) {
-        c += a.s;
-        while(i < this.t) {
-          c += this[i];
-          r[i++] = c&this.DM;
-          c >>= this.DB;
-        }
-        c += this.s;
-      }
-      else {
-        c += this.s;
-        while(i < a.t) {
-          c += a[i];
-          r[i++] = c&this.DM;
-          c >>= this.DB;
-        }
-        c += a.s;
-      }
-      r.s = (c<0)?-1:0;
-      if(c > 0) r[i++] = c;
-      else if(c < -1) r[i++] = this.DV+c;
-      r.t = i;
-      r.clamp();
-    }
+  var flags = options.nocase ? 'i' : ''
+  try {
+    var regExp = new RegExp('^' + re + '$', flags)
+  } catch (er) /* istanbul ignore next - should be impossible */ {
+    // If it was an invalid regular expression, then it can't match
+    // anything.  This trick looks for a character after the end of
+    // the string, which is of course impossible, except in multi-line
+    // mode, but it's not a /m regex.
+    return new RegExp('$.')
+  }
 
-    // (public) this + a
-    function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
+  regExp._glob = pattern
+  regExp._src = re
 
-    // (public) this - a
-    function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
+  return regExp
+}
 
-    // (public) this * a
-    function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
+minimatch.makeRe = function (pattern, options) {
+  return new Minimatch(pattern, options || {}).makeRe()
+}
 
-    // (public) this^2
-    function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
+Minimatch.prototype.makeRe = makeRe
+function makeRe () {
+  if (this.regexp || this.regexp === false) return this.regexp
 
-    // (public) this / a
-    function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
+  // at this point, this.set is a 2d array of partial
+  // pattern strings, or "**".
+  //
+  // It's better to use .match().  This function shouldn't
+  // be used, really, but it's pretty convenient sometimes,
+  // when you just want to work with a regex.
+  var set = this.set
 
-    // (public) this % a
-    function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
+  if (!set.length) {
+    this.regexp = false
+    return this.regexp
+  }
+  var options = this.options
 
-    // (public) [this/a,this%a]
-    function bnDivideAndRemainder(a) {
-      var q = nbi(), r = nbi();
-      this.divRemTo(a,q,r);
-      return new Array(q,r);
-    }
+  var twoStar = options.noglobstar ? star
+    : options.dot ? twoStarDot
+    : twoStarNoDot
+  var flags = options.nocase ? 'i' : ''
 
-    // (protected) this *= n, this >= 0, 1 < n < DV
-    function bnpDMultiply(n) {
-      this[this.t] = this.am(0,n-1,this,0,0,this.t);
-      ++this.t;
-      this.clamp();
-    }
+  var re = set.map(function (pattern) {
+    return pattern.map(function (p) {
+      return (p === GLOBSTAR) ? twoStar
+      : (typeof p === 'string') ? regExpEscape(p)
+      : p._src
+    }).join('\\\/')
+  }).join('|')
 
-    // (protected) this += n << w words, this >= 0
-    function bnpDAddOffset(n,w) {
-      if(n == 0) return;
-      while(this.t <= w) this[this.t++] = 0;
-      this[w] += n;
-      while(this[w] >= this.DV) {
-        this[w] -= this.DV;
-        if(++w >= this.t) this[this.t++] = 0;
-        ++this[w];
-      }
-    }
+  // must match entire pattern
+  // ending in a * or ** will make it less strict.
+  re = '^(?:' + re + ')$'
 
-    // A "null" reducer
-    function NullExp() {}
-    function nNop(x) { return x; }
-    function nMulTo(x,y,r) { x.multiplyTo(y,r); }
-    function nSqrTo(x,r) { x.squareTo(r); }
+  // can match anything, as long as it's not this.
+  if (this.negate) re = '^(?!' + re + ').*$'
 
-    NullExp.prototype.convert = nNop;
-    NullExp.prototype.revert = nNop;
-    NullExp.prototype.mulTo = nMulTo;
-    NullExp.prototype.sqrTo = nSqrTo;
+  try {
+    this.regexp = new RegExp(re, flags)
+  } catch (ex) /* istanbul ignore next - should be impossible */ {
+    this.regexp = false
+  }
+  return this.regexp
+}
 
-    // (public) this^e
-    function bnPow(e) { return this.exp(e,new NullExp()); }
+minimatch.match = function (list, pattern, options) {
+  options = options || {}
+  var mm = new Minimatch(pattern, options)
+  list = list.filter(function (f) {
+    return mm.match(f)
+  })
+  if (mm.options.nonull && !list.length) {
+    list.push(pattern)
+  }
+  return list
+}
 
-    // (protected) r = lower n words of "this * a", a.t <= n
-    // "this" should be the larger one if appropriate.
-    function bnpMultiplyLowerTo(a,n,r) {
-      var i = Math.min(this.t+a.t,n);
-      r.s = 0; // assumes a,this >= 0
-      r.t = i;
-      while(i > 0) r[--i] = 0;
-      var j;
-      for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
-      for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
-      r.clamp();
-    }
+Minimatch.prototype.match = function match (f, partial) {
+  if (typeof partial === 'undefined') partial = this.partial
+  this.debug('match', f, this.pattern)
+  // short-circuit in the case of busted things.
+  // comments, etc.
+  if (this.comment) return false
+  if (this.empty) return f === ''
 
-    // (protected) r = "this * a" without lower n words, n > 0
-    // "this" should be the larger one if appropriate.
-    function bnpMultiplyUpperTo(a,n,r) {
-      --n;
-      var i = r.t = this.t+a.t-n;
-      r.s = 0; // assumes a,this >= 0
-      while(--i >= 0) r[i] = 0;
-      for(i = Math.max(n-this.t,0); i < a.t; ++i)
-        r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
-      r.clamp();
-      r.drShiftTo(1,r);
-    }
+  if (f === '/' && partial) return true
 
-    // Barrett modular reduction
-    function Barrett(m) {
-      // setup Barrett
-      this.r2 = nbi();
-      this.q3 = nbi();
-      BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
-      this.mu = this.r2.divide(m);
-      this.m = m;
-    }
+  var options = this.options
 
-    function barrettConvert(x) {
-      if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
-      else if(x.compareTo(this.m) < 0) return x;
-      else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
-    }
+  // windows: need to use /, not \
+  if (path.sep !== '/') {
+    f = f.split(path.sep).join('/')
+  }
 
-    function barrettRevert(x) { return x; }
+  // treat the test path as a set of pathparts.
+  f = f.split(slashSplit)
+  this.debug(this.pattern, 'split', f)
 
-    // x = x mod m (HAC 14.42)
-    function barrettReduce(x) {
-      x.drShiftTo(this.m.t-1,this.r2);
-      if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
-      this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
-      this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
-      while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
-      x.subTo(this.r2,x);
-      while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
-    }
+  // just ONE of the pattern sets in this.set needs to match
+  // in order for it to be valid.  If negating, then just one
+  // match means that we have failed.
+  // Either way, return on the first hit.
 
-    // r = x^2 mod m; x != r
-    function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
+  var set = this.set
+  this.debug(this.pattern, 'set', set)
 
-    // r = x*y mod m; x,y != r
-    function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
+  // Find the basename of the path by looking for the last non-empty segment
+  var filename
+  var i
+  for (i = f.length - 1; i >= 0; i--) {
+    filename = f[i]
+    if (filename) break
+  }
 
-    Barrett.prototype.convert = barrettConvert;
-    Barrett.prototype.revert = barrettRevert;
-    Barrett.prototype.reduce = barrettReduce;
-    Barrett.prototype.mulTo = barrettMulTo;
-    Barrett.prototype.sqrTo = barrettSqrTo;
+  for (i = 0; i < set.length; i++) {
+    var pattern = set[i]
+    var file = f
+    if (options.matchBase && pattern.length === 1) {
+      file = [filename]
+    }
+    var hit = this.matchOne(file, pattern, partial)
+    if (hit) {
+      if (options.flipNegate) return true
+      return !this.negate
+    }
+  }
 
-    // (public) this^e % m (HAC 14.85)
-    function bnModPow(e,m) {
-      var i = e.bitLength(), k, r = nbv(1), z;
-      if(i <= 0) return r;
-      else if(i < 18) k = 1;
-      else if(i < 48) k = 3;
-      else if(i < 144) k = 4;
-      else if(i < 768) k = 5;
-      else k = 6;
-      if(i < 8)
-        z = new Classic(m);
-      else if(m.isEven())
-        z = new Barrett(m);
-      else
-        z = new Montgomery(m);
+  // didn't get any hits.  this is success if it's a negative
+  // pattern, failure otherwise.
+  if (options.flipNegate) return false
+  return this.negate
+}
 
-      // precomputation
-      var g = new Array(), n = 3, k1 = k-1, km = (1< 1) {
-        var g2 = nbi();
-        z.sqrTo(g[1],g2);
-        while(n <= km) {
-          g[n] = nbi();
-          z.mulTo(g2,g[n-2],g[n]);
-          n += 2;
-        }
-      }
+// set partial to true to test if, for example,
+// "/a/b" matches the start of "/*/b/*/d"
+// Partial means, if you run out of file before you run
+// out of pattern, then that's fine, as long as all
+// the parts match.
+Minimatch.prototype.matchOne = function (file, pattern, partial) {
+  var options = this.options
 
-      var j = e.t-1, w, is1 = true, r2 = nbi(), t;
-      i = nbits(e[j])-1;
-      while(j >= 0) {
-        if(i >= k1) w = (e[j]>>(i-k1))&km;
-        else {
-          w = (e[j]&((1<<(i+1))-1))<<(k1-i);
-          if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
-        }
+  this.debug('matchOne',
+    { 'this': this, file: file, pattern: pattern })
 
-        n = k;
-        while((w&1) == 0) { w >>= 1; --n; }
-        if((i -= n) < 0) { i += this.DB; --j; }
-        if(is1) {    // ret == 1, don't bother squaring or multiplying it
-          g[w].copyTo(r);
-          is1 = false;
-        }
-        else {
-          while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
-          if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
-          z.mulTo(r2,g[w],r);
-        }
+  this.debug('matchOne', file.length, pattern.length)
 
-        while(j >= 0 && (e[j]&(1< 0) {
-        x.rShiftTo(g,x);
-        y.rShiftTo(g,y);
-      }
-      while(x.signum() > 0) {
-        if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
-        if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
-        if(x.compareTo(y) >= 0) {
-          x.subTo(y,x);
-          x.rShiftTo(1,x);
-        }
-        else {
-          y.subTo(x,y);
-          y.rShiftTo(1,y);
-        }
-      }
-      if(g > 0) y.lShiftTo(g,y);
-      return y;
-    }
+    this.debug(pattern, p, f)
 
-    // (protected) this % n, n < 2^26
-    function bnpModInt(n) {
-      if(n <= 0) return 0;
-      var d = this.DV%n, r = (this.s<0)?n-1:0;
-      if(this.t > 0)
-        if(d == 0) r = this[0]%n;
-        else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
-      return r;
-    }
+    // should be impossible.
+    // some invalid regexp stuff in the set.
+    /* istanbul ignore if */
+    if (p === false) return false
 
-    // (public) 1/this % m (HAC 14.61)
-    function bnModInverse(m) {
-      var ac = m.isEven();
-      if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
-      var u = m.clone(), v = this.clone();
-      var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
-      while(u.signum() != 0) {
-        while(u.isEven()) {
-          u.rShiftTo(1,u);
-          if(ac) {
-            if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
-            a.rShiftTo(1,a);
-          }
-          else if(!b.isEven()) b.subTo(m,b);
-          b.rShiftTo(1,b);
-        }
-        while(v.isEven()) {
-          v.rShiftTo(1,v);
-          if(ac) {
-            if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
-            c.rShiftTo(1,c);
-          }
-          else if(!d.isEven()) d.subTo(m,d);
-          d.rShiftTo(1,d);
-        }
-        if(u.compareTo(v) >= 0) {
-          u.subTo(v,u);
-          if(ac) a.subTo(c,a);
-          b.subTo(d,b);
-        }
-        else {
-          v.subTo(u,v);
-          if(ac) c.subTo(a,c);
-          d.subTo(b,d);
+    if (p === GLOBSTAR) {
+      this.debug('GLOBSTAR', [pattern, p, f])
+
+      // "**"
+      // a/**/b/**/c would match the following:
+      // a/b/x/y/z/c
+      // a/x/y/z/b/c
+      // a/b/x/b/x/c
+      // a/b/c
+      // To do this, take the rest of the pattern after
+      // the **, and see if it would match the file remainder.
+      // If so, return success.
+      // If not, the ** "swallows" a segment, and try again.
+      // This is recursively awful.
+      //
+      // a/**/b/**/c matching a/b/x/y/z/c
+      // - a matches a
+      // - doublestar
+      //   - matchOne(b/x/y/z/c, b/**/c)
+      //     - b matches b
+      //     - doublestar
+      //       - matchOne(x/y/z/c, c) -> no
+      //       - matchOne(y/z/c, c) -> no
+      //       - matchOne(z/c, c) -> no
+      //       - matchOne(c, c) yes, hit
+      var fr = fi
+      var pr = pi + 1
+      if (pr === pl) {
+        this.debug('** at the end')
+        // a ** at the end will just swallow the rest.
+        // We have found a match.
+        // however, it will not swallow /.x, unless
+        // options.dot is set.
+        // . and .. are *never* matched by **, for explosively
+        // exponential reasons.
+        for (; fi < fl; fi++) {
+          if (file[fi] === '.' || file[fi] === '..' ||
+            (!options.dot && file[fi].charAt(0) === '.')) return false
         }
+        return true
       }
-      if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
-      if(d.compareTo(m) >= 0) return d.subtract(m);
-      if(d.signum() < 0) d.addTo(m,d); else return d;
-      if(d.signum() < 0) return d.add(m); else return d;
-    }
 
-    var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
-    var lplim = (1<<26)/lowprimes[lowprimes.length-1];
+      // ok, let's see if we can swallow whatever we can.
+      while (fr < fl) {
+        var swallowee = file[fr]
 
-    // (public) test primality with certainty >= 1-.5^t
-    function bnIsProbablePrime(t) {
-      var i, x = this.abs();
-      if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
-        for(i = 0; i < lowprimes.length; ++i)
-          if(x[0] == lowprimes[i]) return true;
-        return false;
-      }
-      if(x.isEven()) return false;
-      i = 1;
-      while(i < lowprimes.length) {
-        var m = lowprimes[i], j = i+1;
-        while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
-        m = x.modInt(m);
-        while(i < j) if(m%lowprimes[i++] == 0) return false;
-      }
-      return x.millerRabin(t);
-    }
+        this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
 
-    // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
-    function bnpMillerRabin(t) {
-      var n1 = this.subtract(BigInteger.ONE);
-      var k = n1.getLowestSetBit();
-      if(k <= 0) return false;
-      var r = n1.shiftRight(k);
-      t = (t+1)>>1;
-      if(t > lowprimes.length) t = lowprimes.length;
-      var a = nbi();
-      for(var i = 0; i < t; ++i) {
-        //Pick bases at random, instead of starting at 2
-        a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
-        var y = a.modPow(r,this);
-        if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
-          var j = 1;
-          while(j++ < k && y.compareTo(n1) != 0) {
-            y = y.modPowInt(2,this);
-            if(y.compareTo(BigInteger.ONE) == 0) return false;
+        // XXX remove this slice.  Just pass the start index.
+        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+          this.debug('globstar found match!', fr, fl, swallowee)
+          // found a match.
+          return true
+        } else {
+          // can't swallow "." or ".." ever.
+          // can only swallow ".foo" when explicitly asked.
+          if (swallowee === '.' || swallowee === '..' ||
+            (!options.dot && swallowee.charAt(0) === '.')) {
+            this.debug('dot detected!', file, fr, pattern, pr)
+            break
           }
-          if(y.compareTo(n1) != 0) return false;
+
+          // ** swallows a segment, and continue.
+          this.debug('globstar swallow a segment, and continue')
+          fr++
         }
       }
-      return true;
+
+      // no match was found.
+      // However, in partial mode, we can't say this is necessarily over.
+      // If there's more *pattern* left, then
+      /* istanbul ignore if */
+      if (partial) {
+        // ran out of file
+        this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
+        if (fr === fl) return true
+      }
+      return false
     }
 
-    // protected
-    BigInteger.prototype.chunkSize = bnpChunkSize;
-    BigInteger.prototype.toRadix = bnpToRadix;
-    BigInteger.prototype.fromRadix = bnpFromRadix;
-    BigInteger.prototype.fromNumber = bnpFromNumber;
-    BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
-    BigInteger.prototype.changeBit = bnpChangeBit;
-    BigInteger.prototype.addTo = bnpAddTo;
-    BigInteger.prototype.dMultiply = bnpDMultiply;
-    BigInteger.prototype.dAddOffset = bnpDAddOffset;
-    BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
-    BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
-    BigInteger.prototype.modInt = bnpModInt;
-    BigInteger.prototype.millerRabin = bnpMillerRabin;
+    // something other than **
+    // non-magic patterns just have to match exactly
+    // patterns with magic have been turned into regexps.
+    var hit
+    if (typeof p === 'string') {
+      hit = f === p
+      this.debug('string match', p, f, hit)
+    } else {
+      hit = f.match(p)
+      this.debug('pattern match', p, f, hit)
+    }
 
-    // public
-    BigInteger.prototype.clone = bnClone;
-    BigInteger.prototype.intValue = bnIntValue;
-    BigInteger.prototype.byteValue = bnByteValue;
-    BigInteger.prototype.shortValue = bnShortValue;
-    BigInteger.prototype.signum = bnSigNum;
-    BigInteger.prototype.toByteArray = bnToByteArray;
-    BigInteger.prototype.equals = bnEquals;
-    BigInteger.prototype.min = bnMin;
-    BigInteger.prototype.max = bnMax;
-    BigInteger.prototype.and = bnAnd;
-    BigInteger.prototype.or = bnOr;
-    BigInteger.prototype.xor = bnXor;
-    BigInteger.prototype.andNot = bnAndNot;
-    BigInteger.prototype.not = bnNot;
-    BigInteger.prototype.shiftLeft = bnShiftLeft;
-    BigInteger.prototype.shiftRight = bnShiftRight;
-    BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
-    BigInteger.prototype.bitCount = bnBitCount;
-    BigInteger.prototype.testBit = bnTestBit;
-    BigInteger.prototype.setBit = bnSetBit;
-    BigInteger.prototype.clearBit = bnClearBit;
-    BigInteger.prototype.flipBit = bnFlipBit;
-    BigInteger.prototype.add = bnAdd;
-    BigInteger.prototype.subtract = bnSubtract;
-    BigInteger.prototype.multiply = bnMultiply;
-    BigInteger.prototype.divide = bnDivide;
-    BigInteger.prototype.remainder = bnRemainder;
-    BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
-    BigInteger.prototype.modPow = bnModPow;
-    BigInteger.prototype.modInverse = bnModInverse;
-    BigInteger.prototype.pow = bnPow;
-    BigInteger.prototype.gcd = bnGCD;
-    BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
+    if (!hit) return false
+  }
 
-    // JSBN-specific extension
-    BigInteger.prototype.square = bnSquare;
+  // Note: ending in / means that we'll get a final ""
+  // at the end of the pattern.  This can only match a
+  // corresponding "" at the end of the file.
+  // If the file ends in /, then it can only match a
+  // a pattern that ends in /, unless the pattern just
+  // doesn't have any more for it. But, a/b/ should *not*
+  // match "a/b/*", even though "" matches against the
+  // [^/]*? pattern, except in partial mode, where it might
+  // simply not be reached yet.
+  // However, a/b/ should still satisfy a/*
 
-    // Expose the Barrett function
-    BigInteger.prototype.Barrett = Barrett
+  // now either we fell off the end of the pattern, or we're done.
+  if (fi === fl && pi === pl) {
+    // ran out of pattern and filename at the same time.
+    // an exact hit!
+    return true
+  } else if (fi === fl) {
+    // ran out of file, but still had pattern left.
+    // this is ok if we're doing the match as part of
+    // a glob fs traversal.
+    return partial
+  } else /* istanbul ignore else */ if (pi === pl) {
+    // ran out of pattern, still have file left.
+    // this is only acceptable if we're on the very last
+    // empty segment of a file with a trailing slash.
+    // a/* should match a/b/
+    return (fi === fl - 1) && (file[fi] === '')
+  }
 
-    // BigInteger interfaces not implemented in jsbn:
+  // should be unreachable.
+  /* istanbul ignore next */
+  throw new Error('wtf?')
+}
 
-    // BigInteger(int signum, byte[] magnitude)
-    // double doubleValue()
-    // float floatValue()
-    // int hashCode()
-    // long longValue()
-    // static BigInteger valueOf(long val)
+// replace stuff like \* with *
+function globUnescape (s) {
+  return s.replace(/\\(.)/g, '$1')
+}
 
-    // Random number generator - requires a PRNG backend, e.g. prng4.js
+function regExpEscape (s) {
+  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+}
 
-    // For best results, put code like
-    // 
-    // in your main HTML document.
 
-    var rng_state;
-    var rng_pool;
-    var rng_pptr;
+/***/ }),
 
-    // Mix in a 32-bit integer into the pool
-    function rng_seed_int(x) {
-      rng_pool[rng_pptr++] ^= x & 255;
-      rng_pool[rng_pptr++] ^= (x >> 8) & 255;
-      rng_pool[rng_pptr++] ^= (x >> 16) & 255;
-      rng_pool[rng_pptr++] ^= (x >> 24) & 255;
-      if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
-    }
+/***/ 11757:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    // Mix in the current time (w/milliseconds) into the pool
-    function rng_seed_time() {
-      rng_seed_int(new Date().getTime());
-    }
+const { Minipass } = __nccwpck_require__(78275)
+const _data = Symbol('_data')
+const _length = Symbol('_length')
+class Collect extends Minipass {
+  constructor (options) {
+    super(options)
+    this[_data] = []
+    this[_length] = 0
+  }
+  write (chunk, encoding, cb) {
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
 
-    // Initialize the pool with junk if needed.
-    if(rng_pool == null) {
-      rng_pool = new Array();
-      rng_pptr = 0;
-      var t;
-      if(typeof window !== "undefined" && window.crypto) {
-        if (window.crypto.getRandomValues) {
-          // Use webcrypto if available
-          var ua = new Uint8Array(32);
-          window.crypto.getRandomValues(ua);
-          for(t = 0; t < 32; ++t)
-            rng_pool[rng_pptr++] = ua[t];
-        }
-        else if(navigator.appName == "Netscape" && navigator.appVersion < "5") {
-          // Extract entropy (256 bits) from NS4 RNG if available
-          var z = window.crypto.random(32);
-          for(t = 0; t < z.length; ++t)
-            rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
-        }
-      }
-      while(rng_pptr < rng_psize) {  // extract some randomness from Math.random()
-        t = Math.floor(65536 * Math.random());
-        rng_pool[rng_pptr++] = t >>> 8;
-        rng_pool[rng_pptr++] = t & 255;
-      }
-      rng_pptr = 0;
-      rng_seed_time();
-      //rng_seed_int(window.screenX);
-      //rng_seed_int(window.screenY);
-    }
+    if (!encoding)
+      encoding = 'utf8'
 
-    function rng_get_byte() {
-      if(rng_state == null) {
-        rng_seed_time();
-        rng_state = prng_newstate();
-        rng_state.init(rng_pool);
-        for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
-          rng_pool[rng_pptr] = 0;
-        rng_pptr = 0;
-        //rng_pool = null;
-      }
-      // TODO: allow reseeding after first request
-      return rng_state.next();
-    }
+    const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
+    this[_data].push(c)
+    this[_length] += c.length
+    if (cb)
+      cb()
+    return true
+  }
+  end (chunk, encoding, cb) {
+    if (typeof chunk === 'function')
+      cb = chunk, chunk = null
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
+    if (chunk)
+      this.write(chunk, encoding)
+    const result = Buffer.concat(this[_data], this[_length])
+    super.write(result)
+    return super.end(cb)
+  }
+}
+module.exports = Collect
 
-    function rng_get_bytes(ba) {
-      var i;
-      for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
-    }
+// it would be possible to DRY this a bit by doing something like
+// this.collector = new Collect() and listening on its data event,
+// but it's not much code, and we may as well save the extra obj
+class CollectPassThrough extends Minipass {
+  constructor (options) {
+    super(options)
+    this[_data] = []
+    this[_length] = 0
+  }
+  write (chunk, encoding, cb) {
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
 
-    function SecureRandom() {}
+    if (!encoding)
+      encoding = 'utf8'
 
-    SecureRandom.prototype.nextBytes = rng_get_bytes;
+    const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
+    this[_data].push(c)
+    this[_length] += c.length
+    return super.write(chunk, encoding, cb)
+  }
+  end (chunk, encoding, cb) {
+    if (typeof chunk === 'function')
+      cb = chunk, chunk = null
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
+    if (chunk)
+      this.write(chunk, encoding)
+    const result = Buffer.concat(this[_data], this[_length])
+    this.emit('collect', result)
+    return super.end(cb)
+  }
+}
+module.exports.PassThrough = CollectPassThrough
 
-    // prng4.js - uses Arcfour as a PRNG
 
-    function Arcfour() {
-      this.i = 0;
-      this.j = 0;
-      this.S = new Array();
-    }
+/***/ }),
 
-    // Initialize arcfour context from key, an array of ints, each from [0..255]
-    function ARC4init(key) {
-      var i, j, t;
-      for(i = 0; i < 256; ++i)
-        this.S[i] = i;
-      j = 0;
-      for(i = 0; i < 256; ++i) {
-        j = (j + this.S[i] + key[i % key.length]) & 255;
-        t = this.S[i];
-        this.S[i] = this.S[j];
-        this.S[j] = t;
+/***/ 57442:
+/***/ ((module) => {
+
+"use strict";
+
+class AbortError extends Error {
+  constructor (message) {
+    super(message)
+    this.code = 'FETCH_ABORTED'
+    this.type = 'aborted'
+    Error.captureStackTrace(this, this.constructor)
+  }
+
+  get name () {
+    return 'AbortError'
+  }
+
+  // don't allow name to be overridden, but don't throw either
+  set name (s) {}
+}
+module.exports = AbortError
+
+
+/***/ }),
+
+/***/ 21256:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+"use strict";
+
+const { Minipass } = __nccwpck_require__(78275)
+const TYPE = Symbol('type')
+const BUFFER = Symbol('buffer')
+
+class Blob {
+  constructor (blobParts, options) {
+    this[TYPE] = ''
+
+    const buffers = []
+    let size = 0
+
+    if (blobParts) {
+      const a = blobParts
+      const length = Number(a.length)
+      for (let i = 0; i < length; i++) {
+        const element = a[i]
+        const buffer = element instanceof Buffer ? element
+          : ArrayBuffer.isView(element)
+            ? Buffer.from(element.buffer, element.byteOffset, element.byteLength)
+            : element instanceof ArrayBuffer ? Buffer.from(element)
+            : element instanceof Blob ? element[BUFFER]
+            : typeof element === 'string' ? Buffer.from(element)
+            : Buffer.from(String(element))
+        size += buffer.length
+        buffers.push(buffer)
       }
-      this.i = 0;
-      this.j = 0;
     }
 
-    function ARC4next() {
-      var t;
-      this.i = (this.i + 1) & 255;
-      this.j = (this.j + this.S[this.i]) & 255;
-      t = this.S[this.i];
-      this.S[this.i] = this.S[this.j];
-      this.S[this.j] = t;
-      return this.S[(t + this.S[this.i]) & 255];
+    this[BUFFER] = Buffer.concat(buffers, size)
+
+    const type = options && options.type !== undefined
+      && String(options.type).toLowerCase()
+    if (type && !/[^\u0020-\u007E]/.test(type)) {
+      this[TYPE] = type
     }
+  }
 
-    Arcfour.prototype.init = ARC4init;
-    Arcfour.prototype.next = ARC4next;
+  get size () {
+    return this[BUFFER].length
+  }
 
-    // Plug in your RNG constructor here
-    function prng_newstate() {
-      return new Arcfour();
-    }
+  get type () {
+    return this[TYPE]
+  }
 
-    // Pool size must be a multiple of 4 and greater than 32.
-    // An array of bytes the size of the pool will be passed to init()
-    var rng_psize = 256;
+  text () {
+    return Promise.resolve(this[BUFFER].toString())
+  }
 
-    if (true) {
-        exports = module.exports = {
-            default: BigInteger,
-            BigInteger: BigInteger,
-            SecureRandom: SecureRandom,
-        };
-    } else {}
+  arrayBuffer () {
+    const buf = this[BUFFER]
+    const off = buf.byteOffset
+    const len = buf.byteLength
+    const ab = buf.buffer.slice(off, off + len)
+    return Promise.resolve(ab)
+  }
 
-}).call(this);
+  stream () {
+    return new Minipass().end(this[BUFFER])
+  }
+
+  slice (start, end, type) {
+    const size = this.size
+    const relativeStart = start === undefined ? 0
+      : start < 0 ? Math.max(size + start, 0)
+      : Math.min(start, size)
+    const relativeEnd = end === undefined ? size
+      : end < 0 ? Math.max(size + end, 0)
+      : Math.min(end, size)
+    const span = Math.max(relativeEnd - relativeStart, 0)
+
+    const buffer = this[BUFFER]
+    const slicedBuffer = buffer.slice(
+      relativeStart,
+      relativeStart + span
+    )
+    const blob = new Blob([], { type })
+    blob[BUFFER] = slicedBuffer
+    return blob
+  }
+
+  get [Symbol.toStringTag] () {
+    return 'Blob'
+  }
+
+  static get BUFFER () {
+    return BUFFER
+  }
+}
+
+Object.defineProperties(Blob.prototype, {
+  size: { enumerable: true },
+  type: { enumerable: true },
+})
+
+module.exports = Blob
 
 
 /***/ }),
 
-/***/ 85743:
+/***/ 28515:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-const { Request, Response } = __nccwpck_require__(88483)
+"use strict";
+
 const { Minipass } = __nccwpck_require__(78275)
-const MinipassFlush = __nccwpck_require__(37633)
-const cacache = __nccwpck_require__(85742)
-const url = __nccwpck_require__(87016)
+const MinipassSized = __nccwpck_require__(48484)
 
-const CachingMinipassPipeline = __nccwpck_require__(22314)
-const CachePolicy = __nccwpck_require__(15281)
-const cacheKey = __nccwpck_require__(45808)
-const remote = __nccwpck_require__(20766)
+const Blob = __nccwpck_require__(21256)
+const { BUFFER } = Blob
+const FetchError = __nccwpck_require__(22644)
+
+// optional dependency on 'encoding'
+let convert
+try {
+  convert = (__nccwpck_require__(24056)/* .convert */ .C)
+} catch (e) {
+  // defer error until textConverted is called
+}
 
-const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop)
+const INTERNALS = Symbol('Body internals')
+const CONSUME_BODY = Symbol('consumeBody')
 
-// allow list for request headers that will be written to the cache index
-// note: we will also store any request headers
-// that are named in a response's vary header
-const KEEP_REQUEST_HEADERS = [
-  'accept-charset',
-  'accept-encoding',
-  'accept-language',
-  'accept',
-  'cache-control',
-]
+class Body {
+  constructor (bodyArg, options = {}) {
+    const { size = 0, timeout = 0 } = options
+    const body = bodyArg === undefined || bodyArg === null ? null
+      : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString())
+      : isBlob(bodyArg) ? bodyArg
+      : Buffer.isBuffer(bodyArg) ? bodyArg
+      : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]'
+        ? Buffer.from(bodyArg)
+        : ArrayBuffer.isView(bodyArg)
+          ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength)
+          : Minipass.isStream(bodyArg) ? bodyArg
+          : Buffer.from(String(bodyArg))
 
-// allow list for response headers that will be written to the cache index
-// note: we must not store the real response's age header, or when we load
-// a cache policy based on the metadata it will think the cached response
-// is always stale
-const KEEP_RESPONSE_HEADERS = [
-  'cache-control',
-  'content-encoding',
-  'content-language',
-  'content-type',
-  'date',
-  'etag',
-  'expires',
-  'last-modified',
-  'link',
-  'location',
-  'pragma',
-  'vary',
-]
+    this[INTERNALS] = {
+      body,
+      disturbed: false,
+      error: null,
+    }
 
-// return an object containing all metadata to be written to the index
-const getMetadata = (request, response, options) => {
-  const metadata = {
-    time: Date.now(),
-    url: request.url,
-    reqHeaders: {},
-    resHeaders: {},
+    this.size = size
+    this.timeout = timeout
 
-    // options on which we must match the request and vary the response
-    options: {
-      compress: options.compress != null ? options.compress : request.compress,
-    },
+    if (Minipass.isStream(body)) {
+      body.on('error', er => {
+        const error = er.name === 'AbortError' ? er
+          : new FetchError(`Invalid response while trying to fetch ${
+            this.url}: ${er.message}`, 'system', er)
+        this[INTERNALS].error = error
+      })
+    }
   }
 
-  // only save the status if it's not a 200 or 304
-  if (response.status !== 200 && response.status !== 304) {
-    metadata.status = response.status
+  get body () {
+    return this[INTERNALS].body
   }
 
-  for (const name of KEEP_REQUEST_HEADERS) {
-    if (request.headers.has(name)) {
-      metadata.reqHeaders[name] = request.headers.get(name)
-    }
+  get bodyUsed () {
+    return this[INTERNALS].disturbed
   }
 
-  // if the request's host header differs from the host in the url
-  // we need to keep it, otherwise it's just noise and we ignore it
-  const host = request.headers.get('host')
-  const parsedUrl = new url.URL(request.url)
-  if (host && parsedUrl.host !== host) {
-    metadata.reqHeaders.host = host
+  arrayBuffer () {
+    return this[CONSUME_BODY]().then(buf =>
+      buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
   }
 
-  // if the response has a vary header, make sure
-  // we store the relevant request headers too
-  if (response.headers.has('vary')) {
-    const vary = response.headers.get('vary')
-    // a vary of "*" means every header causes a different response.
-    // in that scenario, we do not include any additional headers
-    // as the freshness check will always fail anyway and we don't
-    // want to bloat the cache indexes
-    if (vary !== '*') {
-      // copy any other request headers that will vary the response
-      const varyHeaders = vary.trim().toLowerCase().split(/\s*,\s*/)
-      for (const name of varyHeaders) {
-        if (request.headers.has(name)) {
-          metadata.reqHeaders[name] = request.headers.get(name)
-        }
-      }
-    }
+  blob () {
+    const ct = this.headers && this.headers.get('content-type') || ''
+    return this[CONSUME_BODY]().then(buf => Object.assign(
+      new Blob([], { type: ct.toLowerCase() }),
+      { [BUFFER]: buf }
+    ))
   }
 
-  for (const name of KEEP_RESPONSE_HEADERS) {
-    if (response.headers.has(name)) {
-      metadata.resHeaders[name] = response.headers.get(name)
+  async json () {
+    const buf = await this[CONSUME_BODY]()
+    try {
+      return JSON.parse(buf.toString())
+    } catch (er) {
+      throw new FetchError(
+        `invalid json response body at ${this.url} reason: ${er.message}`,
+        'invalid-json'
+      )
     }
   }
 
-  for (const name of options.cacheAdditionalHeaders) {
-    if (response.headers.has(name)) {
-      metadata.resHeaders[name] = response.headers.get(name)
-    }
+  text () {
+    return this[CONSUME_BODY]().then(buf => buf.toString())
   }
 
-  return metadata
-}
+  buffer () {
+    return this[CONSUME_BODY]()
+  }
 
-// symbols used to hide objects that may be lazily evaluated in a getter
-const _request = Symbol('request')
-const _response = Symbol('response')
-const _policy = Symbol('policy')
+  textConverted () {
+    return this[CONSUME_BODY]().then(buf => convertBody(buf, this.headers))
+  }
 
-class CacheEntry {
-  constructor ({ entry, request, response, options }) {
-    if (entry) {
-      this.key = entry.key
-      this.entry = entry
-      // previous versions of this module didn't write an explicit timestamp in
-      // the metadata, so fall back to the entry's timestamp. we can't use the
-      // entry timestamp to determine staleness because cacache will update it
-      // when it verifies its data
-      this.entry.metadata.time = this.entry.metadata.time || this.entry.time
-    } else {
-      this.key = cacheKey(request)
+  [CONSUME_BODY] () {
+    if (this[INTERNALS].disturbed) {
+      return Promise.reject(new TypeError(`body used already for: ${
+        this.url}`))
     }
 
-    this.options = options
-
-    // these properties are behind getters that lazily evaluate
-    this[_request] = request
-    this[_response] = response
-    this[_policy] = null
-  }
-
-  // returns a CacheEntry instance that satisfies the given request
-  // or undefined if no existing entry satisfies
-  static async find (request, options) {
-    try {
-      // compacts the index and returns an array of unique entries
-      var matches = await cacache.index.compact(options.cachePath, cacheKey(request), (A, B) => {
-        const entryA = new CacheEntry({ entry: A, options })
-        const entryB = new CacheEntry({ entry: B, options })
-        return entryA.policy.satisfies(entryB.request)
-      }, {
-        validateEntry: (entry) => {
-          // clean out entries with a buggy content-encoding value
-          if (entry.metadata &&
-              entry.metadata.resHeaders &&
-              entry.metadata.resHeaders['content-encoding'] === null) {
-            return false
-          }
+    this[INTERNALS].disturbed = true
 
-          // if an integrity is null, it needs to have a status specified
-          if (entry.integrity === null) {
-            return !!(entry.metadata && entry.metadata.status)
-          }
+    if (this[INTERNALS].error) {
+      return Promise.reject(this[INTERNALS].error)
+    }
 
-          return true
-        },
-      })
-    } catch (err) {
-      // if the compact request fails, ignore the error and return
-      return
+    // body is null
+    if (this.body === null) {
+      return Promise.resolve(Buffer.alloc(0))
     }
 
-    // a cache mode of 'reload' means to behave as though we have no cache
-    // on the way to the network. return undefined to allow cacheFetch to
-    // create a brand new request no matter what.
-    if (options.cache === 'reload') {
-      return
+    if (Buffer.isBuffer(this.body)) {
+      return Promise.resolve(this.body)
     }
 
-    // find the specific entry that satisfies the request
-    let match
-    for (const entry of matches) {
-      const _entry = new CacheEntry({
-        entry,
-        options,
-      })
+    const upstream = isBlob(this.body) ? this.body.stream() : this.body
 
-      if (_entry.policy.satisfies(request)) {
-        match = _entry
-        break
-      }
+    /* istanbul ignore if: should never happen */
+    if (!Minipass.isStream(upstream)) {
+      return Promise.resolve(Buffer.alloc(0))
     }
 
-    return match
-  }
+    const stream = this.size && upstream instanceof MinipassSized ? upstream
+      : !this.size && upstream instanceof Minipass &&
+        !(upstream instanceof MinipassSized) ? upstream
+      : this.size ? new MinipassSized({ size: this.size })
+      : new Minipass()
 
-  // if the user made a PUT/POST/PATCH then we invalidate our
-  // cache for the same url by deleting the index entirely
-  static async invalidate (request, options) {
-    const key = cacheKey(request)
-    try {
-      await cacache.rm.entry(options.cachePath, key, { removeFully: true })
-    } catch (err) {
-      // ignore errors
-    }
-  }
+    // allow timeout on slow response body, but only if the stream is still writable. this
+    // makes the timeout center on the socket stream from lib/index.js rather than the
+    // intermediary minipass stream we create to receive the data
+    const resTimeout = this.timeout && stream.writable ? setTimeout(() => {
+      stream.emit('error', new FetchError(
+        `Response timeout while trying to fetch ${
+          this.url} (over ${this.timeout}ms)`, 'body-timeout'))
+    }, this.timeout) : null
 
-  get request () {
-    if (!this[_request]) {
-      this[_request] = new Request(this.entry.metadata.url, {
-        method: 'GET',
-        headers: this.entry.metadata.reqHeaders,
-        ...this.entry.metadata.options,
-      })
+    // do not keep the process open just for this timeout, even
+    // though we expect it'll get cleared eventually.
+    if (resTimeout && resTimeout.unref) {
+      resTimeout.unref()
     }
 
-    return this[_request]
+    // do the pipe in the promise, because the pipe() can send too much
+    // data through right away and upset the MP Sized object
+    return new Promise((resolve) => {
+      // if the stream is some other kind of stream, then pipe through a MP
+      // so we can collect it more easily.
+      if (stream !== upstream) {
+        upstream.on('error', er => stream.emit('error', er))
+        upstream.pipe(stream)
+      }
+      resolve()
+    }).then(() => stream.concat()).then(buf => {
+      clearTimeout(resTimeout)
+      return buf
+    }).catch(er => {
+      clearTimeout(resTimeout)
+      // request was aborted, reject with this Error
+      if (er.name === 'AbortError' || er.name === 'FetchError') {
+        throw er
+      } else if (er.name === 'RangeError') {
+        throw new FetchError(`Could not create Buffer from response body for ${
+          this.url}: ${er.message}`, 'system', er)
+      } else {
+        // other errors, such as incorrect content-encoding or content-length
+        throw new FetchError(`Invalid response body while trying to fetch ${
+          this.url}: ${er.message}`, 'system', er)
+      }
+    })
   }
 
-  get response () {
-    if (!this[_response]) {
-      this[_response] = new Response(null, {
-        url: this.entry.metadata.url,
-        counter: this.options.counter,
-        status: this.entry.metadata.status || 200,
-        headers: {
-          ...this.entry.metadata.resHeaders,
-          'content-length': this.entry.size,
-        },
-      })
+  static clone (instance) {
+    if (instance.bodyUsed) {
+      throw new Error('cannot clone body after it is used')
     }
 
-    return this[_response]
-  }
+    const body = instance.body
 
-  get policy () {
-    if (!this[_policy]) {
-      this[_policy] = new CachePolicy({
-        entry: this.entry,
-        request: this.request,
-        response: this.response,
-        options: this.options,
+    // check that body is a stream and not form-data object
+    // NB: can't clone the form-data object without having it as a dependency
+    if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') {
+      // create a dedicated tee stream so that we don't lose data
+      // potentially sitting in the body stream's buffer by writing it
+      // immediately to p1 and not having it for p2.
+      const tee = new Minipass()
+      const p1 = new Minipass()
+      const p2 = new Minipass()
+      tee.on('error', er => {
+        p1.emit('error', er)
+        p2.emit('error', er)
       })
+      body.on('error', er => tee.emit('error', er))
+      tee.pipe(p1)
+      tee.pipe(p2)
+      body.pipe(tee)
+      // set instance body to one fork, return the other
+      instance[INTERNALS].body = p1
+      return p2
+    } else {
+      return instance.body
     }
-
-    return this[_policy]
   }
 
-  // wraps the response in a pipeline that stores the data
-  // in the cache while the user consumes it
-  async store (status) {
-    // if we got a status other than 200, 301, or 308,
-    // or the CachePolicy forbid storage, append the
-    // cache status header and return it untouched
-    if (
-      this.request.method !== 'GET' ||
-      ![200, 301, 308].includes(this.response.status) ||
-      !this.policy.storable()
-    ) {
-      this.response.headers.set('x-local-cache-status', 'skip')
-      return this.response
-    }
-
-    const size = this.response.headers.get('content-length')
-    const cacheOpts = {
-      algorithms: this.options.algorithms,
-      metadata: getMetadata(this.request, this.response, this.options),
-      size,
-      integrity: this.options.integrity,
-      integrityEmitter: this.response.body.hasIntegrityEmitter && this.response.body,
-    }
-
-    let body = null
-    // we only set a body if the status is a 200, redirects are
-    // stored as metadata only
-    if (this.response.status === 200) {
-      let cacheWriteResolve, cacheWriteReject
-      const cacheWritePromise = new Promise((resolve, reject) => {
-        cacheWriteResolve = resolve
-        cacheWriteReject = reject
-      }).catch((err) => {
-        body.emit('error', err)
-      })
+  static extractContentType (body) {
+    return body === null || body === undefined ? null
+      : typeof body === 'string' ? 'text/plain;charset=UTF-8'
+      : isURLSearchParams(body)
+        ? 'application/x-www-form-urlencoded;charset=UTF-8'
+        : isBlob(body) ? body.type || null
+        : Buffer.isBuffer(body) ? null
+        : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null
+        : ArrayBuffer.isView(body) ? null
+        : typeof body.getBoundary === 'function'
+          ? `multipart/form-data;boundary=${body.getBoundary()}`
+          : Minipass.isStream(body) ? null
+          : 'text/plain;charset=UTF-8'
+  }
 
-      body = new CachingMinipassPipeline({ events: ['integrity', 'size'] }, new MinipassFlush({
-        flush () {
-          return cacheWritePromise
-        },
-      }))
-      // this is always true since if we aren't reusing the one from the remote fetch, we
-      // are using the one from cacache
-      body.hasIntegrityEmitter = true
+  static getTotalBytes (instance) {
+    const { body } = instance
+    return (body === null || body === undefined) ? 0
+      : isBlob(body) ? body.size
+      : Buffer.isBuffer(body) ? body.length
+      : body && typeof body.getLengthSync === 'function' && (
+        // detect form data input from form-data module
+        body._lengthRetrievers &&
+        /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x
+        body.hasKnownLength && body.hasKnownLength()) // 2.x
+        ? body.getLengthSync()
+        : null
+  }
 
-      const onResume = () => {
-        const tee = new Minipass()
-        const cacheStream = cacache.put.stream(this.options.cachePath, this.key, cacheOpts)
-        // re-emit the integrity and size events on our new response body so they can be reused
-        cacheStream.on('integrity', i => body.emit('integrity', i))
-        cacheStream.on('size', s => body.emit('size', s))
-        // stick a flag on here so downstream users will know if they can expect integrity events
-        tee.pipe(cacheStream)
-        // TODO if the cache write fails, log a warning but return the response anyway
-        // eslint-disable-next-line promise/catch-or-return
-        cacheStream.promise().then(cacheWriteResolve, cacheWriteReject)
-        body.unshift(tee)
-        body.unshift(this.response.body)
-      }
+  static writeToStream (dest, instance) {
+    const { body } = instance
 
-      body.once('resume', onResume)
-      body.once('end', () => body.removeListener('resume', onResume))
+    if (body === null || body === undefined) {
+      dest.end()
+    } else if (Buffer.isBuffer(body) || typeof body === 'string') {
+      dest.end(body)
     } else {
-      await cacache.index.insert(this.options.cachePath, this.key, null, cacheOpts)
+      // body is stream or blob
+      const stream = isBlob(body) ? body.stream() : body
+      stream.on('error', er => dest.emit('error', er)).pipe(dest)
     }
 
-    // note: we do not set the x-local-cache-hash header because we do not know
-    // the hash value until after the write to the cache completes, which doesn't
-    // happen until after the response has been sent and it's too late to write
-    // the header anyway
-    this.response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath))
-    this.response.headers.set('x-local-cache-key', encodeURIComponent(this.key))
-    this.response.headers.set('x-local-cache-mode', 'stream')
-    this.response.headers.set('x-local-cache-status', status)
-    this.response.headers.set('x-local-cache-time', new Date().toISOString())
-    const newResponse = new Response(body, {
-      url: this.response.url,
-      status: this.response.status,
-      headers: this.response.headers,
-      counter: this.options.counter,
-    })
-    return newResponse
+    return dest
   }
+}
 
-  // use the cached data to create a response and return it
-  async respond (method, options, status) {
-    let response
-    if (method === 'HEAD' || [301, 308].includes(this.response.status)) {
-      // if the request is a HEAD, or the response is a redirect,
-      // then the metadata in the entry already includes everything
-      // we need to build a response
-      response = this.response
-    } else {
-      // we're responding with a full cached response, so create a body
-      // that reads from cacache and attach it to a new Response
-      const body = new Minipass()
-      const headers = { ...this.policy.responseHeaders() }
-
-      const onResume = () => {
-        const cacheStream = cacache.get.stream.byDigest(
-          this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize }
-        )
-        cacheStream.on('error', async (err) => {
-          cacheStream.pause()
-          if (err.code === 'EINTEGRITY') {
-            await cacache.rm.content(
-              this.options.cachePath, this.entry.integrity, { memoize: this.options.memoize }
-            )
-          }
-          if (err.code === 'ENOENT' || err.code === 'EINTEGRITY') {
-            await CacheEntry.invalidate(this.request, this.options)
-          }
-          body.emit('error', err)
-          cacheStream.resume()
-        })
-        // emit the integrity and size events based on our metadata so we're consistent
-        body.emit('integrity', this.entry.integrity)
-        body.emit('size', Number(headers['content-length']))
-        cacheStream.pipe(body)
-      }
+Object.defineProperties(Body.prototype, {
+  body: { enumerable: true },
+  bodyUsed: { enumerable: true },
+  arrayBuffer: { enumerable: true },
+  blob: { enumerable: true },
+  json: { enumerable: true },
+  text: { enumerable: true },
+})
 
-      body.once('resume', onResume)
-      body.once('end', () => body.removeListener('resume', onResume))
-      response = new Response(body, {
-        url: this.entry.metadata.url,
-        counter: options.counter,
-        status: 200,
-        headers,
-      })
-    }
+const isURLSearchParams = obj =>
+  // Duck-typing as a necessary condition.
+  (typeof obj !== 'object' ||
+    typeof obj.append !== 'function' ||
+    typeof obj.delete !== 'function' ||
+    typeof obj.get !== 'function' ||
+    typeof obj.getAll !== 'function' ||
+    typeof obj.has !== 'function' ||
+    typeof obj.set !== 'function') ? false
+  // Brand-checking and more duck-typing as optional condition.
+  : obj.constructor.name === 'URLSearchParams' ||
+    Object.prototype.toString.call(obj) === '[object URLSearchParams]' ||
+    typeof obj.sort === 'function'
 
-    response.headers.set('x-local-cache', encodeURIComponent(this.options.cachePath))
-    response.headers.set('x-local-cache-hash', encodeURIComponent(this.entry.integrity))
-    response.headers.set('x-local-cache-key', encodeURIComponent(this.key))
-    response.headers.set('x-local-cache-mode', 'stream')
-    response.headers.set('x-local-cache-status', status)
-    response.headers.set('x-local-cache-time', new Date(this.entry.metadata.time).toUTCString())
-    return response
-  }
+const isBlob = obj =>
+  typeof obj === 'object' &&
+  typeof obj.arrayBuffer === 'function' &&
+  typeof obj.type === 'string' &&
+  typeof obj.stream === 'function' &&
+  typeof obj.constructor === 'function' &&
+  typeof obj.constructor.name === 'string' &&
+  /^(Blob|File)$/.test(obj.constructor.name) &&
+  /^(Blob|File)$/.test(obj[Symbol.toStringTag])
 
-  // use the provided request along with this cache entry to
-  // revalidate the stored response. returns a response, either
-  // from the cache or from the update
-  async revalidate (request, options) {
-    const revalidateRequest = new Request(request, {
-      headers: this.policy.revalidationHeaders(request),
-    })
+const convertBody = (buffer, headers) => {
+  /* istanbul ignore if */
+  if (typeof convert !== 'function') {
+    throw new Error('The package `encoding` must be installed to use the textConverted() function')
+  }
 
-    try {
-      // NOTE: be sure to remove the headers property from the
-      // user supplied options, since we have already defined
-      // them on the new request object. if they're still in the
-      // options then those will overwrite the ones from the policy
-      var response = await remote(revalidateRequest, {
-        ...options,
-        headers: undefined,
-      })
-    } catch (err) {
-      // if the network fetch fails, return the stale
-      // cached response unless it has a cache-control
-      // of 'must-revalidate'
-      if (!this.policy.mustRevalidate) {
-        return this.respond(request.method, options, 'stale')
-      }
+  const ct = headers && headers.get('content-type')
+  let charset = 'utf-8'
+  let res
 
-      throw err
-    }
+  // header
+  if (ct) {
+    res = /charset=([^;]*)/i.exec(ct)
+  }
 
-    if (this.policy.revalidated(revalidateRequest, response)) {
-      // we got a 304, write a new index to the cache and respond from cache
-      const metadata = getMetadata(request, response, options)
-      // 304 responses do not include headers that are specific to the response data
-      // since they do not include a body, so we copy values for headers that were
-      // in the old cache entry to the new one, if the new metadata does not already
-      // include that header
-      for (const name of KEEP_RESPONSE_HEADERS) {
-        if (
-          !hasOwnProperty(metadata.resHeaders, name) &&
-          hasOwnProperty(this.entry.metadata.resHeaders, name)
-        ) {
-          metadata.resHeaders[name] = this.entry.metadata.resHeaders[name]
-        }
-      }
+  // no charset in content type, peek at response body for at most 1024 bytes
+  const str = buffer.slice(0, 1024).toString()
 
-      for (const name of options.cacheAdditionalHeaders) {
-        const inMeta = hasOwnProperty(metadata.resHeaders, name)
-        const inEntry = hasOwnProperty(this.entry.metadata.resHeaders, name)
-        const inPolicy = hasOwnProperty(this.policy.response.headers, name)
+  // html5
+  if (!res && str) {
+    res = / {
+  // found charset
+  if (res) {
+    charset = res.pop()
 
-class NotCachedError extends Error {
-  constructor (url) {
-    /* eslint-disable-next-line max-len */
-    super(`request to ${url} failed: cache mode is 'only-if-cached' but no cached response is available.`)
-    this.code = 'ENOTCACHED'
+    // prevent decode issues when sites use incorrect encoding
+    // ref: https://hsivonen.fi/encoding-menu/
+    if (charset === 'gb2312' || charset === 'gbk') {
+      charset = 'gb18030'
+    }
   }
-}
 
-module.exports = {
-  NotCachedError,
+  // turn raw buffers into a single utf-8 buffer
+  return convert(
+    buffer,
+    'UTF-8',
+    charset
+  ).toString()
 }
 
+module.exports = Body
+
 
 /***/ }),
 
-/***/ 96807:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 22644:
+/***/ ((module) => {
 
-const { NotCachedError } = __nccwpck_require__(59456)
-const CacheEntry = __nccwpck_require__(85743)
-const remote = __nccwpck_require__(20766)
+"use strict";
 
-// do whatever is necessary to get a Response and return it
-const cacheFetch = async (request, options) => {
-  // try to find a cached entry that satisfies this request
-  const entry = await CacheEntry.find(request, options)
-  if (!entry) {
-    // no cached result, if the cache mode is 'only-if-cached' that's a failure
-    if (options.cache === 'only-if-cached') {
-      throw new NotCachedError(request.url)
+class FetchError extends Error {
+  constructor (message, type, systemError) {
+    super(message)
+    this.code = 'FETCH_ERROR'
+
+    // pick up code, expected, path, ...
+    if (systemError) {
+      Object.assign(this, systemError)
     }
 
-    // otherwise, we make a request, store it and return it
-    const response = await remote(request, options)
-    const newEntry = new CacheEntry({ request, response, options })
-    return newEntry.store('miss')
-  }
+    this.errno = this.code
 
-  // we have a cached response that satisfies this request, however if the cache
-  // mode is 'no-cache' then we send the revalidation request no matter what
-  if (options.cache === 'no-cache') {
-    return entry.revalidate(request, options)
+    // override anything the system error might've clobbered
+    this.type = this.code === 'EBADSIZE' && this.found > this.expect
+      ? 'max-size' : type
+    this.message = message
+    Error.captureStackTrace(this, this.constructor)
   }
 
-  // if the cached entry is not stale, or if the cache mode is 'force-cache' or
-  // 'only-if-cached' we can respond with the cached entry. set the status
-  // based on the result of needsRevalidation and respond
-  const _needsRevalidation = entry.policy.needsRevalidation(request)
-  if (options.cache === 'force-cache' ||
-      options.cache === 'only-if-cached' ||
-      !_needsRevalidation) {
-    return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit')
+  get name () {
+    return 'FetchError'
   }
 
-  // if we got here, the cache entry is stale so revalidate it
-  return entry.revalidate(request, options)
-}
+  // don't allow name to be overwritten
+  set name (n) {}
 
-cacheFetch.invalidate = async (request, options) => {
-  if (!options.cachePath) {
-    return
+  get [Symbol.toStringTag] () {
+    return 'FetchError'
   }
-
-  return CacheEntry.invalidate(request, options)
 }
-
-module.exports = cacheFetch
+module.exports = FetchError
 
 
 /***/ }),
 
-/***/ 45808:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 98645:
+/***/ ((module) => {
 
-const { URL, format } = __nccwpck_require__(87016)
+"use strict";
 
-// options passed to url.format() when generating a key
-const formatOptions = {
-  auth: false,
-  fragment: false,
-  search: true,
-  unicode: false,
+const invalidTokenRegex = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/
+const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+
+const validateName = name => {
+  name = `${name}`
+  if (invalidTokenRegex.test(name) || name === '') {
+    throw new TypeError(`${name} is not a legal HTTP header name`)
+  }
 }
 
-// returns a string to be used as the cache key for the Request
-const cacheKey = (request) => {
-  const parsed = new URL(request.url)
-  return `make-fetch-happen:request-cache:${format(parsed, formatOptions)}`
+const validateValue = value => {
+  value = `${value}`
+  if (invalidHeaderCharRegex.test(value)) {
+    throw new TypeError(`${value} is not a legal HTTP header value`)
+  }
 }
 
-module.exports = cacheKey
+const find = (map, name) => {
+  name = name.toLowerCase()
+  for (const key in map) {
+    if (key.toLowerCase() === name) {
+      return key
+    }
+  }
+  return undefined
+}
 
+const MAP = Symbol('map')
+class Headers {
+  constructor (init = undefined) {
+    this[MAP] = Object.create(null)
+    if (init instanceof Headers) {
+      const rawHeaders = init.raw()
+      const headerNames = Object.keys(rawHeaders)
+      for (const headerName of headerNames) {
+        for (const value of rawHeaders[headerName]) {
+          this.append(headerName, value)
+        }
+      }
+      return
+    }
 
-/***/ }),
+    // no-op
+    if (init === undefined || init === null) {
+      return
+    }
 
-/***/ 15281:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    if (typeof init === 'object') {
+      const method = init[Symbol.iterator]
+      if (method !== null && method !== undefined) {
+        if (typeof method !== 'function') {
+          throw new TypeError('Header pairs must be iterable')
+        }
 
-const CacheSemantics = __nccwpck_require__(12203)
-const Negotiator = __nccwpck_require__(60668)
-const ssri = __nccwpck_require__(68951)
+        // sequence>
+        // Note: per spec we have to first exhaust the lists then process them
+        const pairs = []
+        for (const pair of init) {
+          if (typeof pair !== 'object' ||
+              typeof pair[Symbol.iterator] !== 'function') {
+            throw new TypeError('Each header pair must be iterable')
+          }
+          const arrPair = Array.from(pair)
+          if (arrPair.length !== 2) {
+            throw new TypeError('Each header pair must be a name/value tuple')
+          }
+          pairs.push(arrPair)
+        }
 
-// options passed to http-cache-semantics constructor
-const policyOptions = {
-  shared: false,
-  ignoreCargoCult: true,
-}
+        for (const pair of pairs) {
+          this.append(pair[0], pair[1])
+        }
+      } else {
+        // record
+        for (const key of Object.keys(init)) {
+          this.append(key, init[key])
+        }
+      }
+    } else {
+      throw new TypeError('Provided initializer must be an object')
+    }
+  }
 
-// a fake empty response, used when only testing the
-// request for storability
-const emptyResponse = { status: 200, headers: {} }
+  get (name) {
+    name = `${name}`
+    validateName(name)
+    const key = find(this[MAP], name)
+    if (key === undefined) {
+      return null
+    }
 
-// returns a plain object representation of the Request
-const requestObject = (request) => {
-  const _obj = {
-    method: request.method,
-    url: request.url,
-    headers: {},
-    compress: request.compress,
+    return this[MAP][key].join(', ')
   }
 
-  request.headers.forEach((value, key) => {
-    _obj.headers[key] = value
-  })
+  forEach (callback, thisArg = undefined) {
+    let pairs = getHeaders(this)
+    for (let i = 0; i < pairs.length; i++) {
+      const [name, value] = pairs[i]
+      callback.call(thisArg, value, name, this)
+      // refresh in case the callback added more headers
+      pairs = getHeaders(this)
+    }
+  }
 
-  return _obj
-}
+  set (name, value) {
+    name = `${name}`
+    value = `${value}`
+    validateName(name)
+    validateValue(value)
+    const key = find(this[MAP], name)
+    this[MAP][key !== undefined ? key : name] = [value]
+  }
 
-// returns a plain object representation of the Response
-const responseObject = (response) => {
-  const _obj = {
-    status: response.status,
-    headers: {},
+  append (name, value) {
+    name = `${name}`
+    value = `${value}`
+    validateName(name)
+    validateValue(value)
+    const key = find(this[MAP], name)
+    if (key !== undefined) {
+      this[MAP][key].push(value)
+    } else {
+      this[MAP][name] = [value]
+    }
   }
 
-  response.headers.forEach((value, key) => {
-    _obj.headers[key] = value
-  })
+  has (name) {
+    name = `${name}`
+    validateName(name)
+    return find(this[MAP], name) !== undefined
+  }
 
-  return _obj
-}
+  delete (name) {
+    name = `${name}`
+    validateName(name)
+    const key = find(this[MAP], name)
+    if (key !== undefined) {
+      delete this[MAP][key]
+    }
+  }
 
-class CachePolicy {
-  constructor ({ entry, request, response, options }) {
-    this.entry = entry
-    this.request = requestObject(request)
-    this.response = responseObject(response)
-    this.options = options
-    this.policy = new CacheSemantics(this.request, this.response, policyOptions)
+  raw () {
+    return this[MAP]
+  }
 
-    if (this.entry) {
-      // if we have an entry, copy the timestamp to the _responseTime
-      // this is necessary because the CacheSemantics constructor forces
-      // the value to Date.now() which means a policy created from a
-      // cache entry is likely to always identify itself as stale
-      this.policy._responseTime = this.entry.metadata.time
-    }
+  keys () {
+    return new HeadersIterator(this, 'key')
   }
 
-  // static method to quickly determine if a request alone is storable
-  static storable (request, options) {
-    // no cachePath means no caching
-    if (!options.cachePath) {
-      return false
-    }
+  values () {
+    return new HeadersIterator(this, 'value')
+  }
 
-    // user explicitly asked not to cache
-    if (options.cache === 'no-store') {
-      return false
-    }
+  [Symbol.iterator] () {
+    return new HeadersIterator(this, 'key+value')
+  }
 
-    // we only cache GET and HEAD requests
-    if (!['GET', 'HEAD'].includes(request.method)) {
-      return false
-    }
+  entries () {
+    return new HeadersIterator(this, 'key+value')
+  }
 
-    // otherwise, let http-cache-semantics make the decision
-    // based on the request's headers
-    const policy = new CacheSemantics(requestObject(request), emptyResponse, policyOptions)
-    return policy.storable()
+  get [Symbol.toStringTag] () {
+    return 'Headers'
   }
 
-  // returns true if the policy satisfies the request
-  satisfies (request) {
-    const _req = requestObject(request)
-    if (this.request.headers.host !== _req.headers.host) {
-      return false
-    }
+  static exportNodeCompatibleHeaders (headers) {
+    const obj = Object.assign(Object.create(null), headers[MAP])
 
-    if (this.request.compress !== _req.compress) {
-      return false
+    // http.request() only supports string as Host header. This hack makes
+    // specifying custom Host header possible.
+    const hostHeaderKey = find(headers[MAP], 'Host')
+    if (hostHeaderKey !== undefined) {
+      obj[hostHeaderKey] = obj[hostHeaderKey][0]
     }
 
-    const negotiatorA = new Negotiator(this.request)
-    const negotiatorB = new Negotiator(_req)
+    return obj
+  }
 
-    if (JSON.stringify(negotiatorA.mediaTypes()) !== JSON.stringify(negotiatorB.mediaTypes())) {
-      return false
-    }
+  static createHeadersLenient (obj) {
+    const headers = new Headers()
+    for (const name of Object.keys(obj)) {
+      if (invalidTokenRegex.test(name)) {
+        continue
+      }
 
-    if (JSON.stringify(negotiatorA.languages()) !== JSON.stringify(negotiatorB.languages())) {
-      return false
-    }
+      if (Array.isArray(obj[name])) {
+        for (const val of obj[name]) {
+          if (invalidHeaderCharRegex.test(val)) {
+            continue
+          }
 
-    if (JSON.stringify(negotiatorA.encodings()) !== JSON.stringify(negotiatorB.encodings())) {
-      return false
+          if (headers[MAP][name] === undefined) {
+            headers[MAP][name] = [val]
+          } else {
+            headers[MAP][name].push(val)
+          }
+        }
+      } else if (!invalidHeaderCharRegex.test(obj[name])) {
+        headers[MAP][name] = [obj[name]]
+      }
     }
+    return headers
+  }
+}
 
-    if (this.options.integrity) {
-      return ssri.parse(this.options.integrity).match(this.entry.integrity)
-    }
+Object.defineProperties(Headers.prototype, {
+  get: { enumerable: true },
+  forEach: { enumerable: true },
+  set: { enumerable: true },
+  append: { enumerable: true },
+  has: { enumerable: true },
+  delete: { enumerable: true },
+  keys: { enumerable: true },
+  values: { enumerable: true },
+  entries: { enumerable: true },
+})
+
+const getHeaders = (headers, kind = 'key+value') =>
+  Object.keys(headers[MAP]).sort().map(
+    kind === 'key' ? k => k.toLowerCase()
+    : kind === 'value' ? k => headers[MAP][k].join(', ')
+    : k => [k.toLowerCase(), headers[MAP][k].join(', ')]
+  )
 
-    return true
-  }
+const INTERNAL = Symbol('internal')
 
-  // returns true if the request and response allow caching
-  storable () {
-    return this.policy.storable()
+class HeadersIterator {
+  constructor (target, kind) {
+    this[INTERNAL] = {
+      target,
+      kind,
+      index: 0,
+    }
   }
 
-  // NOTE: this is a hack to avoid parsing the cache-control
-  // header ourselves, it returns true if the response's
-  // cache-control contains must-revalidate
-  get mustRevalidate () {
-    return !!this.policy._rescc['must-revalidate']
+  get [Symbol.toStringTag] () {
+    return 'HeadersIterator'
   }
 
-  // returns true if the cached response requires revalidation
-  // for the given request
-  needsRevalidation (request) {
-    const _req = requestObject(request)
-    // force method to GET because we only cache GETs
-    // but can serve a HEAD from a cached GET
-    _req.method = 'GET'
-    return !this.policy.satisfiesWithoutRevalidation(_req)
-  }
+  next () {
+    /* istanbul ignore if: should be impossible */
+    if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) {
+      throw new TypeError('Value of `this` is not a HeadersIterator')
+    }
 
-  responseHeaders () {
-    return this.policy.responseHeaders()
-  }
+    const { target, kind, index } = this[INTERNAL]
+    const values = getHeaders(target, kind)
+    const len = values.length
+    if (index >= len) {
+      return {
+        value: undefined,
+        done: true,
+      }
+    }
 
-  // returns a new object containing the appropriate headers
-  // to send a revalidation request
-  revalidationHeaders (request) {
-    const _req = requestObject(request)
-    return this.policy.revalidationHeaders(_req)
-  }
+    this[INTERNAL].index++
 
-  // returns true if the request/response was revalidated
-  // successfully. returns false if a new response was received
-  revalidated (request, response) {
-    const _req = requestObject(request)
-    const _res = responseObject(response)
-    const policy = this.policy.revalidatedPolicy(_req, _res)
-    return !policy.modified
+    return { value: values[index], done: false }
   }
 }
 
-module.exports = CachePolicy
+// manually extend because 'extends' requires a ctor
+Object.setPrototypeOf(HeadersIterator.prototype,
+  Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())))
+
+module.exports = Headers
 
 
 /***/ }),
 
-/***/ 67242:
+/***/ 88483:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
+const { URL } = __nccwpck_require__(87016)
+const http = __nccwpck_require__(58611)
+const https = __nccwpck_require__(65692)
+const zlib = __nccwpck_require__(37119)
+const { Minipass } = __nccwpck_require__(78275)
 
-const { FetchError, Request, isRedirect } = __nccwpck_require__(88483)
-const url = __nccwpck_require__(87016)
-
-const CachePolicy = __nccwpck_require__(15281)
-const cache = __nccwpck_require__(96807)
-const remote = __nccwpck_require__(20766)
-
-// given a Request, a Response and user options
-// return true if the response is a redirect that
-// can be followed. we throw errors that will result
-// in the fetch being rejected if the redirect is
-// possible but invalid for some reason
-const canFollowRedirect = (request, response, options) => {
-  if (!isRedirect(response.status)) {
-    return false
-  }
-
-  if (options.redirect === 'manual') {
-    return false
-  }
+const Body = __nccwpck_require__(28515)
+const { writeToStream, getTotalBytes } = Body
+const Response = __nccwpck_require__(43852)
+const Headers = __nccwpck_require__(98645)
+const { createHeadersLenient } = Headers
+const Request = __nccwpck_require__(99586)
+const { getNodeRequestOptions } = Request
+const FetchError = __nccwpck_require__(22644)
+const AbortError = __nccwpck_require__(57442)
 
-  if (options.redirect === 'error') {
-    throw new FetchError(`redirect mode is set to error: ${request.url}`,
-      'no-redirect', { code: 'ENOREDIRECT' })
-  }
+// XXX this should really be split up and unit-ized for easier testing
+// and better DRY implementation of data/http request aborting
+const fetch = async (url, opts) => {
+  if (/^data:/.test(url)) {
+    const request = new Request(url, opts)
+    // delay 1 promise tick so that the consumer can abort right away
+    return Promise.resolve().then(() => new Promise((resolve, reject) => {
+      let type, data
+      try {
+        const { pathname, search } = new URL(url)
+        const split = pathname.split(',')
+        if (split.length < 2) {
+          throw new Error('invalid data: URI')
+        }
+        const mime = split.shift()
+        const base64 = /;base64$/.test(mime)
+        type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime
+        const rawData = decodeURIComponent(split.join(',') + search)
+        data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData)
+      } catch (er) {
+        return reject(new FetchError(`[${request.method}] ${
+          request.url} invalid URL, ${er.message}`, 'system', er))
+      }
 
-  if (!response.headers.has('location')) {
-    throw new FetchError(`redirect location header missing for: ${request.url}`,
-      'no-location', { code: 'EINVALIDREDIRECT' })
-  }
+      const { signal } = request
+      if (signal && signal.aborted) {
+        return reject(new AbortError('The user aborted a request.'))
+      }
 
-  if (request.counter >= request.follow) {
-    throw new FetchError(`maximum redirect reached at: ${request.url}`,
-      'max-redirect', { code: 'EMAXREDIRECT' })
+      const headers = { 'Content-Length': data.length }
+      if (type) {
+        headers['Content-Type'] = type
+      }
+      return resolve(new Response(data, { headers }))
+    }))
   }
 
-  return true
-}
-
-// given a Request, a Response, and the user's options return an object
-// with a new Request and a new options object that will be used for
-// following the redirect
-const getRedirect = (request, response, options) => {
-  const _opts = { ...options }
-  const location = response.headers.get('location')
-  const redirectUrl = new url.URL(location, /^https?:/.test(location) ? undefined : request.url)
-  // Comment below is used under the following license:
-  /**
-   * @license
-   * Copyright (c) 2010-2012 Mikeal Rogers
-   * Licensed under the Apache License, Version 2.0 (the "License");
-   * you may not use this file except in compliance with the License.
-   * You may obtain a copy of the License at
-   * http://www.apache.org/licenses/LICENSE-2.0
-   * Unless required by applicable law or agreed to in writing,
-   * software distributed under the License is distributed on an "AS
-   * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
-   * express or implied. See the License for the specific language
-   * governing permissions and limitations under the License.
-   */
+  return new Promise((resolve, reject) => {
+    // build request object
+    const request = new Request(url, opts)
+    let options
+    try {
+      options = getNodeRequestOptions(request)
+    } catch (er) {
+      return reject(er)
+    }
 
-  // Remove authorization if changing hostnames (but not if just
-  // changing ports or protocols).  This matches the behavior of request:
-  // https://github.com/request/request/blob/b12a6245/lib/redirect.js#L134-L138
-  if (new url.URL(request.url).hostname !== redirectUrl.hostname) {
-    request.headers.delete('authorization')
-    request.headers.delete('cookie')
-  }
+    const send = (options.protocol === 'https:' ? https : http).request
+    const { signal } = request
+    let response = null
+    const abort = () => {
+      const error = new AbortError('The user aborted a request.')
+      reject(error)
+      if (Minipass.isStream(request.body) &&
+          typeof request.body.destroy === 'function') {
+        request.body.destroy(error)
+      }
+      if (response && response.body) {
+        response.body.emit('error', error)
+      }
+    }
 
-  // for POST request with 301/302 response, or any request with 303 response,
-  // use GET when following redirect
-  if (
-    response.status === 303 ||
-    (request.method === 'POST' && [301, 302].includes(response.status))
-  ) {
-    _opts.method = 'GET'
-    _opts.body = null
-    request.headers.delete('content-length')
-  }
+    if (signal && signal.aborted) {
+      return abort()
+    }
 
-  _opts.headers = {}
-  request.headers.forEach((value, key) => {
-    _opts.headers[key] = value
-  })
+    const abortAndFinalize = () => {
+      abort()
+      finalize()
+    }
 
-  _opts.counter = ++request.counter
-  const redirectReq = new Request(url.format(redirectUrl), _opts)
-  return {
-    request: redirectReq,
-    options: _opts,
-  }
-}
+    const finalize = () => {
+      req.abort()
+      if (signal) {
+        signal.removeEventListener('abort', abortAndFinalize)
+      }
+      clearTimeout(reqTimeout)
+    }
 
-const fetch = async (request, options) => {
-  const response = CachePolicy.storable(request, options)
-    ? await cache(request, options)
-    : await remote(request, options)
+    // send request
+    const req = send(options)
 
-  // if the request wasn't a GET or HEAD, and the response
-  // status is between 200 and 399 inclusive, invalidate the
-  // request url
-  if (!['GET', 'HEAD'].includes(request.method) &&
-      response.status >= 200 &&
-      response.status <= 399) {
-    await cache.invalidate(request, options)
-  }
+    if (signal) {
+      signal.addEventListener('abort', abortAndFinalize)
+    }
 
-  if (!canFollowRedirect(request, response, options)) {
-    return response
-  }
+    let reqTimeout = null
+    if (request.timeout) {
+      req.once('socket', () => {
+        reqTimeout = setTimeout(() => {
+          reject(new FetchError(`network timeout at: ${
+            request.url}`, 'request-timeout'))
+          finalize()
+        }, request.timeout)
+      })
+    }
 
-  const redirect = getRedirect(request, response, options)
-  return fetch(redirect.request, redirect.options)
-}
+    req.on('error', er => {
+      // if a 'response' event is emitted before the 'error' event, then by the
+      // time this handler is run it's too late to reject the Promise for the
+      // response. instead, we forward the error event to the response stream
+      // so that the error will surface to the user when they try to consume
+      // the body. this is done as a side effect of aborting the request except
+      // for in windows, where we must forward the event manually, otherwise
+      // there is no longer a ref'd socket attached to the request and the
+      // stream never ends so the event loop runs out of work and the process
+      // exits without warning.
+      // coverage skipped here due to the difficulty in testing
+      // istanbul ignore next
+      if (req.res) {
+        req.res.emit('error', er)
+      }
+      reject(new FetchError(`request to ${request.url} failed, reason: ${
+        er.message}`, 'system', er))
+      finalize()
+    })
 
-module.exports = fetch
+    req.on('response', res => {
+      clearTimeout(reqTimeout)
 
+      const headers = createHeadersLenient(res.headers)
 
-/***/ }),
+      // HTTP fetch step 5
+      if (fetch.isRedirect(res.statusCode)) {
+        // HTTP fetch step 5.2
+        const location = headers.get('Location')
 
-/***/ 39310:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+        // HTTP fetch step 5.3
+        let locationURL = null
+        try {
+          locationURL = location === null ? null : new URL(location, request.url).toString()
+        } catch {
+          // error here can only be invalid URL in Location: header
+          // do not throw when options.redirect == manual
+          // let the user extract the errorneous redirect URL
+          if (request.redirect !== 'manual') {
+            /* eslint-disable-next-line max-len */
+            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'))
+            finalize()
+            return
+          }
+        }
 
-const { FetchError, Headers, Request, Response } = __nccwpck_require__(88483)
+        // HTTP fetch step 5.5
+        if (request.redirect === 'error') {
+          reject(new FetchError('uri requested responds with a redirect, ' +
+            `redirect mode is set to error: ${request.url}`, 'no-redirect'))
+          finalize()
+          return
+        } else if (request.redirect === 'manual') {
+          // node-fetch-specific step: make manual redirect a bit easier to
+          // use by setting the Location header value to the resolved URL.
+          if (locationURL !== null) {
+            // handle corrupted header
+            try {
+              headers.set('Location', locationURL)
+            } catch (err) {
+              /* istanbul ignore next: nodejs server prevent invalid
+                 response headers, we can't test this through normal
+                 request */
+              reject(err)
+            }
+          }
+        } else if (request.redirect === 'follow' && locationURL !== null) {
+          // HTTP-redirect fetch step 5
+          if (request.counter >= request.follow) {
+            reject(new FetchError(`maximum redirect reached at: ${
+              request.url}`, 'max-redirect'))
+            finalize()
+            return
+          }
 
-const configureOptions = __nccwpck_require__(99824)
-const fetch = __nccwpck_require__(67242)
+          // HTTP-redirect fetch step 9
+          if (res.statusCode !== 303 &&
+              request.body &&
+              getTotalBytes(request) === null) {
+            reject(new FetchError(
+              'Cannot follow redirect with body being a readable stream',
+              'unsupported-redirect'
+            ))
+            finalize()
+            return
+          }
 
-const makeFetchHappen = (url, opts) => {
-  const options = configureOptions(opts)
+          // Update host due to redirection
+          request.headers.set('host', (new URL(locationURL)).host)
 
-  const request = new Request(url, options)
-  return fetch(request, options)
-}
+          // HTTP-redirect fetch step 6 (counter increment)
+          // Create a new Request object.
+          const requestOpts = {
+            headers: new Headers(request.headers),
+            follow: request.follow,
+            counter: request.counter + 1,
+            agent: request.agent,
+            compress: request.compress,
+            method: request.method,
+            body: request.body,
+            signal: request.signal,
+            timeout: request.timeout,
+          }
 
-makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => {
-  if (typeof defaultUrl === 'object') {
-    defaultOptions = defaultUrl
-    defaultUrl = null
-  }
+          // if the redirect is to a new hostname, strip the authorization and cookie headers
+          const parsedOriginal = new URL(request.url)
+          const parsedRedirect = new URL(locationURL)
+          if (parsedOriginal.hostname !== parsedRedirect.hostname) {
+            requestOpts.headers.delete('authorization')
+            requestOpts.headers.delete('cookie')
+          }
 
-  const defaultedFetch = (url, options = {}) => {
-    const finalUrl = url || defaultUrl
-    const finalOptions = {
-      ...defaultOptions,
-      ...options,
-      headers: {
-        ...defaultOptions.headers,
-        ...options.headers,
-      },
-    }
-    return wrappedFetch(finalUrl, finalOptions)
-  }
+          // HTTP-redirect fetch step 11
+          if (res.statusCode === 303 || (
+            (res.statusCode === 301 || res.statusCode === 302) &&
+              request.method === 'POST'
+          )) {
+            requestOpts.method = 'GET'
+            requestOpts.body = undefined
+            requestOpts.headers.delete('content-length')
+          }
 
-  defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) =>
-    makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch)
-  return defaultedFetch
-}
+          // HTTP-redirect fetch step 15
+          resolve(fetch(new Request(locationURL, requestOpts)))
+          finalize()
+          return
+        }
+      } // end if(isRedirect)
 
-module.exports = makeFetchHappen
-module.exports.FetchError = FetchError
-module.exports.Headers = Headers
-module.exports.Request = Request
-module.exports.Response = Response
+      // prepare response
+      res.once('end', () =>
+        signal && signal.removeEventListener('abort', abortAndFinalize))
 
+      const body = new Minipass()
+      // if an error occurs, either on the response stream itself, on one of the
+      // decoder streams, or a response length timeout from the Body class, we
+      // forward the error through to our internal body stream. If we see an
+      // error event on that, we call finalize to abort the request and ensure
+      // we don't leave a socket believing a request is in flight.
+      // this is difficult to test, so lacks specific coverage.
+      body.on('error', finalize)
+      // exceedingly rare that the stream would have an error,
+      // but just in case we proxy it to the stream in use.
+      res.on('error', /* istanbul ignore next */ er => body.emit('error', er))
+      res.on('data', (chunk) => body.write(chunk))
+      res.on('end', () => body.end())
 
-/***/ }),
+      const responseOptions = {
+        url: request.url,
+        status: res.statusCode,
+        statusText: res.statusMessage,
+        headers: headers,
+        size: request.size,
+        timeout: request.timeout,
+        counter: request.counter,
+        trailer: new Promise(resolveTrailer =>
+          res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))),
+      }
 
-/***/ 99824:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+      // HTTP-network fetch step 12.1.1.3
+      const codings = headers.get('Content-Encoding')
 
-const dns = __nccwpck_require__(72250)
+      // HTTP-network fetch step 12.1.1.4: handle content codings
 
-const conditionalHeaders = [
-  'if-modified-since',
-  'if-none-match',
-  'if-unmodified-since',
-  'if-match',
-  'if-range',
-]
+      // in following scenarios we ignore compression support
+      // 1. compression support is disabled
+      // 2. HEAD request
+      // 3. no Content-Encoding header
+      // 4. no content response (204)
+      // 5. content not modified response (304)
+      if (!request.compress ||
+          request.method === 'HEAD' ||
+          codings === null ||
+          res.statusCode === 204 ||
+          res.statusCode === 304) {
+        response = new Response(body, responseOptions)
+        resolve(response)
+        return
+      }
 
-const configureOptions = (opts) => {
-  const { strictSSL, ...options } = { ...opts }
-  options.method = options.method ? options.method.toUpperCase() : 'GET'
+      // Be less strict when decoding compressed responses, since sometimes
+      // servers send slightly invalid responses that are still accepted
+      // by common browsers.
+      // Always using Z_SYNC_FLUSH is what cURL does.
+      const zlibOptions = {
+        flush: zlib.constants.Z_SYNC_FLUSH,
+        finishFlush: zlib.constants.Z_SYNC_FLUSH,
+      }
 
-  if (strictSSL === undefined || strictSSL === null) {
-    options.rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'
-  } else {
-    options.rejectUnauthorized = strictSSL !== false
-  }
+      // for gzip
+      if (codings === 'gzip' || codings === 'x-gzip') {
+        const unzip = new zlib.Gunzip(zlibOptions)
+        response = new Response(
+          // exceedingly rare that the stream would have an error,
+          // but just in case we proxy it to the stream in use.
+          body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip),
+          responseOptions
+        )
+        resolve(response)
+        return
+      }
 
-  if (!options.retry) {
-    options.retry = { retries: 0 }
-  } else if (typeof options.retry === 'string') {
-    const retries = parseInt(options.retry, 10)
-    if (isFinite(retries)) {
-      options.retry = { retries }
-    } else {
-      options.retry = { retries: 0 }
-    }
-  } else if (typeof options.retry === 'number') {
-    options.retry = { retries: options.retry }
-  } else {
-    options.retry = { retries: 0, ...options.retry }
-  }
+      // for deflate
+      if (codings === 'deflate' || codings === 'x-deflate') {
+        // handle the infamous raw deflate response from old servers
+        // a hack for old IIS and Apache servers
+        const raw = res.pipe(new Minipass())
+        raw.once('data', chunk => {
+          // see http://stackoverflow.com/questions/37519828
+          const decoder = (chunk[0] & 0x0F) === 0x08
+            ? new zlib.Inflate()
+            : new zlib.InflateRaw()
+          // exceedingly rare that the stream would have an error,
+          // but just in case we proxy it to the stream in use.
+          body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
+          response = new Response(decoder, responseOptions)
+          resolve(response)
+        })
+        return
+      }
 
-  options.dns = { ttl: 5 * 60 * 1000, lookup: dns.lookup, ...options.dns }
+      // for br
+      if (codings === 'br') {
+        // ignoring coverage so tests don't have to fake support (or lack of) for brotli
+        // istanbul ignore next
+        try {
+          var decoder = new zlib.BrotliDecompress()
+        } catch (err) {
+          reject(err)
+          finalize()
+          return
+        }
+        // exceedingly rare that the stream would have an error,
+        // but just in case we proxy it to the stream in use.
+        body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
+        response = new Response(decoder, responseOptions)
+        resolve(response)
+        return
+      }
 
-  options.cache = options.cache || 'default'
-  if (options.cache === 'default') {
-    const hasConditionalHeader = Object.keys(options.headers || {}).some((name) => {
-      return conditionalHeaders.includes(name.toLowerCase())
+      // otherwise, use response as-is
+      response = new Response(body, responseOptions)
+      resolve(response)
     })
-    if (hasConditionalHeader) {
-      options.cache = 'no-store'
-    }
-  }
 
-  options.cacheAdditionalHeaders = options.cacheAdditionalHeaders || []
+    writeToStream(req, request)
+  })
+}
 
-  // cacheManager is deprecated, but if it's set and
-  // cachePath is not we should copy it to the new field
-  if (options.cacheManager && !options.cachePath) {
-    options.cachePath = options.cacheManager
-  }
+module.exports = fetch
 
-  return options
-}
+fetch.isRedirect = code =>
+  code === 301 ||
+  code === 302 ||
+  code === 303 ||
+  code === 307 ||
+  code === 308
 
-module.exports = configureOptions
+fetch.Headers = Headers
+fetch.Request = Request
+fetch.Response = Response
+fetch.FetchError = FetchError
+fetch.AbortError = AbortError
 
 
 /***/ }),
 
-/***/ 22314:
+/***/ 99586:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
+const { URL } = __nccwpck_require__(87016)
+const { Minipass } = __nccwpck_require__(78275)
+const Headers = __nccwpck_require__(98645)
+const { exportNodeCompatibleHeaders } = Headers
+const Body = __nccwpck_require__(28515)
+const { clone, extractContentType, getTotalBytes } = Body
 
-const MinipassPipeline = __nccwpck_require__(52899)
+const version = (__nccwpck_require__(27573)/* .version */ .rE)
+const defaultUserAgent =
+  `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)`
 
-class CachingMinipassPipeline extends MinipassPipeline {
-  #events = []
-  #data = new Map()
+const INTERNALS = Symbol('Request internals')
 
-  constructor (opts, ...streams) {
-    // CRITICAL: do NOT pass the streams to the call to super(), this will start
-    // the flow of data and potentially cause the events we need to catch to emit
-    // before we've finished our own setup. instead we call super() with no args,
-    // finish our setup, and then push the streams into ourselves to start the
-    // data flow
-    super()
-    this.#events = opts.events
+const isRequest = input =>
+  typeof input === 'object' && typeof input[INTERNALS] === 'object'
 
-    /* istanbul ignore next - coverage disabled because this is pointless to test here */
-    if (streams.length) {
-      this.push(...streams)
-    }
-  }
+const isAbortSignal = signal => {
+  const proto = (
+    signal
+    && typeof signal === 'object'
+    && Object.getPrototypeOf(signal)
+  )
+  return !!(proto && proto.constructor.name === 'AbortSignal')
+}
 
-  on (event, handler) {
-    if (this.#events.includes(event) && this.#data.has(event)) {
-      return handler(...this.#data.get(event))
+class Request extends Body {
+  constructor (input, init = {}) {
+    const parsedURL = isRequest(input) ? new URL(input.url)
+      : input && input.href ? new URL(input.href)
+      : new URL(`${input}`)
+
+    if (isRequest(input)) {
+      init = { ...input[INTERNALS], ...init }
+    } else if (!input || typeof input === 'string') {
+      input = {}
     }
 
-    return super.on(event, handler)
-  }
+    const method = (init.method || input.method || 'GET').toUpperCase()
+    const isGETHEAD = method === 'GET' || method === 'HEAD'
 
-  emit (event, ...data) {
-    if (this.#events.includes(event)) {
-      this.#data.set(event, data)
+    if ((init.body !== null && init.body !== undefined ||
+        isRequest(input) && input.body !== null) && isGETHEAD) {
+      throw new TypeError('Request with GET/HEAD method cannot have body')
     }
 
-    return super.emit(event, ...data)
-  }
-}
-
-module.exports = CachingMinipassPipeline
+    const inputBody = init.body !== null && init.body !== undefined ? init.body
+      : isRequest(input) && input.body !== null ? clone(input)
+      : null
 
+    super(inputBody, {
+      timeout: init.timeout || input.timeout || 0,
+      size: init.size || input.size || 0,
+    })
 
-/***/ }),
+    const headers = new Headers(init.headers || input.headers || {})
 
-/***/ 20766:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    if (inputBody !== null && inputBody !== undefined &&
+        !headers.has('Content-Type')) {
+      const contentType = extractContentType(inputBody)
+      if (contentType) {
+        headers.append('Content-Type', contentType)
+      }
+    }
 
-const { Minipass } = __nccwpck_require__(78275)
-const fetch = __nccwpck_require__(88483)
-const promiseRetry = __nccwpck_require__(90390)
-const ssri = __nccwpck_require__(68951)
-const { log } = __nccwpck_require__(26687)
+    const signal = 'signal' in init ? init.signal
+      : null
 
-const CachingMinipassPipeline = __nccwpck_require__(22314)
-const { getAgent } = __nccwpck_require__(57995)
-const pkg = __nccwpck_require__(96734)
+    if (signal !== null && signal !== undefined && !isAbortSignal(signal)) {
+      throw new TypeError('Expected signal must be an instanceof AbortSignal')
+    }
 
-const USER_AGENT = `${pkg.name}/${pkg.version} (+https://npm.im/${pkg.name})`
+    // TLS specific options that are handled by node
+    const {
+      ca,
+      cert,
+      ciphers,
+      clientCertEngine,
+      crl,
+      dhparam,
+      ecdhCurve,
+      family,
+      honorCipherOrder,
+      key,
+      passphrase,
+      pfx,
+      rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0',
+      secureOptions,
+      secureProtocol,
+      servername,
+      sessionIdContext,
+    } = init
 
-const RETRY_ERRORS = [
-  'ECONNRESET', // remote socket closed on us
-  'ECONNREFUSED', // remote host refused to open connection
-  'EADDRINUSE', // failed to bind to a local port (proxy?)
-  'ETIMEDOUT', // someone in the transaction is WAY TOO SLOW
-  // from @npmcli/agent
-  'ECONNECTIONTIMEOUT',
-  'EIDLETIMEOUT',
-  'ERESPONSETIMEOUT',
-  'ETRANSFERTIMEOUT',
-  // Known codes we do NOT retry on:
-  // ENOTFOUND (getaddrinfo failure. Either bad hostname, or offline)
-  // EINVALIDPROXY // invalid protocol from @npmcli/agent
-  // EINVALIDRESPONSE // invalid status code from @npmcli/agent
-]
+    this[INTERNALS] = {
+      method,
+      redirect: init.redirect || input.redirect || 'follow',
+      headers,
+      parsedURL,
+      signal,
+      ca,
+      cert,
+      ciphers,
+      clientCertEngine,
+      crl,
+      dhparam,
+      ecdhCurve,
+      family,
+      honorCipherOrder,
+      key,
+      passphrase,
+      pfx,
+      rejectUnauthorized,
+      secureOptions,
+      secureProtocol,
+      servername,
+      sessionIdContext,
+    }
 
-const RETRY_TYPES = [
-  'request-timeout',
-]
+    // node-fetch-only options
+    this.follow = init.follow !== undefined ? init.follow
+      : input.follow !== undefined ? input.follow
+      : 20
+    this.compress = init.compress !== undefined ? init.compress
+      : input.compress !== undefined ? input.compress
+      : true
+    this.counter = init.counter || input.counter || 0
+    this.agent = init.agent || input.agent
+  }
 
-// make a request directly to the remote source,
-// retrying certain classes of errors as well as
-// following redirects (through the cache if necessary)
-// and verifying response integrity
-const remoteFetch = (request, options) => {
-  // options.signal is intended for the fetch itself, not the agent.  Attaching it to the agent will re-use that signal across multiple requests, which prevents any connections beyond the first one.
-  const agent = getAgent(request.url, { ...options, signal: undefined })
-  if (!request.headers.has('connection')) {
-    request.headers.set('connection', agent ? 'keep-alive' : 'close')
+  get method () {
+    return this[INTERNALS].method
   }
 
-  if (!request.headers.has('user-agent')) {
-    request.headers.set('user-agent', USER_AGENT)
+  get url () {
+    return this[INTERNALS].parsedURL.toString()
   }
 
-  // keep our own options since we're overriding the agent
-  // and the redirect mode
-  const _opts = {
-    ...options,
-    agent,
-    redirect: 'manual',
+  get headers () {
+    return this[INTERNALS].headers
   }
 
-  return promiseRetry(async (retryHandler, attemptNum) => {
-    const req = new fetch.Request(request, _opts)
-    try {
-      let res = await fetch(req, _opts)
-      if (_opts.integrity && res.status === 200) {
-        // we got a 200 response and the user has specified an expected
-        // integrity value, so wrap the response in an ssri stream to verify it
-        const integrityStream = ssri.integrityStream({
-          algorithms: _opts.algorithms,
-          integrity: _opts.integrity,
-          size: _opts.size,
-        })
-        const pipeline = new CachingMinipassPipeline({
-          events: ['integrity', 'size'],
-        }, res.body, integrityStream)
-        // we also propagate the integrity and size events out to the pipeline so we can use
-        // this new response body as an integrityEmitter for cacache
-        integrityStream.on('integrity', i => pipeline.emit('integrity', i))
-        integrityStream.on('size', s => pipeline.emit('size', s))
-        res = new fetch.Response(pipeline, res)
-        // set an explicit flag so we know if our response body will emit integrity and size
-        res.body.hasIntegrityEmitter = true
-      }
+  get redirect () {
+    return this[INTERNALS].redirect
+  }
 
-      res.headers.set('x-fetch-attempts', attemptNum)
+  get signal () {
+    return this[INTERNALS].signal
+  }
 
-      // do not retry POST requests, or requests with a streaming body
-      // do retry requests with a 408, 420, 429 or 500+ status in the response
-      const isStream = Minipass.isStream(req.body)
-      const isRetriable = req.method !== 'POST' &&
-          !isStream &&
-          ([408, 420, 429].includes(res.status) || res.status >= 500)
+  clone () {
+    return new Request(this)
+  }
 
-      if (isRetriable) {
-        if (typeof options.onRetry === 'function') {
-          options.onRetry(res)
-        }
+  get [Symbol.toStringTag] () {
+    return 'Request'
+  }
 
-        /* eslint-disable-next-line max-len */
-        log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${res.status}`)
-        return retryHandler(res)
-      }
+  static getNodeRequestOptions (request) {
+    const parsedURL = request[INTERNALS].parsedURL
+    const headers = new Headers(request[INTERNALS].headers)
 
-      return res
-    } catch (err) {
-      const code = (err.code === 'EPROMISERETRY')
-        ? err.retried.code
-        : err.code
+    // fetch step 1.3
+    if (!headers.has('Accept')) {
+      headers.set('Accept', '*/*')
+    }
 
-      // err.retried will be the thing that was thrown from above
-      // if it's a response, we just got a bad status code and we
-      // can re-throw to allow the retry
-      const isRetryError = err.retried instanceof fetch.Response ||
-        (RETRY_ERRORS.includes(code) && RETRY_TYPES.includes(err.type))
+    // Basic fetch
+    if (!/^https?:$/.test(parsedURL.protocol)) {
+      throw new TypeError('Only HTTP(S) protocols are supported')
+    }
 
-      if (req.method === 'POST' || isRetryError) {
-        throw err
-      }
+    if (request.signal &&
+        Minipass.isStream(request.body) &&
+        typeof request.body.destroy !== 'function') {
+      throw new Error(
+        'Cancellation of streamed requests with AbortSignal is not supported')
+    }
 
-      if (typeof options.onRetry === 'function') {
-        options.onRetry(err)
-      }
+    // HTTP-network-or-cache fetch steps 2.4-2.7
+    const contentLengthValue =
+      (request.body === null || request.body === undefined) &&
+        /^(POST|PUT)$/i.test(request.method) ? '0'
+      : request.body !== null && request.body !== undefined
+        ? getTotalBytes(request)
+        : null
 
-      log.http('fetch', `${req.method} ${req.url} attempt ${attemptNum} failed with ${err.code}`)
-      return retryHandler(err)
-    }
-  }, options.retry).catch((err) => {
-    // don't reject for http errors, just return them
-    if (err.status >= 400 && err.type !== 'system') {
-      return err
+    if (contentLengthValue) {
+      headers.set('Content-Length', contentLengthValue + '')
     }
 
-    throw err
-  })
-}
-
-module.exports = remoteFetch
+    // HTTP-network-or-cache fetch step 2.11
+    if (!headers.has('User-Agent')) {
+      headers.set('User-Agent', defaultUserAgent)
+    }
 
+    // HTTP-network-or-cache fetch step 2.15
+    if (request.compress && !headers.has('Accept-Encoding')) {
+      headers.set('Accept-Encoding', 'gzip,deflate')
+    }
 
-/***/ }),
+    const agent = typeof request.agent === 'function'
+      ? request.agent(parsedURL)
+      : request.agent
 
-/***/ 43772:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    if (!headers.has('Connection') && !agent) {
+      headers.set('Connection', 'close')
+    }
 
-module.exports = minimatch
-minimatch.Minimatch = Minimatch
+    // TLS specific options that are handled by node
+    const {
+      ca,
+      cert,
+      ciphers,
+      clientCertEngine,
+      crl,
+      dhparam,
+      ecdhCurve,
+      family,
+      honorCipherOrder,
+      key,
+      passphrase,
+      pfx,
+      rejectUnauthorized,
+      secureOptions,
+      secureProtocol,
+      servername,
+      sessionIdContext,
+    } = request[INTERNALS]
 
-var path = (function () { try { return __nccwpck_require__(16928) } catch (e) {}}()) || {
-  sep: '/'
-}
-minimatch.sep = path.sep
+    // HTTP-network fetch step 4.2
+    // chunked encoding is handled by Node.js
 
-var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
-var expand = __nccwpck_require__(94691)
+    // we cannot spread parsedURL directly, so we have to read each property one-by-one
+    // and map them to the equivalent https?.request() method options
+    const urlProps = {
+      auth: parsedURL.username || parsedURL.password
+        ? `${parsedURL.username}:${parsedURL.password}`
+        : '',
+      host: parsedURL.host,
+      hostname: parsedURL.hostname,
+      path: `${parsedURL.pathname}${parsedURL.search}`,
+      port: parsedURL.port,
+      protocol: parsedURL.protocol,
+    }
 
-var plTypes = {
-  '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
-  '?': { open: '(?:', close: ')?' },
-  '+': { open: '(?:', close: ')+' },
-  '*': { open: '(?:', close: ')*' },
-  '@': { open: '(?:', close: ')' }
+    return {
+      ...urlProps,
+      method: request.method,
+      headers: exportNodeCompatibleHeaders(headers),
+      agent,
+      ca,
+      cert,
+      ciphers,
+      clientCertEngine,
+      crl,
+      dhparam,
+      ecdhCurve,
+      family,
+      honorCipherOrder,
+      key,
+      passphrase,
+      pfx,
+      rejectUnauthorized,
+      secureOptions,
+      secureProtocol,
+      servername,
+      sessionIdContext,
+      timeout: request.timeout,
+    }
+  }
 }
 
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-var qmark = '[^/]'
+module.exports = Request
 
-// * => any number of characters
-var star = qmark + '*?'
+Object.defineProperties(Request.prototype, {
+  method: { enumerable: true },
+  url: { enumerable: true },
+  headers: { enumerable: true },
+  redirect: { enumerable: true },
+  clone: { enumerable: true },
+  signal: { enumerable: true },
+})
 
-// ** when dots are allowed.  Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
 
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
+/***/ }),
 
-// characters that need to be escaped in RegExp.
-var reSpecials = charSet('().*{}+?[]^$\\!')
+/***/ 43852:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-// "abc" -> { a:true, b:true, c:true }
-function charSet (s) {
-  return s.split('').reduce(function (set, c) {
-    set[c] = true
-    return set
-  }, {})
-}
+"use strict";
 
-// normalizes slashes.
-var slashSplit = /\/+/
+const http = __nccwpck_require__(58611)
+const { STATUS_CODES } = http
 
-minimatch.filter = filter
-function filter (pattern, options) {
-  options = options || {}
-  return function (p, i, list) {
-    return minimatch(p, pattern, options)
-  }
-}
+const Headers = __nccwpck_require__(98645)
+const Body = __nccwpck_require__(28515)
+const { clone, extractContentType } = Body
 
-function ext (a, b) {
-  b = b || {}
-  var t = {}
-  Object.keys(a).forEach(function (k) {
-    t[k] = a[k]
-  })
-  Object.keys(b).forEach(function (k) {
-    t[k] = b[k]
-  })
-  return t
-}
+const INTERNALS = Symbol('Response internals')
 
-minimatch.defaults = function (def) {
-  if (!def || typeof def !== 'object' || !Object.keys(def).length) {
-    return minimatch
-  }
+class Response extends Body {
+  constructor (body = null, opts = {}) {
+    super(body, opts)
 
-  var orig = minimatch
+    const status = opts.status || 200
+    const headers = new Headers(opts.headers)
 
-  var m = function minimatch (p, pattern, options) {
-    return orig(p, pattern, ext(def, options))
-  }
+    if (body !== null && body !== undefined && !headers.has('Content-Type')) {
+      const contentType = extractContentType(body)
+      if (contentType) {
+        headers.append('Content-Type', contentType)
+      }
+    }
 
-  m.Minimatch = function Minimatch (pattern, options) {
-    return new orig.Minimatch(pattern, ext(def, options))
-  }
-  m.Minimatch.defaults = function defaults (options) {
-    return orig.defaults(ext(def, options)).Minimatch
+    this[INTERNALS] = {
+      url: opts.url,
+      status,
+      statusText: opts.statusText || STATUS_CODES[status],
+      headers,
+      counter: opts.counter,
+      trailer: Promise.resolve(opts.trailer || new Headers()),
+    }
   }
 
-  m.filter = function filter (pattern, options) {
-    return orig.filter(pattern, ext(def, options))
+  get trailer () {
+    return this[INTERNALS].trailer
   }
 
-  m.defaults = function defaults (options) {
-    return orig.defaults(ext(def, options))
+  get url () {
+    return this[INTERNALS].url || ''
   }
 
-  m.makeRe = function makeRe (pattern, options) {
-    return orig.makeRe(pattern, ext(def, options))
+  get status () {
+    return this[INTERNALS].status
   }
 
-  m.braceExpand = function braceExpand (pattern, options) {
-    return orig.braceExpand(pattern, ext(def, options))
+  get ok () {
+    return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
   }
 
-  m.match = function (list, pattern, options) {
-    return orig.match(list, pattern, ext(def, options))
+  get redirected () {
+    return this[INTERNALS].counter > 0
   }
 
-  return m
-}
-
-Minimatch.defaults = function (def) {
-  return minimatch.defaults(def).Minimatch
-}
-
-function minimatch (p, pattern, options) {
-  assertValidPattern(pattern)
-
-  if (!options) options = {}
+  get statusText () {
+    return this[INTERNALS].statusText
+  }
 
-  // shortcut: comments match nothing.
-  if (!options.nocomment && pattern.charAt(0) === '#') {
-    return false
+  get headers () {
+    return this[INTERNALS].headers
   }
 
-  return new Minimatch(pattern, options).match(p)
-}
+  clone () {
+    return new Response(clone(this), {
+      url: this.url,
+      status: this.status,
+      statusText: this.statusText,
+      headers: this.headers,
+      ok: this.ok,
+      redirected: this.redirected,
+      trailer: this.trailer,
+    })
+  }
 
-function Minimatch (pattern, options) {
-  if (!(this instanceof Minimatch)) {
-    return new Minimatch(pattern, options)
+  get [Symbol.toStringTag] () {
+    return 'Response'
   }
+}
 
-  assertValidPattern(pattern)
+module.exports = Response
 
-  if (!options) options = {}
+Object.defineProperties(Response.prototype, {
+  url: { enumerable: true },
+  status: { enumerable: true },
+  ok: { enumerable: true },
+  redirected: { enumerable: true },
+  statusText: { enumerable: true },
+  headers: { enumerable: true },
+  clone: { enumerable: true },
+})
 
-  pattern = pattern.trim()
 
-  // windows support: need to use /, not \
-  if (!options.allowWindowsEscape && path.sep !== '/') {
-    pattern = pattern.split(path.sep).join('/')
-  }
+/***/ }),
 
-  this.options = options
-  this.set = []
-  this.pattern = pattern
-  this.regexp = null
-  this.negate = false
-  this.comment = false
-  this.empty = false
-  this.partial = !!options.partial
+/***/ 37633:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  // make the set of regexps etc.
-  this.make()
-}
+const Minipass = __nccwpck_require__(64387)
+const _flush = Symbol('_flush')
+const _flushed = Symbol('_flushed')
+const _flushing = Symbol('_flushing')
+class Flush extends Minipass {
+  constructor (opt = {}) {
+    if (typeof opt === 'function')
+      opt = { flush: opt }
 
-Minimatch.prototype.debug = function () {}
+    super(opt)
 
-Minimatch.prototype.make = make
-function make () {
-  var pattern = this.pattern
-  var options = this.options
+    // or extend this class and provide a 'flush' method in your subclass
+    if (typeof opt.flush !== 'function' && typeof this.flush !== 'function')
+      throw new TypeError('must provide flush function in options')
 
-  // empty patterns and comments match nothing.
-  if (!options.nocomment && pattern.charAt(0) === '#') {
-    this.comment = true
-    return
-  }
-  if (!pattern) {
-    this.empty = true
-    return
+    this[_flush] = opt.flush || this.flush
   }
 
-  // step 1: figure out negation, etc.
-  this.parseNegate()
+  emit (ev, ...data) {
+    if ((ev !== 'end' && ev !== 'finish') || this[_flushed])
+      return super.emit(ev, ...data)
 
-  // step 2: expand braces
-  var set = this.globSet = this.braceExpand()
+    if (this[_flushing])
+      return
 
-  if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
+    this[_flushing] = true
 
-  this.debug(this.pattern, set)
+    const afterFlush = er => {
+      this[_flushed] = true
+      er ? super.emit('error', er) : super.emit('end')
+    }
 
-  // step 3: now we have a set, so turn each one into a series of path-portion
-  // matching patterns.
-  // These will be regexps, except in the case of "**", which is
-  // set to the GLOBSTAR object for globstar behavior,
-  // and will not contain any / characters
-  set = this.globParts = set.map(function (s) {
-    return s.split(slashSplit)
-  })
+    const ret = this[_flush](afterFlush)
+    if (ret && ret.then)
+      ret.then(() => afterFlush(), er => afterFlush(er))
+  }
+}
 
-  this.debug(this.pattern, set)
+module.exports = Flush
 
-  // glob --> regexps
-  set = set.map(function (s, si, set) {
-    return s.map(this.parse, this)
-  }, this)
 
-  this.debug(this.pattern, set)
+/***/ }),
 
-  // filter out everything that didn't compile properly.
-  set = set.filter(function (s) {
-    return s.indexOf(false) === -1
-  })
+/***/ 64387:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  this.debug(this.pattern, set)
+"use strict";
 
-  this.set = set
+const proc = typeof process === 'object' && process ? process : {
+  stdout: null,
+  stderr: null,
 }
+const EE = __nccwpck_require__(24434)
+const Stream = __nccwpck_require__(2203)
+const SD = (__nccwpck_require__(13193).StringDecoder)
 
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
-  var pattern = this.pattern
-  var negate = false
-  var options = this.options
-  var negateOffset = 0
+const EOF = Symbol('EOF')
+const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
+const EMITTED_END = Symbol('emittedEnd')
+const EMITTING_END = Symbol('emittingEnd')
+const EMITTED_ERROR = Symbol('emittedError')
+const CLOSED = Symbol('closed')
+const READ = Symbol('read')
+const FLUSH = Symbol('flush')
+const FLUSHCHUNK = Symbol('flushChunk')
+const ENCODING = Symbol('encoding')
+const DECODER = Symbol('decoder')
+const FLOWING = Symbol('flowing')
+const PAUSED = Symbol('paused')
+const RESUME = Symbol('resume')
+const BUFFERLENGTH = Symbol('bufferLength')
+const BUFFERPUSH = Symbol('bufferPush')
+const BUFFERSHIFT = Symbol('bufferShift')
+const OBJECTMODE = Symbol('objectMode')
+const DESTROYED = Symbol('destroyed')
+const EMITDATA = Symbol('emitData')
+const EMITEND = Symbol('emitEnd')
+const EMITEND2 = Symbol('emitEnd2')
+const ASYNC = Symbol('async')
 
-  if (options.nonegate) return
+const defer = fn => Promise.resolve().then(fn)
 
-  for (var i = 0, l = pattern.length
-    ; i < l && pattern.charAt(i) === '!'
-    ; i++) {
-    negate = !negate
-    negateOffset++
-  }
+// TODO remove when Node v8 support drops
+const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
+const ASYNCITERATOR = doIter && Symbol.asyncIterator
+  || Symbol('asyncIterator not implemented')
+const ITERATOR = doIter && Symbol.iterator
+  || Symbol('iterator not implemented')
 
-  if (negateOffset) this.pattern = pattern.substr(negateOffset)
-  this.negate = negate
-}
+// events that mean 'the stream is over'
+// these are treated specially, and re-emitted
+// if they are listened for after emitting.
+const isEndish = ev =>
+  ev === 'end' ||
+  ev === 'finish' ||
+  ev === 'prefinish'
 
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
-  return braceExpand(pattern, options)
-}
+const isArrayBuffer = b => b instanceof ArrayBuffer ||
+  typeof b === 'object' &&
+  b.constructor &&
+  b.constructor.name === 'ArrayBuffer' &&
+  b.byteLength >= 0
 
-Minimatch.prototype.braceExpand = braceExpand
+const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
 
-function braceExpand (pattern, options) {
-  if (!options) {
-    if (this instanceof Minimatch) {
-      options = this.options
-    } else {
-      options = {}
-    }
+class Pipe {
+  constructor (src, dest, opts) {
+    this.src = src
+    this.dest = dest
+    this.opts = opts
+    this.ondrain = () => src[RESUME]()
+    dest.on('drain', this.ondrain)
   }
-
-  pattern = typeof pattern === 'undefined'
-    ? this.pattern : pattern
-
-  assertValidPattern(pattern)
-
-  // Thanks to Yeting Li  for
-  // improving this regexp to avoid a ReDOS vulnerability.
-  if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
-    // shortcut. no need to expand.
-    return [pattern]
+  unpipe () {
+    this.dest.removeListener('drain', this.ondrain)
+  }
+  // istanbul ignore next - only here for the prototype
+  proxyErrors () {}
+  end () {
+    this.unpipe()
+    if (this.opts.end)
+      this.dest.end()
   }
-
-  return expand(pattern)
 }
 
-var MAX_PATTERN_LENGTH = 1024 * 64
-var assertValidPattern = function (pattern) {
-  if (typeof pattern !== 'string') {
-    throw new TypeError('invalid pattern')
+class PipeProxyErrors extends Pipe {
+  unpipe () {
+    this.src.removeListener('error', this.proxyErrors)
+    super.unpipe()
   }
-
-  if (pattern.length > MAX_PATTERN_LENGTH) {
-    throw new TypeError('pattern is too long')
+  constructor (src, dest, opts) {
+    super(src, dest, opts)
+    this.proxyErrors = er => dest.emit('error', er)
+    src.on('error', this.proxyErrors)
   }
 }
 
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion.  Otherwise, any series
-// of * is equivalent to a single *.  Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
-  assertValidPattern(pattern)
-
-  var options = this.options
-
-  // shortcuts
-  if (pattern === '**') {
-    if (!options.noglobstar)
-      return GLOBSTAR
+module.exports = class Minipass extends Stream {
+  constructor (options) {
+    super()
+    this[FLOWING] = false
+    // whether we're explicitly paused
+    this[PAUSED] = false
+    this.pipes = []
+    this.buffer = []
+    this[OBJECTMODE] = options && options.objectMode || false
+    if (this[OBJECTMODE])
+      this[ENCODING] = null
     else
-      pattern = '*'
+      this[ENCODING] = options && options.encoding || null
+    if (this[ENCODING] === 'buffer')
+      this[ENCODING] = null
+    this[ASYNC] = options && !!options.async || false
+    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
+    this[EOF] = false
+    this[EMITTED_END] = false
+    this[EMITTING_END] = false
+    this[CLOSED] = false
+    this[EMITTED_ERROR] = null
+    this.writable = true
+    this.readable = true
+    this[BUFFERLENGTH] = 0
+    this[DESTROYED] = false
   }
-  if (pattern === '') return ''
 
-  var re = ''
-  var hasMagic = !!options.nocase
-  var escaping = false
-  // ? => one single character
-  var patternListStack = []
-  var negativeLists = []
-  var stateChar
-  var inClass = false
-  var reClassStart = -1
-  var classStart = -1
-  // . and .. never match anything that doesn't start with .,
-  // even when options.dot is set.
-  var patternStart = pattern.charAt(0) === '.' ? '' // anything
-  // not (start or / followed by . or .. followed by / or end)
-  : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
-  : '(?!\\.)'
-  var self = this
+  get bufferLength () { return this[BUFFERLENGTH] }
 
-  function clearStateChar () {
-    if (stateChar) {
-      // we had some state-tracking character
-      // that wasn't consumed by this pass.
-      switch (stateChar) {
-        case '*':
-          re += star
-          hasMagic = true
-        break
-        case '?':
-          re += qmark
-          hasMagic = true
-        break
-        default:
-          re += '\\' + stateChar
-        break
-      }
-      self.debug('clearStateChar %j %j', stateChar, re)
-      stateChar = false
-    }
-  }
+  get encoding () { return this[ENCODING] }
+  set encoding (enc) {
+    if (this[OBJECTMODE])
+      throw new Error('cannot set encoding in objectMode')
 
-  for (var i = 0, len = pattern.length, c
-    ; (i < len) && (c = pattern.charAt(i))
-    ; i++) {
-    this.debug('%s\t%s %s %j', pattern, i, re, c)
+    if (this[ENCODING] && enc !== this[ENCODING] &&
+        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
+      throw new Error('cannot change encoding')
 
-    // skip over any that are escaped.
-    if (escaping && reSpecials[c]) {
-      re += '\\' + c
-      escaping = false
-      continue
+    if (this[ENCODING] !== enc) {
+      this[DECODER] = enc ? new SD(enc) : null
+      if (this.buffer.length)
+        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
     }
 
-    switch (c) {
-      /* istanbul ignore next */
-      case '/': {
-        // completely not allowed, even escaped.
-        // Should already be path-split by now.
-        return false
-      }
+    this[ENCODING] = enc
+  }
 
-      case '\\':
-        clearStateChar()
-        escaping = true
-      continue
+  setEncoding (enc) {
+    this.encoding = enc
+  }
 
-      // the various stateChar values
-      // for the "extglob" stuff.
-      case '?':
-      case '*':
-      case '+':
-      case '@':
-      case '!':
-        this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
+  get objectMode () { return this[OBJECTMODE] }
+  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
 
-        // all of those are literals inside a class, except that
-        // the glob [!a] means [^a] in regexp
-        if (inClass) {
-          this.debug('  in class')
-          if (c === '!' && i === classStart + 1) c = '^'
-          re += c
-          continue
-        }
+  get ['async'] () { return this[ASYNC] }
+  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }
 
-        // if we already have a stateChar, then it means
-        // that there was something like ** or +? in there.
-        // Handle the stateChar, then proceed with this one.
-        self.debug('call clearStateChar %j', stateChar)
-        clearStateChar()
-        stateChar = c
-        // if extglob is disabled, then +(asdf|foo) isn't a thing.
-        // just clear the statechar *now*, rather than even diving into
-        // the patternList stuff.
-        if (options.noext) clearStateChar()
-      continue
+  write (chunk, encoding, cb) {
+    if (this[EOF])
+      throw new Error('write after end')
 
-      case '(':
-        if (inClass) {
-          re += '('
-          continue
-        }
+    if (this[DESTROYED]) {
+      this.emit('error', Object.assign(
+        new Error('Cannot call write after a stream was destroyed'),
+        { code: 'ERR_STREAM_DESTROYED' }
+      ))
+      return true
+    }
 
-        if (!stateChar) {
-          re += '\\('
-          continue
-        }
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
 
-        patternListStack.push({
-          type: stateChar,
-          start: i - 1,
-          reStart: re.length,
-          open: plTypes[stateChar].open,
-          close: plTypes[stateChar].close
-        })
-        // negation is (?:(?!js)[^/]*)
-        re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
-        this.debug('plType %j %j', stateChar, re)
-        stateChar = false
-      continue
+    if (!encoding)
+      encoding = 'utf8'
 
-      case ')':
-        if (inClass || !patternListStack.length) {
-          re += '\\)'
-          continue
-        }
+    const fn = this[ASYNC] ? defer : f => f()
 
-        clearStateChar()
-        hasMagic = true
-        var pl = patternListStack.pop()
-        // negation is (?:(?!js)[^/]*)
-        // The others are (?:)
-        re += pl.close
-        if (pl.type === '!') {
-          negativeLists.push(pl)
-        }
-        pl.reEnd = re.length
-      continue
+    // convert array buffers and typed array views into buffers
+    // at some point in the future, we may want to do the opposite!
+    // leave strings and buffers as-is
+    // anything else switches us into object mode
+    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+      if (isArrayBufferView(chunk))
+        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
+      else if (isArrayBuffer(chunk))
+        chunk = Buffer.from(chunk)
+      else if (typeof chunk !== 'string')
+        // use the setter so we throw if we have encoding set
+        this.objectMode = true
+    }
 
-      case '|':
-        if (inClass || !patternListStack.length || escaping) {
-          re += '\\|'
-          escaping = false
-          continue
-        }
+    // handle object mode up front, since it's simpler
+    // this yields better performance, fewer checks later.
+    if (this[OBJECTMODE]) {
+      /* istanbul ignore if - maybe impossible? */
+      if (this.flowing && this[BUFFERLENGTH] !== 0)
+        this[FLUSH](true)
 
-        clearStateChar()
-        re += '|'
-      continue
+      if (this.flowing)
+        this.emit('data', chunk)
+      else
+        this[BUFFERPUSH](chunk)
 
-      // these are mostly the same in regexp and glob
-      case '[':
-        // swallow any state-tracking char before the [
-        clearStateChar()
+      if (this[BUFFERLENGTH] !== 0)
+        this.emit('readable')
 
-        if (inClass) {
-          re += '\\' + c
-          continue
-        }
+      if (cb)
+        fn(cb)
 
-        inClass = true
-        classStart = i
-        reClassStart = re.length
-        re += c
-      continue
+      return this.flowing
+    }
 
-      case ']':
-        //  a right bracket shall lose its special
-        //  meaning and represent itself in
-        //  a bracket expression if it occurs
-        //  first in the list.  -- POSIX.2 2.8.3.2
-        if (i === classStart + 1 || !inClass) {
-          re += '\\' + c
-          escaping = false
-          continue
-        }
+    // at this point the chunk is a buffer or string
+    // don't buffer it up or send it to the decoder
+    if (!chunk.length) {
+      if (this[BUFFERLENGTH] !== 0)
+        this.emit('readable')
+      if (cb)
+        fn(cb)
+      return this.flowing
+    }
 
-        // handle the case where we left a class open.
-        // "[z-a]" is valid, equivalent to "\[z-a\]"
-        // split where the last [ was, make sure we don't have
-        // an invalid re. if so, re-walk the contents of the
-        // would-be class to re-translate any characters that
-        // were passed through as-is
-        // TODO: It would probably be faster to determine this
-        // without a try/catch and a new RegExp, but it's tricky
-        // to do safely.  For now, this is safe and works.
-        var cs = pattern.substring(classStart + 1, i)
-        try {
-          RegExp('[' + cs + ']')
-        } catch (er) {
-          // not a valid class!
-          var sp = this.parse(cs, SUBPARSE)
-          re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
-          hasMagic = hasMagic || sp[1]
-          inClass = false
-          continue
-        }
+    // fast-path writing strings of same encoding to a stream with
+    // an empty buffer, skipping the buffer/decoder dance
+    if (typeof chunk === 'string' &&
+        // unless it is a string already ready for us to use
+        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
+      chunk = Buffer.from(chunk, encoding)
+    }
 
-        // finish up the class.
-        hasMagic = true
-        inClass = false
-        re += c
-      continue
+    if (Buffer.isBuffer(chunk) && this[ENCODING])
+      chunk = this[DECODER].write(chunk)
 
-      default:
-        // swallow any state char that wasn't consumed
-        clearStateChar()
+    // Note: flushing CAN potentially switch us into not-flowing mode
+    if (this.flowing && this[BUFFERLENGTH] !== 0)
+      this[FLUSH](true)
 
-        if (escaping) {
-          // no need
-          escaping = false
-        } else if (reSpecials[c]
-          && !(c === '^' && inClass)) {
-          re += '\\'
-        }
+    if (this.flowing)
+      this.emit('data', chunk)
+    else
+      this[BUFFERPUSH](chunk)
 
-        re += c
+    if (this[BUFFERLENGTH] !== 0)
+      this.emit('readable')
 
-    } // switch
-  } // for
+    if (cb)
+      fn(cb)
 
-  // handle the case where we left a class open.
-  // "[abc" is valid, equivalent to "\[abc"
-  if (inClass) {
-    // split where the last [ was, and escape it
-    // this is a huge pita.  We now have to re-walk
-    // the contents of the would-be class to re-translate
-    // any characters that were passed through as-is
-    cs = pattern.substr(classStart + 1)
-    sp = this.parse(cs, SUBPARSE)
-    re = re.substr(0, reClassStart) + '\\[' + sp[0]
-    hasMagic = hasMagic || sp[1]
+    return this.flowing
   }
 
-  // handle the case where we had a +( thing at the *end*
-  // of the pattern.
-  // each pattern list stack adds 3 chars, and we need to go through
-  // and escape any | chars that were passed through as-is for the regexp.
-  // Go through and escape them, taking care not to double-escape any
-  // | chars that were already escaped.
-  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
-    var tail = re.slice(pl.reStart + pl.open.length)
-    this.debug('setting tail', re, pl)
-    // maybe some even number of \, then maybe 1 \, followed by a |
-    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
-      if (!$2) {
-        // the | isn't already escaped, so escape it.
-        $2 = '\\'
-      }
+  read (n) {
+    if (this[DESTROYED])
+      return null
 
-      // need to escape all those slashes *again*, without escaping the
-      // one that we need for escaping the | character.  As it works out,
-      // escaping an even number of slashes can be done by simply repeating
-      // it exactly after itself.  That's why this trick works.
-      //
-      // I am sorry that you have to see this.
-      return $1 + $1 + $2 + '|'
-    })
+    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
+      this[MAYBE_EMIT_END]()
+      return null
+    }
 
-    this.debug('tail=%j\n   %s', tail, tail, pl, re)
-    var t = pl.type === '*' ? star
-      : pl.type === '?' ? qmark
-      : '\\' + pl.type
+    if (this[OBJECTMODE])
+      n = null
 
-    hasMagic = true
-    re = re.slice(0, pl.reStart) + t + '\\(' + tail
-  }
+    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
+      if (this.encoding)
+        this.buffer = [this.buffer.join('')]
+      else
+        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
+    }
 
-  // handle trailing things that only matter at the very end.
-  clearStateChar()
-  if (escaping) {
-    // trailing \\
-    re += '\\\\'
+    const ret = this[READ](n || null, this.buffer[0])
+    this[MAYBE_EMIT_END]()
+    return ret
   }
 
-  // only need to apply the nodot start if the re starts with
-  // something that could conceivably capture a dot
-  var addPatternStart = false
-  switch (re.charAt(0)) {
-    case '[': case '.': case '(': addPatternStart = true
+  [READ] (n, chunk) {
+    if (n === chunk.length || n === null)
+      this[BUFFERSHIFT]()
+    else {
+      this.buffer[0] = chunk.slice(n)
+      chunk = chunk.slice(0, n)
+      this[BUFFERLENGTH] -= n
+    }
+
+    this.emit('data', chunk)
+
+    if (!this.buffer.length && !this[EOF])
+      this.emit('drain')
+
+    return chunk
   }
 
-  // Hack to work around lack of negative lookbehind in JS
-  // A pattern like: *.!(x).!(y|z) needs to ensure that a name
-  // like 'a.xyz.yz' doesn't match.  So, the first negative
-  // lookahead, has to look ALL the way ahead, to the end of
-  // the pattern.
-  for (var n = negativeLists.length - 1; n > -1; n--) {
-    var nl = negativeLists[n]
+  end (chunk, encoding, cb) {
+    if (typeof chunk === 'function')
+      cb = chunk, chunk = null
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
+    if (chunk)
+      this.write(chunk, encoding)
+    if (cb)
+      this.once('end', cb)
+    this[EOF] = true
+    this.writable = false
 
-    var nlBefore = re.slice(0, nl.reStart)
-    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
-    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
-    var nlAfter = re.slice(nl.reEnd)
+    // if we haven't written anything, then go ahead and emit,
+    // even if we're not reading.
+    // we'll re-emit if a new 'end' listener is added anyway.
+    // This makes MP more suitable to write-only use cases.
+    if (this.flowing || !this[PAUSED])
+      this[MAYBE_EMIT_END]()
+    return this
+  }
 
-    nlLast += nlAfter
+  // don't let the internal resume be overwritten
+  [RESUME] () {
+    if (this[DESTROYED])
+      return
 
-    // Handle nested stuff like *(*.js|!(*.json)), where open parens
-    // mean that we should *not* include the ) in the bit that is considered
-    // "after" the negated section.
-    var openParensBefore = nlBefore.split('(').length - 1
-    var cleanAfter = nlAfter
-    for (i = 0; i < openParensBefore; i++) {
-      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
-    }
-    nlAfter = cleanAfter
+    this[PAUSED] = false
+    this[FLOWING] = true
+    this.emit('resume')
+    if (this.buffer.length)
+      this[FLUSH]()
+    else if (this[EOF])
+      this[MAYBE_EMIT_END]()
+    else
+      this.emit('drain')
+  }
 
-    var dollar = ''
-    if (nlAfter === '' && isSub !== SUBPARSE) {
-      dollar = '$'
-    }
-    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
-    re = newRe
+  resume () {
+    return this[RESUME]()
   }
 
-  // if the re is not "" at this point, then we need to make sure
-  // it doesn't match against an empty path part.
-  // Otherwise a/* will match a/, which it should not.
-  if (re !== '' && hasMagic) {
-    re = '(?=.)' + re
+  pause () {
+    this[FLOWING] = false
+    this[PAUSED] = true
   }
 
-  if (addPatternStart) {
-    re = patternStart + re
+  get destroyed () {
+    return this[DESTROYED]
   }
 
-  // parsing just a piece of a larger pattern.
-  if (isSub === SUBPARSE) {
-    return [re, hasMagic]
+  get flowing () {
+    return this[FLOWING]
   }
 
-  // skip the regexp for non-magical patterns
-  // unescape anything in it, though, so that it'll be
-  // an exact match against a file etc.
-  if (!hasMagic) {
-    return globUnescape(pattern)
+  get paused () {
+    return this[PAUSED]
   }
 
-  var flags = options.nocase ? 'i' : ''
-  try {
-    var regExp = new RegExp('^' + re + '$', flags)
-  } catch (er) /* istanbul ignore next - should be impossible */ {
-    // If it was an invalid regular expression, then it can't match
-    // anything.  This trick looks for a character after the end of
-    // the string, which is of course impossible, except in multi-line
-    // mode, but it's not a /m regex.
-    return new RegExp('$.')
+  [BUFFERPUSH] (chunk) {
+    if (this[OBJECTMODE])
+      this[BUFFERLENGTH] += 1
+    else
+      this[BUFFERLENGTH] += chunk.length
+    this.buffer.push(chunk)
   }
 
-  regExp._glob = pattern
-  regExp._src = re
+  [BUFFERSHIFT] () {
+    if (this.buffer.length) {
+      if (this[OBJECTMODE])
+        this[BUFFERLENGTH] -= 1
+      else
+        this[BUFFERLENGTH] -= this.buffer[0].length
+    }
+    return this.buffer.shift()
+  }
 
-  return regExp
-}
+  [FLUSH] (noDrain) {
+    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
 
-minimatch.makeRe = function (pattern, options) {
-  return new Minimatch(pattern, options || {}).makeRe()
-}
+    if (!noDrain && !this.buffer.length && !this[EOF])
+      this.emit('drain')
+  }
 
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
-  if (this.regexp || this.regexp === false) return this.regexp
+  [FLUSHCHUNK] (chunk) {
+    return chunk ? (this.emit('data', chunk), this.flowing) : false
+  }
 
-  // at this point, this.set is a 2d array of partial
-  // pattern strings, or "**".
-  //
-  // It's better to use .match().  This function shouldn't
-  // be used, really, but it's pretty convenient sometimes,
-  // when you just want to work with a regex.
-  var set = this.set
+  pipe (dest, opts) {
+    if (this[DESTROYED])
+      return
 
-  if (!set.length) {
-    this.regexp = false
-    return this.regexp
+    const ended = this[EMITTED_END]
+    opts = opts || {}
+    if (dest === proc.stdout || dest === proc.stderr)
+      opts.end = false
+    else
+      opts.end = opts.end !== false
+    opts.proxyErrors = !!opts.proxyErrors
+
+    // piping an ended stream ends immediately
+    if (ended) {
+      if (opts.end)
+        dest.end()
+    } else {
+      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
+        : new PipeProxyErrors(this, dest, opts))
+      if (this[ASYNC])
+        defer(() => this[RESUME]())
+      else
+        this[RESUME]()
+    }
+
+    return dest
   }
-  var options = this.options
 
-  var twoStar = options.noglobstar ? star
-    : options.dot ? twoStarDot
-    : twoStarNoDot
-  var flags = options.nocase ? 'i' : ''
+  unpipe (dest) {
+    const p = this.pipes.find(p => p.dest === dest)
+    if (p) {
+      this.pipes.splice(this.pipes.indexOf(p), 1)
+      p.unpipe()
+    }
+  }
 
-  var re = set.map(function (pattern) {
-    return pattern.map(function (p) {
-      return (p === GLOBSTAR) ? twoStar
-      : (typeof p === 'string') ? regExpEscape(p)
-      : p._src
-    }).join('\\\/')
-  }).join('|')
+  addListener (ev, fn) {
+    return this.on(ev, fn)
+  }
 
-  // must match entire pattern
-  // ending in a * or ** will make it less strict.
-  re = '^(?:' + re + ')$'
+  on (ev, fn) {
+    const ret = super.on(ev, fn)
+    if (ev === 'data' && !this.pipes.length && !this.flowing)
+      this[RESUME]()
+    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
+      super.emit('readable')
+    else if (isEndish(ev) && this[EMITTED_END]) {
+      super.emit(ev)
+      this.removeAllListeners(ev)
+    } else if (ev === 'error' && this[EMITTED_ERROR]) {
+      if (this[ASYNC])
+        defer(() => fn.call(this, this[EMITTED_ERROR]))
+      else
+        fn.call(this, this[EMITTED_ERROR])
+    }
+    return ret
+  }
 
-  // can match anything, as long as it's not this.
-  if (this.negate) re = '^(?!' + re + ').*$'
+  get emittedEnd () {
+    return this[EMITTED_END]
+  }
 
-  try {
-    this.regexp = new RegExp(re, flags)
-  } catch (ex) /* istanbul ignore next - should be impossible */ {
-    this.regexp = false
+  [MAYBE_EMIT_END] () {
+    if (!this[EMITTING_END] &&
+        !this[EMITTED_END] &&
+        !this[DESTROYED] &&
+        this.buffer.length === 0 &&
+        this[EOF]) {
+      this[EMITTING_END] = true
+      this.emit('end')
+      this.emit('prefinish')
+      this.emit('finish')
+      if (this[CLOSED])
+        this.emit('close')
+      this[EMITTING_END] = false
+    }
   }
-  return this.regexp
-}
 
-minimatch.match = function (list, pattern, options) {
-  options = options || {}
-  var mm = new Minimatch(pattern, options)
-  list = list.filter(function (f) {
-    return mm.match(f)
-  })
-  if (mm.options.nonull && !list.length) {
-    list.push(pattern)
+  emit (ev, data, ...extra) {
+    // error and close are only events allowed after calling destroy()
+    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
+      return
+    else if (ev === 'data') {
+      return !data ? false
+        : this[ASYNC] ? defer(() => this[EMITDATA](data))
+        : this[EMITDATA](data)
+    } else if (ev === 'end') {
+      return this[EMITEND]()
+    } else if (ev === 'close') {
+      this[CLOSED] = true
+      // don't emit close before 'end' and 'finish'
+      if (!this[EMITTED_END] && !this[DESTROYED])
+        return
+      const ret = super.emit('close')
+      this.removeAllListeners('close')
+      return ret
+    } else if (ev === 'error') {
+      this[EMITTED_ERROR] = data
+      const ret = super.emit('error', data)
+      this[MAYBE_EMIT_END]()
+      return ret
+    } else if (ev === 'resume') {
+      const ret = super.emit('resume')
+      this[MAYBE_EMIT_END]()
+      return ret
+    } else if (ev === 'finish' || ev === 'prefinish') {
+      const ret = super.emit(ev)
+      this.removeAllListeners(ev)
+      return ret
+    }
+
+    // Some other unknown event
+    const ret = super.emit(ev, data, ...extra)
+    this[MAYBE_EMIT_END]()
+    return ret
   }
-  return list
-}
-
-Minimatch.prototype.match = function match (f, partial) {
-  if (typeof partial === 'undefined') partial = this.partial
-  this.debug('match', f, this.pattern)
-  // short-circuit in the case of busted things.
-  // comments, etc.
-  if (this.comment) return false
-  if (this.empty) return f === ''
-
-  if (f === '/' && partial) return true
 
-  var options = this.options
-
-  // windows: need to use /, not \
-  if (path.sep !== '/') {
-    f = f.split(path.sep).join('/')
+  [EMITDATA] (data) {
+    for (const p of this.pipes) {
+      if (p.dest.write(data) === false)
+        this.pause()
+    }
+    const ret = super.emit('data', data)
+    this[MAYBE_EMIT_END]()
+    return ret
   }
 
-  // treat the test path as a set of pathparts.
-  f = f.split(slashSplit)
-  this.debug(this.pattern, 'split', f)
-
-  // just ONE of the pattern sets in this.set needs to match
-  // in order for it to be valid.  If negating, then just one
-  // match means that we have failed.
-  // Either way, return on the first hit.
-
-  var set = this.set
-  this.debug(this.pattern, 'set', set)
+  [EMITEND] () {
+    if (this[EMITTED_END])
+      return
 
-  // Find the basename of the path by looking for the last non-empty segment
-  var filename
-  var i
-  for (i = f.length - 1; i >= 0; i--) {
-    filename = f[i]
-    if (filename) break
+    this[EMITTED_END] = true
+    this.readable = false
+    if (this[ASYNC])
+      defer(() => this[EMITEND2]())
+    else
+      this[EMITEND2]()
   }
 
-  for (i = 0; i < set.length; i++) {
-    var pattern = set[i]
-    var file = f
-    if (options.matchBase && pattern.length === 1) {
-      file = [filename]
+  [EMITEND2] () {
+    if (this[DECODER]) {
+      const data = this[DECODER].end()
+      if (data) {
+        for (const p of this.pipes) {
+          p.dest.write(data)
+        }
+        super.emit('data', data)
+      }
     }
-    var hit = this.matchOne(file, pattern, partial)
-    if (hit) {
-      if (options.flipNegate) return true
-      return !this.negate
+
+    for (const p of this.pipes) {
+      p.end()
     }
+    const ret = super.emit('end')
+    this.removeAllListeners('end')
+    return ret
   }
 
-  // didn't get any hits.  this is success if it's a negative
-  // pattern, failure otherwise.
-  if (options.flipNegate) return false
-  return this.negate
-}
-
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
-  var options = this.options
-
-  this.debug('matchOne',
-    { 'this': this, file: file, pattern: pattern })
-
-  this.debug('matchOne', file.length, pattern.length)
+  // const all = await stream.collect()
+  collect () {
+    const buf = []
+    if (!this[OBJECTMODE])
+      buf.dataLength = 0
+    // set the promise first, in case an error is raised
+    // by triggering the flow here.
+    const p = this.promise()
+    this.on('data', c => {
+      buf.push(c)
+      if (!this[OBJECTMODE])
+        buf.dataLength += c.length
+    })
+    return p.then(() => buf)
+  }
 
-  for (var fi = 0,
-      pi = 0,
-      fl = file.length,
-      pl = pattern.length
-      ; (fi < fl) && (pi < pl)
-      ; fi++, pi++) {
-    this.debug('matchOne loop')
-    var p = pattern[pi]
-    var f = file[fi]
+  // const data = await stream.concat()
+  concat () {
+    return this[OBJECTMODE]
+      ? Promise.reject(new Error('cannot concat in objectMode'))
+      : this.collect().then(buf =>
+          this[OBJECTMODE]
+            ? Promise.reject(new Error('cannot concat in objectMode'))
+            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
+  }
 
-    this.debug(pattern, p, f)
+  // stream.promise().then(() => done, er => emitted error)
+  promise () {
+    return new Promise((resolve, reject) => {
+      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
+      this.on('error', er => reject(er))
+      this.on('end', () => resolve())
+    })
+  }
 
-    // should be impossible.
-    // some invalid regexp stuff in the set.
-    /* istanbul ignore if */
-    if (p === false) return false
+  // for await (let chunk of stream)
+  [ASYNCITERATOR] () {
+    const next = () => {
+      const res = this.read()
+      if (res !== null)
+        return Promise.resolve({ done: false, value: res })
 
-    if (p === GLOBSTAR) {
-      this.debug('GLOBSTAR', [pattern, p, f])
+      if (this[EOF])
+        return Promise.resolve({ done: true })
 
-      // "**"
-      // a/**/b/**/c would match the following:
-      // a/b/x/y/z/c
-      // a/x/y/z/b/c
-      // a/b/x/b/x/c
-      // a/b/c
-      // To do this, take the rest of the pattern after
-      // the **, and see if it would match the file remainder.
-      // If so, return success.
-      // If not, the ** "swallows" a segment, and try again.
-      // This is recursively awful.
-      //
-      // a/**/b/**/c matching a/b/x/y/z/c
-      // - a matches a
-      // - doublestar
-      //   - matchOne(b/x/y/z/c, b/**/c)
-      //     - b matches b
-      //     - doublestar
-      //       - matchOne(x/y/z/c, c) -> no
-      //       - matchOne(y/z/c, c) -> no
-      //       - matchOne(z/c, c) -> no
-      //       - matchOne(c, c) yes, hit
-      var fr = fi
-      var pr = pi + 1
-      if (pr === pl) {
-        this.debug('** at the end')
-        // a ** at the end will just swallow the rest.
-        // We have found a match.
-        // however, it will not swallow /.x, unless
-        // options.dot is set.
-        // . and .. are *never* matched by **, for explosively
-        // exponential reasons.
-        for (; fi < fl; fi++) {
-          if (file[fi] === '.' || file[fi] === '..' ||
-            (!options.dot && file[fi].charAt(0) === '.')) return false
-        }
-        return true
+      let resolve = null
+      let reject = null
+      const onerr = er => {
+        this.removeListener('data', ondata)
+        this.removeListener('end', onend)
+        reject(er)
       }
-
-      // ok, let's see if we can swallow whatever we can.
-      while (fr < fl) {
-        var swallowee = file[fr]
-
-        this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
-
-        // XXX remove this slice.  Just pass the start index.
-        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
-          this.debug('globstar found match!', fr, fl, swallowee)
-          // found a match.
-          return true
-        } else {
-          // can't swallow "." or ".." ever.
-          // can only swallow ".foo" when explicitly asked.
-          if (swallowee === '.' || swallowee === '..' ||
-            (!options.dot && swallowee.charAt(0) === '.')) {
-            this.debug('dot detected!', file, fr, pattern, pr)
-            break
-          }
-
-          // ** swallows a segment, and continue.
-          this.debug('globstar swallow a segment, and continue')
-          fr++
-        }
+      const ondata = value => {
+        this.removeListener('error', onerr)
+        this.removeListener('end', onend)
+        this.pause()
+        resolve({ value: value, done: !!this[EOF] })
       }
-
-      // no match was found.
-      // However, in partial mode, we can't say this is necessarily over.
-      // If there's more *pattern* left, then
-      /* istanbul ignore if */
-      if (partial) {
-        // ran out of file
-        this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
-        if (fr === fl) return true
+      const onend = () => {
+        this.removeListener('error', onerr)
+        this.removeListener('data', ondata)
+        resolve({ done: true })
       }
-      return false
+      const ondestroy = () => onerr(new Error('stream destroyed'))
+      return new Promise((res, rej) => {
+        reject = rej
+        resolve = res
+        this.once(DESTROYED, ondestroy)
+        this.once('error', onerr)
+        this.once('end', onend)
+        this.once('data', ondata)
+      })
     }
 
-    // something other than **
-    // non-magic patterns just have to match exactly
-    // patterns with magic have been turned into regexps.
-    var hit
-    if (typeof p === 'string') {
-      hit = f === p
-      this.debug('string match', p, f, hit)
-    } else {
-      hit = f.match(p)
-      this.debug('pattern match', p, f, hit)
-    }
+    return { next }
+  }
 
-    if (!hit) return false
+  // for (let chunk of stream)
+  [ITERATOR] () {
+    const next = () => {
+      const value = this.read()
+      const done = value === null
+      return { value, done }
+    }
+    return { next }
   }
 
-  // Note: ending in / means that we'll get a final ""
-  // at the end of the pattern.  This can only match a
-  // corresponding "" at the end of the file.
-  // If the file ends in /, then it can only match a
-  // a pattern that ends in /, unless the pattern just
-  // doesn't have any more for it. But, a/b/ should *not*
-  // match "a/b/*", even though "" matches against the
-  // [^/]*? pattern, except in partial mode, where it might
-  // simply not be reached yet.
-  // However, a/b/ should still satisfy a/*
+  destroy (er) {
+    if (this[DESTROYED]) {
+      if (er)
+        this.emit('error', er)
+      else
+        this.emit(DESTROYED)
+      return this
+    }
 
-  // now either we fell off the end of the pattern, or we're done.
-  if (fi === fl && pi === pl) {
-    // ran out of pattern and filename at the same time.
-    // an exact hit!
-    return true
-  } else if (fi === fl) {
-    // ran out of file, but still had pattern left.
-    // this is ok if we're doing the match as part of
-    // a glob fs traversal.
-    return partial
-  } else /* istanbul ignore else */ if (pi === pl) {
-    // ran out of pattern, still have file left.
-    // this is only acceptable if we're on the very last
-    // empty segment of a file with a trailing slash.
-    // a/* should match a/b/
-    return (fi === fl - 1) && (file[fi] === '')
-  }
+    this[DESTROYED] = true
 
-  // should be unreachable.
-  /* istanbul ignore next */
-  throw new Error('wtf?')
-}
+    // throw away all buffered data, it's never coming out
+    this.buffer.length = 0
+    this[BUFFERLENGTH] = 0
 
-// replace stuff like \* with *
-function globUnescape (s) {
-  return s.replace(/\\(.)/g, '$1')
-}
+    if (typeof this.close === 'function' && !this[CLOSED])
+      this.close()
 
-function regExpEscape (s) {
-  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
+    if (er)
+      this.emit('error', er)
+    else // if no error to emit, still reject pending promises
+      this.emit(DESTROYED)
+
+    return this
+  }
+
+  static isStream (s) {
+    return !!s && (s instanceof Minipass || s instanceof Stream ||
+      s instanceof EE && (
+        typeof s.pipe === 'function' || // readable
+        (typeof s.write === 'function' && typeof s.end === 'function') // writable
+      ))
+  }
 }
 
 
 /***/ }),
 
-/***/ 11757:
+/***/ 52899:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-const { Minipass } = __nccwpck_require__(78275)
-const _data = Symbol('_data')
-const _length = Symbol('_length')
-class Collect extends Minipass {
-  constructor (options) {
-    super(options)
-    this[_data] = []
-    this[_length] = 0
-  }
-  write (chunk, encoding, cb) {
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
+const Minipass = __nccwpck_require__(45485)
+const EE = __nccwpck_require__(24434)
+const isStream = s => s && s instanceof EE && (
+  typeof s.pipe === 'function' || // readable
+  (typeof s.write === 'function' && typeof s.end === 'function') // writable
+)
 
-    if (!encoding)
-      encoding = 'utf8'
+const _head = Symbol('_head')
+const _tail = Symbol('_tail')
+const _linkStreams = Symbol('_linkStreams')
+const _setHead = Symbol('_setHead')
+const _setTail = Symbol('_setTail')
+const _onError = Symbol('_onError')
+const _onData = Symbol('_onData')
+const _onEnd = Symbol('_onEnd')
+const _onDrain = Symbol('_onDrain')
+const _streams = Symbol('_streams')
+class Pipeline extends Minipass {
+  constructor (opts, ...streams) {
+    if (isStream(opts)) {
+      streams.unshift(opts)
+      opts = {}
+    }
 
-    const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
-    this[_data].push(c)
-    this[_length] += c.length
-    if (cb)
-      cb()
-    return true
-  }
-  end (chunk, encoding, cb) {
-    if (typeof chunk === 'function')
-      cb = chunk, chunk = null
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
-    if (chunk)
-      this.write(chunk, encoding)
-    const result = Buffer.concat(this[_data], this[_length])
-    super.write(result)
-    return super.end(cb)
+    super(opts)
+    this[_streams] = []
+    if (streams.length)
+      this.push(...streams)
   }
-}
-module.exports = Collect
 
-// it would be possible to DRY this a bit by doing something like
-// this.collector = new Collect() and listening on its data event,
-// but it's not much code, and we may as well save the extra obj
-class CollectPassThrough extends Minipass {
-  constructor (options) {
-    super(options)
-    this[_data] = []
-    this[_length] = 0
+  [_linkStreams] (streams) {
+    // reduce takes (left,right), and we return right to make it the
+    // new left value.
+    return streams.reduce((src, dest) => {
+      src.on('error', er => dest.emit('error', er))
+      src.pipe(dest)
+      return dest
+    })
   }
-  write (chunk, encoding, cb) {
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
 
-    if (!encoding)
-      encoding = 'utf8'
+  push (...streams) {
+    this[_streams].push(...streams)
+    if (this[_tail])
+      streams.unshift(this[_tail])
 
-    const c = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
-    this[_data].push(c)
-    this[_length] += c.length
-    return super.write(chunk, encoding, cb)
-  }
-  end (chunk, encoding, cb) {
-    if (typeof chunk === 'function')
-      cb = chunk, chunk = null
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
-    if (chunk)
-      this.write(chunk, encoding)
-    const result = Buffer.concat(this[_data], this[_length])
-    this.emit('collect', result)
-    return super.end(cb)
+    const linkRet = this[_linkStreams](streams)
+
+    this[_setTail](linkRet)
+    if (!this[_head])
+      this[_setHead](streams[0])
   }
-}
-module.exports.PassThrough = CollectPassThrough
 
+  unshift (...streams) {
+    this[_streams].unshift(...streams)
+    if (this[_head])
+      streams.push(this[_head])
 
-/***/ }),
+    const linkRet = this[_linkStreams](streams)
+    this[_setHead](streams[0])
+    if (!this[_tail])
+      this[_setTail](linkRet)
+  }
 
-/***/ 57442:
-/***/ ((module) => {
+  destroy (er) {
+    // set fire to the whole thing.
+    this[_streams].forEach(s =>
+      typeof s.destroy === 'function' && s.destroy())
+    return super.destroy(er)
+  }
 
-"use strict";
+  // readable interface -> tail
+  [_setTail] (stream) {
+    this[_tail] = stream
+    stream.on('error', er => this[_onError](stream, er))
+    stream.on('data', chunk => this[_onData](stream, chunk))
+    stream.on('end', () => this[_onEnd](stream))
+    stream.on('finish', () => this[_onEnd](stream))
+  }
 
-class AbortError extends Error {
-  constructor (message) {
-    super(message)
-    this.code = 'FETCH_ABORTED'
-    this.type = 'aborted'
-    Error.captureStackTrace(this, this.constructor)
+  // errors proxied down the pipeline
+  // they're considered part of the "read" interface
+  [_onError] (stream, er) {
+    if (stream === this[_tail])
+      this.emit('error', er)
+  }
+  [_onData] (stream, chunk) {
+    if (stream === this[_tail])
+      super.write(chunk)
+  }
+  [_onEnd] (stream) {
+    if (stream === this[_tail])
+      super.end()
+  }
+  pause () {
+    super.pause()
+    return this[_tail] && this[_tail].pause && this[_tail].pause()
+  }
+
+  // NB: Minipass calls its internal private [RESUME] method during
+  // pipe drains, to avoid hazards where stream.resume() is overridden.
+  // Thus, we need to listen to the resume *event*, not override the
+  // resume() method, and proxy *that* to the tail.
+  emit (ev, ...args) {
+    if (ev === 'resume' && this[_tail] && this[_tail].resume)
+      this[_tail].resume()
+    return super.emit(ev, ...args)
   }
 
-  get name () {
-    return 'AbortError'
+  // writable interface -> head
+  [_setHead] (stream) {
+    this[_head] = stream
+    stream.on('drain', () => this[_onDrain](stream))
+  }
+  [_onDrain] (stream) {
+    if (stream === this[_head])
+      this.emit('drain')
+  }
+  write (chunk, enc, cb) {
+    return this[_head].write(chunk, enc, cb) &&
+      (this.flowing || this.buffer.length === 0)
+  }
+  end (chunk, enc, cb) {
+    this[_head].end(chunk, enc, cb)
+    return this
   }
-
-  // don't allow name to be overridden, but don't throw either
-  set name (s) {}
 }
-module.exports = AbortError
+
+module.exports = Pipeline
 
 
 /***/ }),
 
-/***/ 21256:
+/***/ 45485:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
 
-const { Minipass } = __nccwpck_require__(78275)
-const TYPE = Symbol('type')
-const BUFFER = Symbol('buffer')
+const proc = typeof process === 'object' && process ? process : {
+  stdout: null,
+  stderr: null,
+}
+const EE = __nccwpck_require__(24434)
+const Stream = __nccwpck_require__(2203)
+const SD = (__nccwpck_require__(13193).StringDecoder)
 
-class Blob {
-  constructor (blobParts, options) {
-    this[TYPE] = ''
+const EOF = Symbol('EOF')
+const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
+const EMITTED_END = Symbol('emittedEnd')
+const EMITTING_END = Symbol('emittingEnd')
+const EMITTED_ERROR = Symbol('emittedError')
+const CLOSED = Symbol('closed')
+const READ = Symbol('read')
+const FLUSH = Symbol('flush')
+const FLUSHCHUNK = Symbol('flushChunk')
+const ENCODING = Symbol('encoding')
+const DECODER = Symbol('decoder')
+const FLOWING = Symbol('flowing')
+const PAUSED = Symbol('paused')
+const RESUME = Symbol('resume')
+const BUFFERLENGTH = Symbol('bufferLength')
+const BUFFERPUSH = Symbol('bufferPush')
+const BUFFERSHIFT = Symbol('bufferShift')
+const OBJECTMODE = Symbol('objectMode')
+const DESTROYED = Symbol('destroyed')
+const EMITDATA = Symbol('emitData')
+const EMITEND = Symbol('emitEnd')
+const EMITEND2 = Symbol('emitEnd2')
+const ASYNC = Symbol('async')
 
-    const buffers = []
-    let size = 0
+const defer = fn => Promise.resolve().then(fn)
 
-    if (blobParts) {
-      const a = blobParts
-      const length = Number(a.length)
-      for (let i = 0; i < length; i++) {
-        const element = a[i]
-        const buffer = element instanceof Buffer ? element
-          : ArrayBuffer.isView(element)
-            ? Buffer.from(element.buffer, element.byteOffset, element.byteLength)
-            : element instanceof ArrayBuffer ? Buffer.from(element)
-            : element instanceof Blob ? element[BUFFER]
-            : typeof element === 'string' ? Buffer.from(element)
-            : Buffer.from(String(element))
-        size += buffer.length
-        buffers.push(buffer)
-      }
-    }
+// TODO remove when Node v8 support drops
+const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
+const ASYNCITERATOR = doIter && Symbol.asyncIterator
+  || Symbol('asyncIterator not implemented')
+const ITERATOR = doIter && Symbol.iterator
+  || Symbol('iterator not implemented')
 
-    this[BUFFER] = Buffer.concat(buffers, size)
+// events that mean 'the stream is over'
+// these are treated specially, and re-emitted
+// if they are listened for after emitting.
+const isEndish = ev =>
+  ev === 'end' ||
+  ev === 'finish' ||
+  ev === 'prefinish'
 
-    const type = options && options.type !== undefined
-      && String(options.type).toLowerCase()
-    if (type && !/[^\u0020-\u007E]/.test(type)) {
-      this[TYPE] = type
-    }
-  }
+const isArrayBuffer = b => b instanceof ArrayBuffer ||
+  typeof b === 'object' &&
+  b.constructor &&
+  b.constructor.name === 'ArrayBuffer' &&
+  b.byteLength >= 0
 
-  get size () {
-    return this[BUFFER].length
-  }
+const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
 
-  get type () {
-    return this[TYPE]
+class Pipe {
+  constructor (src, dest, opts) {
+    this.src = src
+    this.dest = dest
+    this.opts = opts
+    this.ondrain = () => src[RESUME]()
+    dest.on('drain', this.ondrain)
   }
-
-  text () {
-    return Promise.resolve(this[BUFFER].toString())
+  unpipe () {
+    this.dest.removeListener('drain', this.ondrain)
+  }
+  // istanbul ignore next - only here for the prototype
+  proxyErrors () {}
+  end () {
+    this.unpipe()
+    if (this.opts.end)
+      this.dest.end()
   }
+}
 
-  arrayBuffer () {
-    const buf = this[BUFFER]
-    const off = buf.byteOffset
-    const len = buf.byteLength
-    const ab = buf.buffer.slice(off, off + len)
-    return Promise.resolve(ab)
+class PipeProxyErrors extends Pipe {
+  unpipe () {
+    this.src.removeListener('error', this.proxyErrors)
+    super.unpipe()
+  }
+  constructor (src, dest, opts) {
+    super(src, dest, opts)
+    this.proxyErrors = er => dest.emit('error', er)
+    src.on('error', this.proxyErrors)
   }
+}
 
-  stream () {
-    return new Minipass().end(this[BUFFER])
+module.exports = class Minipass extends Stream {
+  constructor (options) {
+    super()
+    this[FLOWING] = false
+    // whether we're explicitly paused
+    this[PAUSED] = false
+    this.pipes = []
+    this.buffer = []
+    this[OBJECTMODE] = options && options.objectMode || false
+    if (this[OBJECTMODE])
+      this[ENCODING] = null
+    else
+      this[ENCODING] = options && options.encoding || null
+    if (this[ENCODING] === 'buffer')
+      this[ENCODING] = null
+    this[ASYNC] = options && !!options.async || false
+    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
+    this[EOF] = false
+    this[EMITTED_END] = false
+    this[EMITTING_END] = false
+    this[CLOSED] = false
+    this[EMITTED_ERROR] = null
+    this.writable = true
+    this.readable = true
+    this[BUFFERLENGTH] = 0
+    this[DESTROYED] = false
   }
 
-  slice (start, end, type) {
-    const size = this.size
-    const relativeStart = start === undefined ? 0
-      : start < 0 ? Math.max(size + start, 0)
-      : Math.min(start, size)
-    const relativeEnd = end === undefined ? size
-      : end < 0 ? Math.max(size + end, 0)
-      : Math.min(end, size)
-    const span = Math.max(relativeEnd - relativeStart, 0)
+  get bufferLength () { return this[BUFFERLENGTH] }
 
-    const buffer = this[BUFFER]
-    const slicedBuffer = buffer.slice(
-      relativeStart,
-      relativeStart + span
-    )
-    const blob = new Blob([], { type })
-    blob[BUFFER] = slicedBuffer
-    return blob
-  }
+  get encoding () { return this[ENCODING] }
+  set encoding (enc) {
+    if (this[OBJECTMODE])
+      throw new Error('cannot set encoding in objectMode')
 
-  get [Symbol.toStringTag] () {
-    return 'Blob'
+    if (this[ENCODING] && enc !== this[ENCODING] &&
+        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
+      throw new Error('cannot change encoding')
+
+    if (this[ENCODING] !== enc) {
+      this[DECODER] = enc ? new SD(enc) : null
+      if (this.buffer.length)
+        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
+    }
+
+    this[ENCODING] = enc
   }
 
-  static get BUFFER () {
-    return BUFFER
+  setEncoding (enc) {
+    this.encoding = enc
   }
-}
 
-Object.defineProperties(Blob.prototype, {
-  size: { enumerable: true },
-  type: { enumerable: true },
-})
+  get objectMode () { return this[OBJECTMODE] }
+  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
 
-module.exports = Blob
+  get ['async'] () { return this[ASYNC] }
+  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }
 
+  write (chunk, encoding, cb) {
+    if (this[EOF])
+      throw new Error('write after end')
 
-/***/ }),
+    if (this[DESTROYED]) {
+      this.emit('error', Object.assign(
+        new Error('Cannot call write after a stream was destroyed'),
+        { code: 'ERR_STREAM_DESTROYED' }
+      ))
+      return true
+    }
 
-/***/ 28515:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
 
-"use strict";
+    if (!encoding)
+      encoding = 'utf8'
 
-const { Minipass } = __nccwpck_require__(78275)
-const MinipassSized = __nccwpck_require__(48484)
+    const fn = this[ASYNC] ? defer : f => f()
 
-const Blob = __nccwpck_require__(21256)
-const { BUFFER } = Blob
-const FetchError = __nccwpck_require__(22644)
+    // convert array buffers and typed array views into buffers
+    // at some point in the future, we may want to do the opposite!
+    // leave strings and buffers as-is
+    // anything else switches us into object mode
+    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+      if (isArrayBufferView(chunk))
+        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
+      else if (isArrayBuffer(chunk))
+        chunk = Buffer.from(chunk)
+      else if (typeof chunk !== 'string')
+        // use the setter so we throw if we have encoding set
+        this.objectMode = true
+    }
 
-// optional dependency on 'encoding'
-let convert
-try {
-  convert = (__nccwpck_require__(24056)/* .convert */ .C)
-} catch (e) {
-  // defer error until textConverted is called
-}
+    // handle object mode up front, since it's simpler
+    // this yields better performance, fewer checks later.
+    if (this[OBJECTMODE]) {
+      /* istanbul ignore if - maybe impossible? */
+      if (this.flowing && this[BUFFERLENGTH] !== 0)
+        this[FLUSH](true)
 
-const INTERNALS = Symbol('Body internals')
-const CONSUME_BODY = Symbol('consumeBody')
+      if (this.flowing)
+        this.emit('data', chunk)
+      else
+        this[BUFFERPUSH](chunk)
 
-class Body {
-  constructor (bodyArg, options = {}) {
-    const { size = 0, timeout = 0 } = options
-    const body = bodyArg === undefined || bodyArg === null ? null
-      : isURLSearchParams(bodyArg) ? Buffer.from(bodyArg.toString())
-      : isBlob(bodyArg) ? bodyArg
-      : Buffer.isBuffer(bodyArg) ? bodyArg
-      : Object.prototype.toString.call(bodyArg) === '[object ArrayBuffer]'
-        ? Buffer.from(bodyArg)
-        : ArrayBuffer.isView(bodyArg)
-          ? Buffer.from(bodyArg.buffer, bodyArg.byteOffset, bodyArg.byteLength)
-          : Minipass.isStream(bodyArg) ? bodyArg
-          : Buffer.from(String(bodyArg))
+      if (this[BUFFERLENGTH] !== 0)
+        this.emit('readable')
 
-    this[INTERNALS] = {
-      body,
-      disturbed: false,
-      error: null,
-    }
+      if (cb)
+        fn(cb)
 
-    this.size = size
-    this.timeout = timeout
+      return this.flowing
+    }
 
-    if (Minipass.isStream(body)) {
-      body.on('error', er => {
-        const error = er.name === 'AbortError' ? er
-          : new FetchError(`Invalid response while trying to fetch ${
-            this.url}: ${er.message}`, 'system', er)
-        this[INTERNALS].error = error
-      })
+    // at this point the chunk is a buffer or string
+    // don't buffer it up or send it to the decoder
+    if (!chunk.length) {
+      if (this[BUFFERLENGTH] !== 0)
+        this.emit('readable')
+      if (cb)
+        fn(cb)
+      return this.flowing
     }
-  }
 
-  get body () {
-    return this[INTERNALS].body
-  }
+    // fast-path writing strings of same encoding to a stream with
+    // an empty buffer, skipping the buffer/decoder dance
+    if (typeof chunk === 'string' &&
+        // unless it is a string already ready for us to use
+        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
+      chunk = Buffer.from(chunk, encoding)
+    }
 
-  get bodyUsed () {
-    return this[INTERNALS].disturbed
-  }
+    if (Buffer.isBuffer(chunk) && this[ENCODING])
+      chunk = this[DECODER].write(chunk)
 
-  arrayBuffer () {
-    return this[CONSUME_BODY]().then(buf =>
-      buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
-  }
+    // Note: flushing CAN potentially switch us into not-flowing mode
+    if (this.flowing && this[BUFFERLENGTH] !== 0)
+      this[FLUSH](true)
 
-  blob () {
-    const ct = this.headers && this.headers.get('content-type') || ''
-    return this[CONSUME_BODY]().then(buf => Object.assign(
-      new Blob([], { type: ct.toLowerCase() }),
-      { [BUFFER]: buf }
-    ))
-  }
+    if (this.flowing)
+      this.emit('data', chunk)
+    else
+      this[BUFFERPUSH](chunk)
 
-  async json () {
-    const buf = await this[CONSUME_BODY]()
-    try {
-      return JSON.parse(buf.toString())
-    } catch (er) {
-      throw new FetchError(
-        `invalid json response body at ${this.url} reason: ${er.message}`,
-        'invalid-json'
-      )
-    }
-  }
+    if (this[BUFFERLENGTH] !== 0)
+      this.emit('readable')
 
-  text () {
-    return this[CONSUME_BODY]().then(buf => buf.toString())
-  }
+    if (cb)
+      fn(cb)
 
-  buffer () {
-    return this[CONSUME_BODY]()
+    return this.flowing
   }
 
-  textConverted () {
-    return this[CONSUME_BODY]().then(buf => convertBody(buf, this.headers))
-  }
+  read (n) {
+    if (this[DESTROYED])
+      return null
 
-  [CONSUME_BODY] () {
-    if (this[INTERNALS].disturbed) {
-      return Promise.reject(new TypeError(`body used already for: ${
-        this.url}`))
+    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
+      this[MAYBE_EMIT_END]()
+      return null
     }
 
-    this[INTERNALS].disturbed = true
+    if (this[OBJECTMODE])
+      n = null
 
-    if (this[INTERNALS].error) {
-      return Promise.reject(this[INTERNALS].error)
+    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
+      if (this.encoding)
+        this.buffer = [this.buffer.join('')]
+      else
+        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
     }
 
-    // body is null
-    if (this.body === null) {
-      return Promise.resolve(Buffer.alloc(0))
-    }
+    const ret = this[READ](n || null, this.buffer[0])
+    this[MAYBE_EMIT_END]()
+    return ret
+  }
 
-    if (Buffer.isBuffer(this.body)) {
-      return Promise.resolve(this.body)
+  [READ] (n, chunk) {
+    if (n === chunk.length || n === null)
+      this[BUFFERSHIFT]()
+    else {
+      this.buffer[0] = chunk.slice(n)
+      chunk = chunk.slice(0, n)
+      this[BUFFERLENGTH] -= n
     }
 
-    const upstream = isBlob(this.body) ? this.body.stream() : this.body
+    this.emit('data', chunk)
 
-    /* istanbul ignore if: should never happen */
-    if (!Minipass.isStream(upstream)) {
-      return Promise.resolve(Buffer.alloc(0))
-    }
+    if (!this.buffer.length && !this[EOF])
+      this.emit('drain')
 
-    const stream = this.size && upstream instanceof MinipassSized ? upstream
-      : !this.size && upstream instanceof Minipass &&
-        !(upstream instanceof MinipassSized) ? upstream
-      : this.size ? new MinipassSized({ size: this.size })
-      : new Minipass()
+    return chunk
+  }
 
-    // allow timeout on slow response body, but only if the stream is still writable. this
-    // makes the timeout center on the socket stream from lib/index.js rather than the
-    // intermediary minipass stream we create to receive the data
-    const resTimeout = this.timeout && stream.writable ? setTimeout(() => {
-      stream.emit('error', new FetchError(
-        `Response timeout while trying to fetch ${
-          this.url} (over ${this.timeout}ms)`, 'body-timeout'))
-    }, this.timeout) : null
+  end (chunk, encoding, cb) {
+    if (typeof chunk === 'function')
+      cb = chunk, chunk = null
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
+    if (chunk)
+      this.write(chunk, encoding)
+    if (cb)
+      this.once('end', cb)
+    this[EOF] = true
+    this.writable = false
 
-    // do not keep the process open just for this timeout, even
-    // though we expect it'll get cleared eventually.
-    if (resTimeout && resTimeout.unref) {
-      resTimeout.unref()
-    }
+    // if we haven't written anything, then go ahead and emit,
+    // even if we're not reading.
+    // we'll re-emit if a new 'end' listener is added anyway.
+    // This makes MP more suitable to write-only use cases.
+    if (this.flowing || !this[PAUSED])
+      this[MAYBE_EMIT_END]()
+    return this
+  }
 
-    // do the pipe in the promise, because the pipe() can send too much
-    // data through right away and upset the MP Sized object
-    return new Promise((resolve) => {
-      // if the stream is some other kind of stream, then pipe through a MP
-      // so we can collect it more easily.
-      if (stream !== upstream) {
-        upstream.on('error', er => stream.emit('error', er))
-        upstream.pipe(stream)
-      }
-      resolve()
-    }).then(() => stream.concat()).then(buf => {
-      clearTimeout(resTimeout)
-      return buf
-    }).catch(er => {
-      clearTimeout(resTimeout)
-      // request was aborted, reject with this Error
-      if (er.name === 'AbortError' || er.name === 'FetchError') {
-        throw er
-      } else if (er.name === 'RangeError') {
-        throw new FetchError(`Could not create Buffer from response body for ${
-          this.url}: ${er.message}`, 'system', er)
-      } else {
-        // other errors, such as incorrect content-encoding or content-length
-        throw new FetchError(`Invalid response body while trying to fetch ${
-          this.url}: ${er.message}`, 'system', er)
-      }
-    })
+  // don't let the internal resume be overwritten
+  [RESUME] () {
+    if (this[DESTROYED])
+      return
+
+    this[PAUSED] = false
+    this[FLOWING] = true
+    this.emit('resume')
+    if (this.buffer.length)
+      this[FLUSH]()
+    else if (this[EOF])
+      this[MAYBE_EMIT_END]()
+    else
+      this.emit('drain')
+  }
+
+  resume () {
+    return this[RESUME]()
   }
 
-  static clone (instance) {
-    if (instance.bodyUsed) {
-      throw new Error('cannot clone body after it is used')
-    }
+  pause () {
+    this[FLOWING] = false
+    this[PAUSED] = true
+  }
 
-    const body = instance.body
+  get destroyed () {
+    return this[DESTROYED]
+  }
 
-    // check that body is a stream and not form-data object
-    // NB: can't clone the form-data object without having it as a dependency
-    if (Minipass.isStream(body) && typeof body.getBoundary !== 'function') {
-      // create a dedicated tee stream so that we don't lose data
-      // potentially sitting in the body stream's buffer by writing it
-      // immediately to p1 and not having it for p2.
-      const tee = new Minipass()
-      const p1 = new Minipass()
-      const p2 = new Minipass()
-      tee.on('error', er => {
-        p1.emit('error', er)
-        p2.emit('error', er)
-      })
-      body.on('error', er => tee.emit('error', er))
-      tee.pipe(p1)
-      tee.pipe(p2)
-      body.pipe(tee)
-      // set instance body to one fork, return the other
-      instance[INTERNALS].body = p1
-      return p2
-    } else {
-      return instance.body
+  get flowing () {
+    return this[FLOWING]
+  }
+
+  get paused () {
+    return this[PAUSED]
+  }
+
+  [BUFFERPUSH] (chunk) {
+    if (this[OBJECTMODE])
+      this[BUFFERLENGTH] += 1
+    else
+      this[BUFFERLENGTH] += chunk.length
+    this.buffer.push(chunk)
+  }
+
+  [BUFFERSHIFT] () {
+    if (this.buffer.length) {
+      if (this[OBJECTMODE])
+        this[BUFFERLENGTH] -= 1
+      else
+        this[BUFFERLENGTH] -= this.buffer[0].length
     }
+    return this.buffer.shift()
   }
 
-  static extractContentType (body) {
-    return body === null || body === undefined ? null
-      : typeof body === 'string' ? 'text/plain;charset=UTF-8'
-      : isURLSearchParams(body)
-        ? 'application/x-www-form-urlencoded;charset=UTF-8'
-        : isBlob(body) ? body.type || null
-        : Buffer.isBuffer(body) ? null
-        : Object.prototype.toString.call(body) === '[object ArrayBuffer]' ? null
-        : ArrayBuffer.isView(body) ? null
-        : typeof body.getBoundary === 'function'
-          ? `multipart/form-data;boundary=${body.getBoundary()}`
-          : Minipass.isStream(body) ? null
-          : 'text/plain;charset=UTF-8'
+  [FLUSH] (noDrain) {
+    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
+
+    if (!noDrain && !this.buffer.length && !this[EOF])
+      this.emit('drain')
   }
 
-  static getTotalBytes (instance) {
-    const { body } = instance
-    return (body === null || body === undefined) ? 0
-      : isBlob(body) ? body.size
-      : Buffer.isBuffer(body) ? body.length
-      : body && typeof body.getLengthSync === 'function' && (
-        // detect form data input from form-data module
-        body._lengthRetrievers &&
-        /* istanbul ignore next */ body._lengthRetrievers.length === 0 || // 1.x
-        body.hasKnownLength && body.hasKnownLength()) // 2.x
-        ? body.getLengthSync()
-        : null
+  [FLUSHCHUNK] (chunk) {
+    return chunk ? (this.emit('data', chunk), this.flowing) : false
   }
 
-  static writeToStream (dest, instance) {
-    const { body } = instance
+  pipe (dest, opts) {
+    if (this[DESTROYED])
+      return
 
-    if (body === null || body === undefined) {
-      dest.end()
-    } else if (Buffer.isBuffer(body) || typeof body === 'string') {
-      dest.end(body)
+    const ended = this[EMITTED_END]
+    opts = opts || {}
+    if (dest === proc.stdout || dest === proc.stderr)
+      opts.end = false
+    else
+      opts.end = opts.end !== false
+    opts.proxyErrors = !!opts.proxyErrors
+
+    // piping an ended stream ends immediately
+    if (ended) {
+      if (opts.end)
+        dest.end()
     } else {
-      // body is stream or blob
-      const stream = isBlob(body) ? body.stream() : body
-      stream.on('error', er => dest.emit('error', er)).pipe(dest)
+      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
+        : new PipeProxyErrors(this, dest, opts))
+      if (this[ASYNC])
+        defer(() => this[RESUME]())
+      else
+        this[RESUME]()
     }
 
     return dest
   }
-}
-
-Object.defineProperties(Body.prototype, {
-  body: { enumerable: true },
-  bodyUsed: { enumerable: true },
-  arrayBuffer: { enumerable: true },
-  blob: { enumerable: true },
-  json: { enumerable: true },
-  text: { enumerable: true },
-})
 
-const isURLSearchParams = obj =>
-  // Duck-typing as a necessary condition.
-  (typeof obj !== 'object' ||
-    typeof obj.append !== 'function' ||
-    typeof obj.delete !== 'function' ||
-    typeof obj.get !== 'function' ||
-    typeof obj.getAll !== 'function' ||
-    typeof obj.has !== 'function' ||
-    typeof obj.set !== 'function') ? false
-  // Brand-checking and more duck-typing as optional condition.
-  : obj.constructor.name === 'URLSearchParams' ||
-    Object.prototype.toString.call(obj) === '[object URLSearchParams]' ||
-    typeof obj.sort === 'function'
+  unpipe (dest) {
+    const p = this.pipes.find(p => p.dest === dest)
+    if (p) {
+      this.pipes.splice(this.pipes.indexOf(p), 1)
+      p.unpipe()
+    }
+  }
 
-const isBlob = obj =>
-  typeof obj === 'object' &&
-  typeof obj.arrayBuffer === 'function' &&
-  typeof obj.type === 'string' &&
-  typeof obj.stream === 'function' &&
-  typeof obj.constructor === 'function' &&
-  typeof obj.constructor.name === 'string' &&
-  /^(Blob|File)$/.test(obj.constructor.name) &&
-  /^(Blob|File)$/.test(obj[Symbol.toStringTag])
+  addListener (ev, fn) {
+    return this.on(ev, fn)
+  }
 
-const convertBody = (buffer, headers) => {
-  /* istanbul ignore if */
-  if (typeof convert !== 'function') {
-    throw new Error('The package `encoding` must be installed to use the textConverted() function')
+  on (ev, fn) {
+    const ret = super.on(ev, fn)
+    if (ev === 'data' && !this.pipes.length && !this.flowing)
+      this[RESUME]()
+    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
+      super.emit('readable')
+    else if (isEndish(ev) && this[EMITTED_END]) {
+      super.emit(ev)
+      this.removeAllListeners(ev)
+    } else if (ev === 'error' && this[EMITTED_ERROR]) {
+      if (this[ASYNC])
+        defer(() => fn.call(this, this[EMITTED_ERROR]))
+      else
+        fn.call(this, this[EMITTED_ERROR])
+    }
+    return ret
   }
 
-  const ct = headers && headers.get('content-type')
-  let charset = 'utf-8'
-  let res
+  get emittedEnd () {
+    return this[EMITTED_END]
+  }
 
-  // header
-  if (ct) {
-    res = /charset=([^;]*)/i.exec(ct)
+  [MAYBE_EMIT_END] () {
+    if (!this[EMITTING_END] &&
+        !this[EMITTED_END] &&
+        !this[DESTROYED] &&
+        this.buffer.length === 0 &&
+        this[EOF]) {
+      this[EMITTING_END] = true
+      this.emit('end')
+      this.emit('prefinish')
+      this.emit('finish')
+      if (this[CLOSED])
+        this.emit('close')
+      this[EMITTING_END] = false
+    }
   }
 
-  // no charset in content type, peek at response body for at most 1024 bytes
-  const str = buffer.slice(0, 1024).toString()
+  emit (ev, data, ...extra) {
+    // error and close are only events allowed after calling destroy()
+    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
+      return
+    else if (ev === 'data') {
+      return !data ? false
+        : this[ASYNC] ? defer(() => this[EMITDATA](data))
+        : this[EMITDATA](data)
+    } else if (ev === 'end') {
+      return this[EMITEND]()
+    } else if (ev === 'close') {
+      this[CLOSED] = true
+      // don't emit close before 'end' and 'finish'
+      if (!this[EMITTED_END] && !this[DESTROYED])
+        return
+      const ret = super.emit('close')
+      this.removeAllListeners('close')
+      return ret
+    } else if (ev === 'error') {
+      this[EMITTED_ERROR] = data
+      const ret = super.emit('error', data)
+      this[MAYBE_EMIT_END]()
+      return ret
+    } else if (ev === 'resume') {
+      const ret = super.emit('resume')
+      this[MAYBE_EMIT_END]()
+      return ret
+    } else if (ev === 'finish' || ev === 'prefinish') {
+      const ret = super.emit(ev)
+      this.removeAllListeners(ev)
+      return ret
+    }
 
-  // html5
-  if (!res && str) {
-    res = / this[EMITEND2]())
+    else
+      this[EMITEND2]()
+  }
+
+  [EMITEND2] () {
+    if (this[DECODER]) {
+      const data = this[DECODER].end()
+      if (data) {
+        for (const p of this.pipes) {
+          p.dest.write(data)
+        }
+        super.emit('data', data)
+      }
     }
 
-    if (res) {
-      res = /charset=(.*)/i.exec(res.pop())
+    for (const p of this.pipes) {
+      p.end()
     }
+    const ret = super.emit('end')
+    this.removeAllListeners('end')
+    return ret
   }
 
-  // xml
-  if (!res && str) {
-    res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str)
+  // const all = await stream.collect()
+  collect () {
+    const buf = []
+    if (!this[OBJECTMODE])
+      buf.dataLength = 0
+    // set the promise first, in case an error is raised
+    // by triggering the flow here.
+    const p = this.promise()
+    this.on('data', c => {
+      buf.push(c)
+      if (!this[OBJECTMODE])
+        buf.dataLength += c.length
+    })
+    return p.then(() => buf)
   }
 
-  // found charset
-  if (res) {
-    charset = res.pop()
+  // const data = await stream.concat()
+  concat () {
+    return this[OBJECTMODE]
+      ? Promise.reject(new Error('cannot concat in objectMode'))
+      : this.collect().then(buf =>
+          this[OBJECTMODE]
+            ? Promise.reject(new Error('cannot concat in objectMode'))
+            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
+  }
 
-    // prevent decode issues when sites use incorrect encoding
-    // ref: https://hsivonen.fi/encoding-menu/
-    if (charset === 'gb2312' || charset === 'gbk') {
-      charset = 'gb18030'
-    }
+  // stream.promise().then(() => done, er => emitted error)
+  promise () {
+    return new Promise((resolve, reject) => {
+      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
+      this.on('error', er => reject(er))
+      this.on('end', () => resolve())
+    })
   }
 
-  // turn raw buffers into a single utf-8 buffer
-  return convert(
-    buffer,
-    'UTF-8',
-    charset
-  ).toString()
-}
+  // for await (let chunk of stream)
+  [ASYNCITERATOR] () {
+    const next = () => {
+      const res = this.read()
+      if (res !== null)
+        return Promise.resolve({ done: false, value: res })
 
-module.exports = Body
+      if (this[EOF])
+        return Promise.resolve({ done: true })
 
+      let resolve = null
+      let reject = null
+      const onerr = er => {
+        this.removeListener('data', ondata)
+        this.removeListener('end', onend)
+        reject(er)
+      }
+      const ondata = value => {
+        this.removeListener('error', onerr)
+        this.removeListener('end', onend)
+        this.pause()
+        resolve({ value: value, done: !!this[EOF] })
+      }
+      const onend = () => {
+        this.removeListener('error', onerr)
+        this.removeListener('data', ondata)
+        resolve({ done: true })
+      }
+      const ondestroy = () => onerr(new Error('stream destroyed'))
+      return new Promise((res, rej) => {
+        reject = rej
+        resolve = res
+        this.once(DESTROYED, ondestroy)
+        this.once('error', onerr)
+        this.once('end', onend)
+        this.once('data', ondata)
+      })
+    }
 
-/***/ }),
+    return { next }
+  }
 
-/***/ 22644:
-/***/ ((module) => {
+  // for (let chunk of stream)
+  [ITERATOR] () {
+    const next = () => {
+      const value = this.read()
+      const done = value === null
+      return { value, done }
+    }
+    return { next }
+  }
 
-"use strict";
+  destroy (er) {
+    if (this[DESTROYED]) {
+      if (er)
+        this.emit('error', er)
+      else
+        this.emit(DESTROYED)
+      return this
+    }
 
-class FetchError extends Error {
-  constructor (message, type, systemError) {
-    super(message)
-    this.code = 'FETCH_ERROR'
+    this[DESTROYED] = true
 
-    // pick up code, expected, path, ...
-    if (systemError) {
-      Object.assign(this, systemError)
-    }
+    // throw away all buffered data, it's never coming out
+    this.buffer.length = 0
+    this[BUFFERLENGTH] = 0
 
-    this.errno = this.code
+    if (typeof this.close === 'function' && !this[CLOSED])
+      this.close()
 
-    // override anything the system error might've clobbered
-    this.type = this.code === 'EBADSIZE' && this.found > this.expect
-      ? 'max-size' : type
-    this.message = message
-    Error.captureStackTrace(this, this.constructor)
-  }
+    if (er)
+      this.emit('error', er)
+    else // if no error to emit, still reject pending promises
+      this.emit(DESTROYED)
 
-  get name () {
-    return 'FetchError'
+    return this
   }
 
-  // don't allow name to be overwritten
-  set name (n) {}
-
-  get [Symbol.toStringTag] () {
-    return 'FetchError'
+  static isStream (s) {
+    return !!s && (s instanceof Minipass || s instanceof Stream ||
+      s instanceof EE && (
+        typeof s.pipe === 'function' || // readable
+        (typeof s.write === 'function' && typeof s.end === 'function') // writable
+      ))
   }
 }
-module.exports = FetchError
 
 
 /***/ }),
 
-/***/ 98645:
-/***/ ((module) => {
-
-"use strict";
+/***/ 48484:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-const invalidTokenRegex = /[^^_`a-zA-Z\-0-9!#$%&'*+.|~]/
-const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+const Minipass = __nccwpck_require__(56670)
 
-const validateName = name => {
-  name = `${name}`
-  if (invalidTokenRegex.test(name) || name === '') {
-    throw new TypeError(`${name} is not a legal HTTP header name`)
+class SizeError extends Error {
+  constructor (found, expect) {
+    super(`Bad data size: expected ${expect} bytes, but got ${found}`)
+    this.expect = expect
+    this.found = found
+    this.code = 'EBADSIZE'
+	  Error.captureStackTrace(this, this.constructor)
+  }
+  get name () {
+    return 'SizeError'
   }
 }
 
-const validateValue = value => {
-  value = `${value}`
-  if (invalidHeaderCharRegex.test(value)) {
-    throw new TypeError(`${value} is not a legal HTTP header value`)
+class MinipassSized extends Minipass {
+  constructor (options = {}) {
+    super(options)
+
+    if (options.objectMode)
+      throw new TypeError(`${
+        this.constructor.name
+      } streams only work with string and buffer data`)
+
+    this.found = 0
+    this.expect = options.size
+    if (typeof this.expect !== 'number' ||
+        this.expect > Number.MAX_SAFE_INTEGER ||
+        isNaN(this.expect) ||
+        this.expect < 0 ||
+        !isFinite(this.expect) ||
+        this.expect !== Math.floor(this.expect))
+      throw new Error('invalid expected size: ' + this.expect)
   }
-}
 
-const find = (map, name) => {
-  name = name.toLowerCase()
-  for (const key in map) {
-    if (key.toLowerCase() === name) {
-      return key
+  write (chunk, encoding, cb) {
+    const buffer = Buffer.isBuffer(chunk) ? chunk
+      : typeof chunk === 'string' ?
+        Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8')
+      : chunk
+
+    if (!Buffer.isBuffer(buffer)) {
+      this.emit('error', new TypeError(`${
+        this.constructor.name
+      } streams only work with string and buffer data`))
+      return false
+    }
+
+    this.found += buffer.length
+    if (this.found > this.expect)
+      this.emit('error', new SizeError(this.found, this.expect))
+
+    return super.write(chunk, encoding, cb)
+  }
+
+  emit (ev, ...data) {
+    if (ev === 'end') {
+      if (this.found !== this.expect)
+        this.emit('error', new SizeError(this.found, this.expect))
     }
+    return super.emit(ev, ...data)
   }
-  return undefined
 }
 
-const MAP = Symbol('map')
-class Headers {
-  constructor (init = undefined) {
-    this[MAP] = Object.create(null)
-    if (init instanceof Headers) {
-      const rawHeaders = init.raw()
-      const headerNames = Object.keys(rawHeaders)
-      for (const headerName of headerNames) {
-        for (const value of rawHeaders[headerName]) {
-          this.append(headerName, value)
-        }
-      }
-      return
-    }
+MinipassSized.SizeError = SizeError
 
-    // no-op
-    if (init === undefined || init === null) {
-      return
-    }
+module.exports = MinipassSized
 
-    if (typeof init === 'object') {
-      const method = init[Symbol.iterator]
-      if (method !== null && method !== undefined) {
-        if (typeof method !== 'function') {
-          throw new TypeError('Header pairs must be iterable')
-        }
 
-        // sequence>
-        // Note: per spec we have to first exhaust the lists then process them
-        const pairs = []
-        for (const pair of init) {
-          if (typeof pair !== 'object' ||
-              typeof pair[Symbol.iterator] !== 'function') {
-            throw new TypeError('Each header pair must be iterable')
-          }
-          const arrPair = Array.from(pair)
-          if (arrPair.length !== 2) {
-            throw new TypeError('Each header pair must be a name/value tuple')
-          }
-          pairs.push(arrPair)
-        }
+/***/ }),
 
-        for (const pair of pairs) {
-          this.append(pair[0], pair[1])
-        }
-      } else {
-        // record
-        for (const key of Object.keys(init)) {
-          this.append(key, init[key])
-        }
-      }
-    } else {
-      throw new TypeError('Provided initializer must be an object')
-    }
-  }
+/***/ 56670:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  get (name) {
-    name = `${name}`
-    validateName(name)
-    const key = find(this[MAP], name)
-    if (key === undefined) {
-      return null
-    }
+"use strict";
 
-    return this[MAP][key].join(', ')
-  }
+const proc = typeof process === 'object' && process ? process : {
+  stdout: null,
+  stderr: null,
+}
+const EE = __nccwpck_require__(24434)
+const Stream = __nccwpck_require__(2203)
+const SD = (__nccwpck_require__(13193).StringDecoder)
 
-  forEach (callback, thisArg = undefined) {
-    let pairs = getHeaders(this)
-    for (let i = 0; i < pairs.length; i++) {
-      const [name, value] = pairs[i]
-      callback.call(thisArg, value, name, this)
-      // refresh in case the callback added more headers
-      pairs = getHeaders(this)
-    }
-  }
+const EOF = Symbol('EOF')
+const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
+const EMITTED_END = Symbol('emittedEnd')
+const EMITTING_END = Symbol('emittingEnd')
+const EMITTED_ERROR = Symbol('emittedError')
+const CLOSED = Symbol('closed')
+const READ = Symbol('read')
+const FLUSH = Symbol('flush')
+const FLUSHCHUNK = Symbol('flushChunk')
+const ENCODING = Symbol('encoding')
+const DECODER = Symbol('decoder')
+const FLOWING = Symbol('flowing')
+const PAUSED = Symbol('paused')
+const RESUME = Symbol('resume')
+const BUFFERLENGTH = Symbol('bufferLength')
+const BUFFERPUSH = Symbol('bufferPush')
+const BUFFERSHIFT = Symbol('bufferShift')
+const OBJECTMODE = Symbol('objectMode')
+const DESTROYED = Symbol('destroyed')
+const EMITDATA = Symbol('emitData')
+const EMITEND = Symbol('emitEnd')
+const EMITEND2 = Symbol('emitEnd2')
+const ASYNC = Symbol('async')
 
-  set (name, value) {
-    name = `${name}`
-    value = `${value}`
-    validateName(name)
-    validateValue(value)
-    const key = find(this[MAP], name)
-    this[MAP][key !== undefined ? key : name] = [value]
-  }
+const defer = fn => Promise.resolve().then(fn)
 
-  append (name, value) {
-    name = `${name}`
-    value = `${value}`
-    validateName(name)
-    validateValue(value)
-    const key = find(this[MAP], name)
-    if (key !== undefined) {
-      this[MAP][key].push(value)
-    } else {
-      this[MAP][name] = [value]
-    }
-  }
+// TODO remove when Node v8 support drops
+const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
+const ASYNCITERATOR = doIter && Symbol.asyncIterator
+  || Symbol('asyncIterator not implemented')
+const ITERATOR = doIter && Symbol.iterator
+  || Symbol('iterator not implemented')
 
-  has (name) {
-    name = `${name}`
-    validateName(name)
-    return find(this[MAP], name) !== undefined
-  }
+// events that mean 'the stream is over'
+// these are treated specially, and re-emitted
+// if they are listened for after emitting.
+const isEndish = ev =>
+  ev === 'end' ||
+  ev === 'finish' ||
+  ev === 'prefinish'
 
-  delete (name) {
-    name = `${name}`
-    validateName(name)
-    const key = find(this[MAP], name)
-    if (key !== undefined) {
-      delete this[MAP][key]
-    }
-  }
+const isArrayBuffer = b => b instanceof ArrayBuffer ||
+  typeof b === 'object' &&
+  b.constructor &&
+  b.constructor.name === 'ArrayBuffer' &&
+  b.byteLength >= 0
 
-  raw () {
-    return this[MAP]
-  }
+const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
 
-  keys () {
-    return new HeadersIterator(this, 'key')
+class Pipe {
+  constructor (src, dest, opts) {
+    this.src = src
+    this.dest = dest
+    this.opts = opts
+    this.ondrain = () => src[RESUME]()
+    dest.on('drain', this.ondrain)
   }
-
-  values () {
-    return new HeadersIterator(this, 'value')
+  unpipe () {
+    this.dest.removeListener('drain', this.ondrain)
   }
-
-  [Symbol.iterator] () {
-    return new HeadersIterator(this, 'key+value')
+  // istanbul ignore next - only here for the prototype
+  proxyErrors () {}
+  end () {
+    this.unpipe()
+    if (this.opts.end)
+      this.dest.end()
   }
+}
 
-  entries () {
-    return new HeadersIterator(this, 'key+value')
+class PipeProxyErrors extends Pipe {
+  unpipe () {
+    this.src.removeListener('error', this.proxyErrors)
+    super.unpipe()
+  }
+  constructor (src, dest, opts) {
+    super(src, dest, opts)
+    this.proxyErrors = er => dest.emit('error', er)
+    src.on('error', this.proxyErrors)
   }
+}
 
-  get [Symbol.toStringTag] () {
-    return 'Headers'
+module.exports = class Minipass extends Stream {
+  constructor (options) {
+    super()
+    this[FLOWING] = false
+    // whether we're explicitly paused
+    this[PAUSED] = false
+    this.pipes = []
+    this.buffer = []
+    this[OBJECTMODE] = options && options.objectMode || false
+    if (this[OBJECTMODE])
+      this[ENCODING] = null
+    else
+      this[ENCODING] = options && options.encoding || null
+    if (this[ENCODING] === 'buffer')
+      this[ENCODING] = null
+    this[ASYNC] = options && !!options.async || false
+    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
+    this[EOF] = false
+    this[EMITTED_END] = false
+    this[EMITTING_END] = false
+    this[CLOSED] = false
+    this[EMITTED_ERROR] = null
+    this.writable = true
+    this.readable = true
+    this[BUFFERLENGTH] = 0
+    this[DESTROYED] = false
   }
 
-  static exportNodeCompatibleHeaders (headers) {
-    const obj = Object.assign(Object.create(null), headers[MAP])
+  get bufferLength () { return this[BUFFERLENGTH] }
 
-    // http.request() only supports string as Host header. This hack makes
-    // specifying custom Host header possible.
-    const hostHeaderKey = find(headers[MAP], 'Host')
-    if (hostHeaderKey !== undefined) {
-      obj[hostHeaderKey] = obj[hostHeaderKey][0]
+  get encoding () { return this[ENCODING] }
+  set encoding (enc) {
+    if (this[OBJECTMODE])
+      throw new Error('cannot set encoding in objectMode')
+
+    if (this[ENCODING] && enc !== this[ENCODING] &&
+        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
+      throw new Error('cannot change encoding')
+
+    if (this[ENCODING] !== enc) {
+      this[DECODER] = enc ? new SD(enc) : null
+      if (this.buffer.length)
+        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
     }
 
-    return obj
+    this[ENCODING] = enc
   }
 
-  static createHeadersLenient (obj) {
-    const headers = new Headers()
-    for (const name of Object.keys(obj)) {
-      if (invalidTokenRegex.test(name)) {
-        continue
-      }
+  setEncoding (enc) {
+    this.encoding = enc
+  }
 
-      if (Array.isArray(obj[name])) {
-        for (const val of obj[name]) {
-          if (invalidHeaderCharRegex.test(val)) {
-            continue
-          }
+  get objectMode () { return this[OBJECTMODE] }
+  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
 
-          if (headers[MAP][name] === undefined) {
-            headers[MAP][name] = [val]
-          } else {
-            headers[MAP][name].push(val)
-          }
-        }
-      } else if (!invalidHeaderCharRegex.test(obj[name])) {
-        headers[MAP][name] = [obj[name]]
-      }
+  get ['async'] () { return this[ASYNC] }
+  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }
+
+  write (chunk, encoding, cb) {
+    if (this[EOF])
+      throw new Error('write after end')
+
+    if (this[DESTROYED]) {
+      this.emit('error', Object.assign(
+        new Error('Cannot call write after a stream was destroyed'),
+        { code: 'ERR_STREAM_DESTROYED' }
+      ))
+      return true
     }
-    return headers
-  }
-}
 
-Object.defineProperties(Headers.prototype, {
-  get: { enumerable: true },
-  forEach: { enumerable: true },
-  set: { enumerable: true },
-  append: { enumerable: true },
-  has: { enumerable: true },
-  delete: { enumerable: true },
-  keys: { enumerable: true },
-  values: { enumerable: true },
-  entries: { enumerable: true },
-})
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
 
-const getHeaders = (headers, kind = 'key+value') =>
-  Object.keys(headers[MAP]).sort().map(
-    kind === 'key' ? k => k.toLowerCase()
-    : kind === 'value' ? k => headers[MAP][k].join(', ')
-    : k => [k.toLowerCase(), headers[MAP][k].join(', ')]
-  )
+    if (!encoding)
+      encoding = 'utf8'
 
-const INTERNAL = Symbol('internal')
+    const fn = this[ASYNC] ? defer : f => f()
 
-class HeadersIterator {
-  constructor (target, kind) {
-    this[INTERNAL] = {
-      target,
-      kind,
-      index: 0,
+    // convert array buffers and typed array views into buffers
+    // at some point in the future, we may want to do the opposite!
+    // leave strings and buffers as-is
+    // anything else switches us into object mode
+    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+      if (isArrayBufferView(chunk))
+        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
+      else if (isArrayBuffer(chunk))
+        chunk = Buffer.from(chunk)
+      else if (typeof chunk !== 'string')
+        // use the setter so we throw if we have encoding set
+        this.objectMode = true
     }
-  }
 
-  get [Symbol.toStringTag] () {
-    return 'HeadersIterator'
-  }
+    // handle object mode up front, since it's simpler
+    // this yields better performance, fewer checks later.
+    if (this[OBJECTMODE]) {
+      /* istanbul ignore if - maybe impossible? */
+      if (this.flowing && this[BUFFERLENGTH] !== 0)
+        this[FLUSH](true)
 
-  next () {
-    /* istanbul ignore if: should be impossible */
-    if (!this || Object.getPrototypeOf(this) !== HeadersIterator.prototype) {
-      throw new TypeError('Value of `this` is not a HeadersIterator')
-    }
+      if (this.flowing)
+        this.emit('data', chunk)
+      else
+        this[BUFFERPUSH](chunk)
 
-    const { target, kind, index } = this[INTERNAL]
-    const values = getHeaders(target, kind)
-    const len = values.length
-    if (index >= len) {
-      return {
-        value: undefined,
-        done: true,
-      }
+      if (this[BUFFERLENGTH] !== 0)
+        this.emit('readable')
+
+      if (cb)
+        fn(cb)
+
+      return this.flowing
     }
 
-    this[INTERNAL].index++
+    // at this point the chunk is a buffer or string
+    // don't buffer it up or send it to the decoder
+    if (!chunk.length) {
+      if (this[BUFFERLENGTH] !== 0)
+        this.emit('readable')
+      if (cb)
+        fn(cb)
+      return this.flowing
+    }
 
-    return { value: values[index], done: false }
-  }
-}
+    // fast-path writing strings of same encoding to a stream with
+    // an empty buffer, skipping the buffer/decoder dance
+    if (typeof chunk === 'string' &&
+        // unless it is a string already ready for us to use
+        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
+      chunk = Buffer.from(chunk, encoding)
+    }
 
-// manually extend because 'extends' requires a ctor
-Object.setPrototypeOf(HeadersIterator.prototype,
-  Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())))
+    if (Buffer.isBuffer(chunk) && this[ENCODING])
+      chunk = this[DECODER].write(chunk)
 
-module.exports = Headers
+    // Note: flushing CAN potentially switch us into not-flowing mode
+    if (this.flowing && this[BUFFERLENGTH] !== 0)
+      this[FLUSH](true)
 
+    if (this.flowing)
+      this.emit('data', chunk)
+    else
+      this[BUFFERPUSH](chunk)
 
-/***/ }),
+    if (this[BUFFERLENGTH] !== 0)
+      this.emit('readable')
 
-/***/ 88483:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    if (cb)
+      fn(cb)
 
-"use strict";
+    return this.flowing
+  }
 
-const { URL } = __nccwpck_require__(87016)
-const http = __nccwpck_require__(58611)
-const https = __nccwpck_require__(65692)
-const zlib = __nccwpck_require__(37119)
-const { Minipass } = __nccwpck_require__(78275)
+  read (n) {
+    if (this[DESTROYED])
+      return null
 
-const Body = __nccwpck_require__(28515)
-const { writeToStream, getTotalBytes } = Body
-const Response = __nccwpck_require__(43852)
-const Headers = __nccwpck_require__(98645)
-const { createHeadersLenient } = Headers
-const Request = __nccwpck_require__(99586)
-const { getNodeRequestOptions } = Request
-const FetchError = __nccwpck_require__(22644)
-const AbortError = __nccwpck_require__(57442)
+    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
+      this[MAYBE_EMIT_END]()
+      return null
+    }
 
-// XXX this should really be split up and unit-ized for easier testing
-// and better DRY implementation of data/http request aborting
-const fetch = async (url, opts) => {
-  if (/^data:/.test(url)) {
-    const request = new Request(url, opts)
-    // delay 1 promise tick so that the consumer can abort right away
-    return Promise.resolve().then(() => new Promise((resolve, reject) => {
-      let type, data
-      try {
-        const { pathname, search } = new URL(url)
-        const split = pathname.split(',')
-        if (split.length < 2) {
-          throw new Error('invalid data: URI')
-        }
-        const mime = split.shift()
-        const base64 = /;base64$/.test(mime)
-        type = base64 ? mime.slice(0, -1 * ';base64'.length) : mime
-        const rawData = decodeURIComponent(split.join(',') + search)
-        data = base64 ? Buffer.from(rawData, 'base64') : Buffer.from(rawData)
-      } catch (er) {
-        return reject(new FetchError(`[${request.method}] ${
-          request.url} invalid URL, ${er.message}`, 'system', er))
-      }
+    if (this[OBJECTMODE])
+      n = null
 
-      const { signal } = request
-      if (signal && signal.aborted) {
-        return reject(new AbortError('The user aborted a request.'))
-      }
+    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
+      if (this.encoding)
+        this.buffer = [this.buffer.join('')]
+      else
+        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
+    }
 
-      const headers = { 'Content-Length': data.length }
-      if (type) {
-        headers['Content-Type'] = type
-      }
-      return resolve(new Response(data, { headers }))
-    }))
+    const ret = this[READ](n || null, this.buffer[0])
+    this[MAYBE_EMIT_END]()
+    return ret
   }
 
-  return new Promise((resolve, reject) => {
-    // build request object
-    const request = new Request(url, opts)
-    let options
-    try {
-      options = getNodeRequestOptions(request)
-    } catch (er) {
-      return reject(er)
+  [READ] (n, chunk) {
+    if (n === chunk.length || n === null)
+      this[BUFFERSHIFT]()
+    else {
+      this.buffer[0] = chunk.slice(n)
+      chunk = chunk.slice(0, n)
+      this[BUFFERLENGTH] -= n
     }
 
-    const send = (options.protocol === 'https:' ? https : http).request
-    const { signal } = request
-    let response = null
-    const abort = () => {
-      const error = new AbortError('The user aborted a request.')
-      reject(error)
-      if (Minipass.isStream(request.body) &&
-          typeof request.body.destroy === 'function') {
-        request.body.destroy(error)
-      }
-      if (response && response.body) {
-        response.body.emit('error', error)
-      }
-    }
+    this.emit('data', chunk)
+
+    if (!this.buffer.length && !this[EOF])
+      this.emit('drain')
+
+    return chunk
+  }
 
-    if (signal && signal.aborted) {
-      return abort()
-    }
+  end (chunk, encoding, cb) {
+    if (typeof chunk === 'function')
+      cb = chunk, chunk = null
+    if (typeof encoding === 'function')
+      cb = encoding, encoding = 'utf8'
+    if (chunk)
+      this.write(chunk, encoding)
+    if (cb)
+      this.once('end', cb)
+    this[EOF] = true
+    this.writable = false
 
-    const abortAndFinalize = () => {
-      abort()
-      finalize()
-    }
+    // if we haven't written anything, then go ahead and emit,
+    // even if we're not reading.
+    // we'll re-emit if a new 'end' listener is added anyway.
+    // This makes MP more suitable to write-only use cases.
+    if (this.flowing || !this[PAUSED])
+      this[MAYBE_EMIT_END]()
+    return this
+  }
 
-    const finalize = () => {
-      req.abort()
-      if (signal) {
-        signal.removeEventListener('abort', abortAndFinalize)
-      }
-      clearTimeout(reqTimeout)
-    }
+  // don't let the internal resume be overwritten
+  [RESUME] () {
+    if (this[DESTROYED])
+      return
 
-    // send request
-    const req = send(options)
+    this[PAUSED] = false
+    this[FLOWING] = true
+    this.emit('resume')
+    if (this.buffer.length)
+      this[FLUSH]()
+    else if (this[EOF])
+      this[MAYBE_EMIT_END]()
+    else
+      this.emit('drain')
+  }
 
-    if (signal) {
-      signal.addEventListener('abort', abortAndFinalize)
-    }
+  resume () {
+    return this[RESUME]()
+  }
 
-    let reqTimeout = null
-    if (request.timeout) {
-      req.once('socket', () => {
-        reqTimeout = setTimeout(() => {
-          reject(new FetchError(`network timeout at: ${
-            request.url}`, 'request-timeout'))
-          finalize()
-        }, request.timeout)
-      })
-    }
+  pause () {
+    this[FLOWING] = false
+    this[PAUSED] = true
+  }
 
-    req.on('error', er => {
-      // if a 'response' event is emitted before the 'error' event, then by the
-      // time this handler is run it's too late to reject the Promise for the
-      // response. instead, we forward the error event to the response stream
-      // so that the error will surface to the user when they try to consume
-      // the body. this is done as a side effect of aborting the request except
-      // for in windows, where we must forward the event manually, otherwise
-      // there is no longer a ref'd socket attached to the request and the
-      // stream never ends so the event loop runs out of work and the process
-      // exits without warning.
-      // coverage skipped here due to the difficulty in testing
-      // istanbul ignore next
-      if (req.res) {
-        req.res.emit('error', er)
-      }
-      reject(new FetchError(`request to ${request.url} failed, reason: ${
-        er.message}`, 'system', er))
-      finalize()
-    })
+  get destroyed () {
+    return this[DESTROYED]
+  }
 
-    req.on('response', res => {
-      clearTimeout(reqTimeout)
+  get flowing () {
+    return this[FLOWING]
+  }
 
-      const headers = createHeadersLenient(res.headers)
+  get paused () {
+    return this[PAUSED]
+  }
 
-      // HTTP fetch step 5
-      if (fetch.isRedirect(res.statusCode)) {
-        // HTTP fetch step 5.2
-        const location = headers.get('Location')
+  [BUFFERPUSH] (chunk) {
+    if (this[OBJECTMODE])
+      this[BUFFERLENGTH] += 1
+    else
+      this[BUFFERLENGTH] += chunk.length
+    this.buffer.push(chunk)
+  }
 
-        // HTTP fetch step 5.3
-        let locationURL = null
-        try {
-          locationURL = location === null ? null : new URL(location, request.url).toString()
-        } catch {
-          // error here can only be invalid URL in Location: header
-          // do not throw when options.redirect == manual
-          // let the user extract the errorneous redirect URL
-          if (request.redirect !== 'manual') {
-            /* eslint-disable-next-line max-len */
-            reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'))
-            finalize()
-            return
-          }
-        }
+  [BUFFERSHIFT] () {
+    if (this.buffer.length) {
+      if (this[OBJECTMODE])
+        this[BUFFERLENGTH] -= 1
+      else
+        this[BUFFERLENGTH] -= this.buffer[0].length
+    }
+    return this.buffer.shift()
+  }
 
-        // HTTP fetch step 5.5
-        if (request.redirect === 'error') {
-          reject(new FetchError('uri requested responds with a redirect, ' +
-            `redirect mode is set to error: ${request.url}`, 'no-redirect'))
-          finalize()
-          return
-        } else if (request.redirect === 'manual') {
-          // node-fetch-specific step: make manual redirect a bit easier to
-          // use by setting the Location header value to the resolved URL.
-          if (locationURL !== null) {
-            // handle corrupted header
-            try {
-              headers.set('Location', locationURL)
-            } catch (err) {
-              /* istanbul ignore next: nodejs server prevent invalid
-                 response headers, we can't test this through normal
-                 request */
-              reject(err)
-            }
-          }
-        } else if (request.redirect === 'follow' && locationURL !== null) {
-          // HTTP-redirect fetch step 5
-          if (request.counter >= request.follow) {
-            reject(new FetchError(`maximum redirect reached at: ${
-              request.url}`, 'max-redirect'))
-            finalize()
-            return
-          }
+  [FLUSH] (noDrain) {
+    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
 
-          // HTTP-redirect fetch step 9
-          if (res.statusCode !== 303 &&
-              request.body &&
-              getTotalBytes(request) === null) {
-            reject(new FetchError(
-              'Cannot follow redirect with body being a readable stream',
-              'unsupported-redirect'
-            ))
-            finalize()
-            return
-          }
+    if (!noDrain && !this.buffer.length && !this[EOF])
+      this.emit('drain')
+  }
 
-          // Update host due to redirection
-          request.headers.set('host', (new URL(locationURL)).host)
+  [FLUSHCHUNK] (chunk) {
+    return chunk ? (this.emit('data', chunk), this.flowing) : false
+  }
 
-          // HTTP-redirect fetch step 6 (counter increment)
-          // Create a new Request object.
-          const requestOpts = {
-            headers: new Headers(request.headers),
-            follow: request.follow,
-            counter: request.counter + 1,
-            agent: request.agent,
-            compress: request.compress,
-            method: request.method,
-            body: request.body,
-            signal: request.signal,
-            timeout: request.timeout,
-          }
+  pipe (dest, opts) {
+    if (this[DESTROYED])
+      return
 
-          // if the redirect is to a new hostname, strip the authorization and cookie headers
-          const parsedOriginal = new URL(request.url)
-          const parsedRedirect = new URL(locationURL)
-          if (parsedOriginal.hostname !== parsedRedirect.hostname) {
-            requestOpts.headers.delete('authorization')
-            requestOpts.headers.delete('cookie')
-          }
+    const ended = this[EMITTED_END]
+    opts = opts || {}
+    if (dest === proc.stdout || dest === proc.stderr)
+      opts.end = false
+    else
+      opts.end = opts.end !== false
+    opts.proxyErrors = !!opts.proxyErrors
 
-          // HTTP-redirect fetch step 11
-          if (res.statusCode === 303 || (
-            (res.statusCode === 301 || res.statusCode === 302) &&
-              request.method === 'POST'
-          )) {
-            requestOpts.method = 'GET'
-            requestOpts.body = undefined
-            requestOpts.headers.delete('content-length')
-          }
+    // piping an ended stream ends immediately
+    if (ended) {
+      if (opts.end)
+        dest.end()
+    } else {
+      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
+        : new PipeProxyErrors(this, dest, opts))
+      if (this[ASYNC])
+        defer(() => this[RESUME]())
+      else
+        this[RESUME]()
+    }
 
-          // HTTP-redirect fetch step 15
-          resolve(fetch(new Request(locationURL, requestOpts)))
-          finalize()
-          return
-        }
-      } // end if(isRedirect)
+    return dest
+  }
 
-      // prepare response
-      res.once('end', () =>
-        signal && signal.removeEventListener('abort', abortAndFinalize))
+  unpipe (dest) {
+    const p = this.pipes.find(p => p.dest === dest)
+    if (p) {
+      this.pipes.splice(this.pipes.indexOf(p), 1)
+      p.unpipe()
+    }
+  }
 
-      const body = new Minipass()
-      // if an error occurs, either on the response stream itself, on one of the
-      // decoder streams, or a response length timeout from the Body class, we
-      // forward the error through to our internal body stream. If we see an
-      // error event on that, we call finalize to abort the request and ensure
-      // we don't leave a socket believing a request is in flight.
-      // this is difficult to test, so lacks specific coverage.
-      body.on('error', finalize)
-      // exceedingly rare that the stream would have an error,
-      // but just in case we proxy it to the stream in use.
-      res.on('error', /* istanbul ignore next */ er => body.emit('error', er))
-      res.on('data', (chunk) => body.write(chunk))
-      res.on('end', () => body.end())
+  addListener (ev, fn) {
+    return this.on(ev, fn)
+  }
 
-      const responseOptions = {
-        url: request.url,
-        status: res.statusCode,
-        statusText: res.statusMessage,
-        headers: headers,
-        size: request.size,
-        timeout: request.timeout,
-        counter: request.counter,
-        trailer: new Promise(resolveTrailer =>
-          res.on('end', () => resolveTrailer(createHeadersLenient(res.trailers)))),
-      }
+  on (ev, fn) {
+    const ret = super.on(ev, fn)
+    if (ev === 'data' && !this.pipes.length && !this.flowing)
+      this[RESUME]()
+    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
+      super.emit('readable')
+    else if (isEndish(ev) && this[EMITTED_END]) {
+      super.emit(ev)
+      this.removeAllListeners(ev)
+    } else if (ev === 'error' && this[EMITTED_ERROR]) {
+      if (this[ASYNC])
+        defer(() => fn.call(this, this[EMITTED_ERROR]))
+      else
+        fn.call(this, this[EMITTED_ERROR])
+    }
+    return ret
+  }
 
-      // HTTP-network fetch step 12.1.1.3
-      const codings = headers.get('Content-Encoding')
+  get emittedEnd () {
+    return this[EMITTED_END]
+  }
 
-      // HTTP-network fetch step 12.1.1.4: handle content codings
+  [MAYBE_EMIT_END] () {
+    if (!this[EMITTING_END] &&
+        !this[EMITTED_END] &&
+        !this[DESTROYED] &&
+        this.buffer.length === 0 &&
+        this[EOF]) {
+      this[EMITTING_END] = true
+      this.emit('end')
+      this.emit('prefinish')
+      this.emit('finish')
+      if (this[CLOSED])
+        this.emit('close')
+      this[EMITTING_END] = false
+    }
+  }
 
-      // in following scenarios we ignore compression support
-      // 1. compression support is disabled
-      // 2. HEAD request
-      // 3. no Content-Encoding header
-      // 4. no content response (204)
-      // 5. content not modified response (304)
-      if (!request.compress ||
-          request.method === 'HEAD' ||
-          codings === null ||
-          res.statusCode === 204 ||
-          res.statusCode === 304) {
-        response = new Response(body, responseOptions)
-        resolve(response)
+  emit (ev, data, ...extra) {
+    // error and close are only events allowed after calling destroy()
+    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
+      return
+    else if (ev === 'data') {
+      return !data ? false
+        : this[ASYNC] ? defer(() => this[EMITDATA](data))
+        : this[EMITDATA](data)
+    } else if (ev === 'end') {
+      return this[EMITEND]()
+    } else if (ev === 'close') {
+      this[CLOSED] = true
+      // don't emit close before 'end' and 'finish'
+      if (!this[EMITTED_END] && !this[DESTROYED])
         return
-      }
+      const ret = super.emit('close')
+      this.removeAllListeners('close')
+      return ret
+    } else if (ev === 'error') {
+      this[EMITTED_ERROR] = data
+      const ret = super.emit('error', data)
+      this[MAYBE_EMIT_END]()
+      return ret
+    } else if (ev === 'resume') {
+      const ret = super.emit('resume')
+      this[MAYBE_EMIT_END]()
+      return ret
+    } else if (ev === 'finish' || ev === 'prefinish') {
+      const ret = super.emit(ev)
+      this.removeAllListeners(ev)
+      return ret
+    }
 
-      // Be less strict when decoding compressed responses, since sometimes
-      // servers send slightly invalid responses that are still accepted
-      // by common browsers.
-      // Always using Z_SYNC_FLUSH is what cURL does.
-      const zlibOptions = {
-        flush: zlib.constants.Z_SYNC_FLUSH,
-        finishFlush: zlib.constants.Z_SYNC_FLUSH,
-      }
+    // Some other unknown event
+    const ret = super.emit(ev, data, ...extra)
+    this[MAYBE_EMIT_END]()
+    return ret
+  }
 
-      // for gzip
-      if (codings === 'gzip' || codings === 'x-gzip') {
-        const unzip = new zlib.Gunzip(zlibOptions)
-        response = new Response(
-          // exceedingly rare that the stream would have an error,
-          // but just in case we proxy it to the stream in use.
-          body.on('error', /* istanbul ignore next */ er => unzip.emit('error', er)).pipe(unzip),
-          responseOptions
-        )
-        resolve(response)
-        return
-      }
+  [EMITDATA] (data) {
+    for (const p of this.pipes) {
+      if (p.dest.write(data) === false)
+        this.pause()
+    }
+    const ret = super.emit('data', data)
+    this[MAYBE_EMIT_END]()
+    return ret
+  }
 
-      // for deflate
-      if (codings === 'deflate' || codings === 'x-deflate') {
-        // handle the infamous raw deflate response from old servers
-        // a hack for old IIS and Apache servers
-        const raw = res.pipe(new Minipass())
-        raw.once('data', chunk => {
-          // see http://stackoverflow.com/questions/37519828
-          const decoder = (chunk[0] & 0x0F) === 0x08
-            ? new zlib.Inflate()
-            : new zlib.InflateRaw()
-          // exceedingly rare that the stream would have an error,
-          // but just in case we proxy it to the stream in use.
-          body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
-          response = new Response(decoder, responseOptions)
-          resolve(response)
-        })
-        return
-      }
+  [EMITEND] () {
+    if (this[EMITTED_END])
+      return
 
-      // for br
-      if (codings === 'br') {
-        // ignoring coverage so tests don't have to fake support (or lack of) for brotli
-        // istanbul ignore next
-        try {
-          var decoder = new zlib.BrotliDecompress()
-        } catch (err) {
-          reject(err)
-          finalize()
-          return
+    this[EMITTED_END] = true
+    this.readable = false
+    if (this[ASYNC])
+      defer(() => this[EMITEND2]())
+    else
+      this[EMITEND2]()
+  }
+
+  [EMITEND2] () {
+    if (this[DECODER]) {
+      const data = this[DECODER].end()
+      if (data) {
+        for (const p of this.pipes) {
+          p.dest.write(data)
         }
-        // exceedingly rare that the stream would have an error,
-        // but just in case we proxy it to the stream in use.
-        body.on('error', /* istanbul ignore next */ er => decoder.emit('error', er)).pipe(decoder)
-        response = new Response(decoder, responseOptions)
-        resolve(response)
-        return
+        super.emit('data', data)
       }
+    }
 
-      // otherwise, use response as-is
-      response = new Response(body, responseOptions)
-      resolve(response)
-    })
+    for (const p of this.pipes) {
+      p.end()
+    }
+    const ret = super.emit('end')
+    this.removeAllListeners('end')
+    return ret
+  }
 
-    writeToStream(req, request)
-  })
-}
+  // const all = await stream.collect()
+  collect () {
+    const buf = []
+    if (!this[OBJECTMODE])
+      buf.dataLength = 0
+    // set the promise first, in case an error is raised
+    // by triggering the flow here.
+    const p = this.promise()
+    this.on('data', c => {
+      buf.push(c)
+      if (!this[OBJECTMODE])
+        buf.dataLength += c.length
+    })
+    return p.then(() => buf)
+  }
 
-module.exports = fetch
+  // const data = await stream.concat()
+  concat () {
+    return this[OBJECTMODE]
+      ? Promise.reject(new Error('cannot concat in objectMode'))
+      : this.collect().then(buf =>
+          this[OBJECTMODE]
+            ? Promise.reject(new Error('cannot concat in objectMode'))
+            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
+  }
 
-fetch.isRedirect = code =>
-  code === 301 ||
-  code === 302 ||
-  code === 303 ||
-  code === 307 ||
-  code === 308
+  // stream.promise().then(() => done, er => emitted error)
+  promise () {
+    return new Promise((resolve, reject) => {
+      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
+      this.on('error', er => reject(er))
+      this.on('end', () => resolve())
+    })
+  }
 
-fetch.Headers = Headers
-fetch.Request = Request
-fetch.Response = Response
-fetch.FetchError = FetchError
-fetch.AbortError = AbortError
+  // for await (let chunk of stream)
+  [ASYNCITERATOR] () {
+    const next = () => {
+      const res = this.read()
+      if (res !== null)
+        return Promise.resolve({ done: false, value: res })
 
+      if (this[EOF])
+        return Promise.resolve({ done: true })
 
-/***/ }),
+      let resolve = null
+      let reject = null
+      const onerr = er => {
+        this.removeListener('data', ondata)
+        this.removeListener('end', onend)
+        reject(er)
+      }
+      const ondata = value => {
+        this.removeListener('error', onerr)
+        this.removeListener('end', onend)
+        this.pause()
+        resolve({ value: value, done: !!this[EOF] })
+      }
+      const onend = () => {
+        this.removeListener('error', onerr)
+        this.removeListener('data', ondata)
+        resolve({ done: true })
+      }
+      const ondestroy = () => onerr(new Error('stream destroyed'))
+      return new Promise((res, rej) => {
+        reject = rej
+        resolve = res
+        this.once(DESTROYED, ondestroy)
+        this.once('error', onerr)
+        this.once('end', onend)
+        this.once('data', ondata)
+      })
+    }
 
-/***/ 99586:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    return { next }
+  }
 
-"use strict";
+  // for (let chunk of stream)
+  [ITERATOR] () {
+    const next = () => {
+      const value = this.read()
+      const done = value === null
+      return { value, done }
+    }
+    return { next }
+  }
 
-const { URL } = __nccwpck_require__(87016)
-const { Minipass } = __nccwpck_require__(78275)
-const Headers = __nccwpck_require__(98645)
-const { exportNodeCompatibleHeaders } = Headers
-const Body = __nccwpck_require__(28515)
-const { clone, extractContentType, getTotalBytes } = Body
+  destroy (er) {
+    if (this[DESTROYED]) {
+      if (er)
+        this.emit('error', er)
+      else
+        this.emit(DESTROYED)
+      return this
+    }
 
-const version = (__nccwpck_require__(27573)/* .version */ .rE)
-const defaultUserAgent =
-  `minipass-fetch/${version} (+https://github.com/isaacs/minipass-fetch)`
+    this[DESTROYED] = true
 
-const INTERNALS = Symbol('Request internals')
+    // throw away all buffered data, it's never coming out
+    this.buffer.length = 0
+    this[BUFFERLENGTH] = 0
 
-const isRequest = input =>
-  typeof input === 'object' && typeof input[INTERNALS] === 'object'
+    if (typeof this.close === 'function' && !this[CLOSED])
+      this.close()
 
-const isAbortSignal = signal => {
-  const proto = (
-    signal
-    && typeof signal === 'object'
-    && Object.getPrototypeOf(signal)
-  )
-  return !!(proto && proto.constructor.name === 'AbortSignal')
-}
+    if (er)
+      this.emit('error', er)
+    else // if no error to emit, still reject pending promises
+      this.emit(DESTROYED)
 
-class Request extends Body {
-  constructor (input, init = {}) {
-    const parsedURL = isRequest(input) ? new URL(input.url)
-      : input && input.href ? new URL(input.href)
-      : new URL(`${input}`)
+    return this
+  }
 
-    if (isRequest(input)) {
-      init = { ...input[INTERNALS], ...init }
-    } else if (!input || typeof input === 'string') {
-      input = {}
-    }
+  static isStream (s) {
+    return !!s && (s instanceof Minipass || s instanceof Stream ||
+      s instanceof EE && (
+        typeof s.pipe === 'function' || // readable
+        (typeof s.write === 'function' && typeof s.end === 'function') // writable
+      ))
+  }
+}
 
-    const method = (init.method || input.method || 'GET').toUpperCase()
-    const isGETHEAD = method === 'GET' || method === 'HEAD'
 
-    if ((init.body !== null && init.body !== undefined ||
-        isRequest(input) && input.body !== null) && isGETHEAD) {
-      throw new TypeError('Request with GET/HEAD method cannot have body')
-    }
+/***/ }),
 
-    const inputBody = init.body !== null && init.body !== undefined ? init.body
-      : isRequest(input) && input.body !== null ? clone(input)
-      : null
+/***/ 70744:
+/***/ ((module) => {
 
-    super(inputBody, {
-      timeout: init.timeout || input.timeout || 0,
-      size: init.size || input.size || 0,
-    })
+/**
+ * Helpers.
+ */
 
-    const headers = new Headers(init.headers || input.headers || {})
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var w = d * 7;
+var y = d * 365.25;
 
-    if (inputBody !== null && inputBody !== undefined &&
-        !headers.has('Content-Type')) {
-      const contentType = extractContentType(inputBody)
-      if (contentType) {
-        headers.append('Content-Type', contentType)
-      }
-    }
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ *  - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
 
-    const signal = 'signal' in init ? init.signal
-      : null
+module.exports = function(val, options) {
+  options = options || {};
+  var type = typeof val;
+  if (type === 'string' && val.length > 0) {
+    return parse(val);
+  } else if (type === 'number' && isFinite(val)) {
+    return options.long ? fmtLong(val) : fmtShort(val);
+  }
+  throw new Error(
+    'val is not a non-empty string or a valid number. val=' +
+      JSON.stringify(val)
+  );
+};
 
-    if (signal !== null && signal !== undefined && !isAbortSignal(signal)) {
-      throw new TypeError('Expected signal must be an instanceof AbortSignal')
-    }
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
 
-    // TLS specific options that are handled by node
-    const {
-      ca,
-      cert,
-      ciphers,
-      clientCertEngine,
-      crl,
-      dhparam,
-      ecdhCurve,
-      family,
-      honorCipherOrder,
-      key,
-      passphrase,
-      pfx,
-      rejectUnauthorized = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0',
-      secureOptions,
-      secureProtocol,
-      servername,
-      sessionIdContext,
-    } = init
+function parse(str) {
+  str = String(str);
+  if (str.length > 100) {
+    return;
+  }
+  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+    str
+  );
+  if (!match) {
+    return;
+  }
+  var n = parseFloat(match[1]);
+  var type = (match[2] || 'ms').toLowerCase();
+  switch (type) {
+    case 'years':
+    case 'year':
+    case 'yrs':
+    case 'yr':
+    case 'y':
+      return n * y;
+    case 'weeks':
+    case 'week':
+    case 'w':
+      return n * w;
+    case 'days':
+    case 'day':
+    case 'd':
+      return n * d;
+    case 'hours':
+    case 'hour':
+    case 'hrs':
+    case 'hr':
+    case 'h':
+      return n * h;
+    case 'minutes':
+    case 'minute':
+    case 'mins':
+    case 'min':
+    case 'm':
+      return n * m;
+    case 'seconds':
+    case 'second':
+    case 'secs':
+    case 'sec':
+    case 's':
+      return n * s;
+    case 'milliseconds':
+    case 'millisecond':
+    case 'msecs':
+    case 'msec':
+    case 'ms':
+      return n;
+    default:
+      return undefined;
+  }
+}
 
-    this[INTERNALS] = {
-      method,
-      redirect: init.redirect || input.redirect || 'follow',
-      headers,
-      parsedURL,
-      signal,
-      ca,
-      cert,
-      ciphers,
-      clientCertEngine,
-      crl,
-      dhparam,
-      ecdhCurve,
-      family,
-      honorCipherOrder,
-      key,
-      passphrase,
-      pfx,
-      rejectUnauthorized,
-      secureOptions,
-      secureProtocol,
-      servername,
-      sessionIdContext,
-    }
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
 
-    // node-fetch-only options
-    this.follow = init.follow !== undefined ? init.follow
-      : input.follow !== undefined ? input.follow
-      : 20
-    this.compress = init.compress !== undefined ? init.compress
-      : input.compress !== undefined ? input.compress
-      : true
-    this.counter = init.counter || input.counter || 0
-    this.agent = init.agent || input.agent
+function fmtShort(ms) {
+  var msAbs = Math.abs(ms);
+  if (msAbs >= d) {
+    return Math.round(ms / d) + 'd';
   }
-
-  get method () {
-    return this[INTERNALS].method
+  if (msAbs >= h) {
+    return Math.round(ms / h) + 'h';
   }
-
-  get url () {
-    return this[INTERNALS].parsedURL.toString()
+  if (msAbs >= m) {
+    return Math.round(ms / m) + 'm';
   }
-
-  get headers () {
-    return this[INTERNALS].headers
+  if (msAbs >= s) {
+    return Math.round(ms / s) + 's';
   }
+  return ms + 'ms';
+}
 
-  get redirect () {
-    return this[INTERNALS].redirect
-  }
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
 
-  get signal () {
-    return this[INTERNALS].signal
+function fmtLong(ms) {
+  var msAbs = Math.abs(ms);
+  if (msAbs >= d) {
+    return plural(ms, msAbs, d, 'day');
   }
-
-  clone () {
-    return new Request(this)
+  if (msAbs >= h) {
+    return plural(ms, msAbs, h, 'hour');
   }
-
-  get [Symbol.toStringTag] () {
-    return 'Request'
+  if (msAbs >= m) {
+    return plural(ms, msAbs, m, 'minute');
   }
+  if (msAbs >= s) {
+    return plural(ms, msAbs, s, 'second');
+  }
+  return ms + ' ms';
+}
 
-  static getNodeRequestOptions (request) {
-    const parsedURL = request[INTERNALS].parsedURL
-    const headers = new Headers(request[INTERNALS].headers)
-
-    // fetch step 1.3
-    if (!headers.has('Accept')) {
-      headers.set('Accept', '*/*')
-    }
+/**
+ * Pluralization helper.
+ */
 
-    // Basic fetch
-    if (!/^https?:$/.test(parsedURL.protocol)) {
-      throw new TypeError('Only HTTP(S) protocols are supported')
-    }
+function plural(ms, msAbs, n, name) {
+  var isPlural = msAbs >= n * 1.5;
+  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+}
 
-    if (request.signal &&
-        Minipass.isStream(request.body) &&
-        typeof request.body.destroy !== 'function') {
-      throw new Error(
-        'Cancellation of streamed requests with AbortSignal is not supported')
-    }
 
-    // HTTP-network-or-cache fetch steps 2.4-2.7
-    const contentLengthValue =
-      (request.body === null || request.body === undefined) &&
-        /^(POST|PUT)$/i.test(request.method) ? '0'
-      : request.body !== null && request.body !== undefined
-        ? getTotalBytes(request)
-        : null
+/***/ }),
 
-    if (contentLengthValue) {
-      headers.set('Content-Length', contentLengthValue + '')
-    }
+/***/ 60668:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    // HTTP-network-or-cache fetch step 2.11
-    if (!headers.has('User-Agent')) {
-      headers.set('User-Agent', defaultUserAgent)
-    }
+"use strict";
+/*!
+ * negotiator
+ * Copyright(c) 2012 Federico Romero
+ * Copyright(c) 2012-2014 Isaac Z. Schlueter
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
 
-    // HTTP-network-or-cache fetch step 2.15
-    if (request.compress && !headers.has('Accept-Encoding')) {
-      headers.set('Accept-Encoding', 'gzip,deflate')
-    }
 
-    const agent = typeof request.agent === 'function'
-      ? request.agent(parsedURL)
-      : request.agent
 
-    if (!headers.has('Connection') && !agent) {
-      headers.set('Connection', 'close')
-    }
+var preferredCharsets = __nccwpck_require__(79168)
+var preferredEncodings = __nccwpck_require__(25111)
+var preferredLanguages = __nccwpck_require__(56008)
+var preferredMediaTypes = __nccwpck_require__(53672)
 
-    // TLS specific options that are handled by node
-    const {
-      ca,
-      cert,
-      ciphers,
-      clientCertEngine,
-      crl,
-      dhparam,
-      ecdhCurve,
-      family,
-      honorCipherOrder,
-      key,
-      passphrase,
-      pfx,
-      rejectUnauthorized,
-      secureOptions,
-      secureProtocol,
-      servername,
-      sessionIdContext,
-    } = request[INTERNALS]
+/**
+ * Module exports.
+ * @public
+ */
 
-    // HTTP-network fetch step 4.2
-    // chunked encoding is handled by Node.js
+module.exports = Negotiator;
+module.exports.Negotiator = Negotiator;
 
-    // we cannot spread parsedURL directly, so we have to read each property one-by-one
-    // and map them to the equivalent https?.request() method options
-    const urlProps = {
-      auth: parsedURL.username || parsedURL.password
-        ? `${parsedURL.username}:${parsedURL.password}`
-        : '',
-      host: parsedURL.host,
-      hostname: parsedURL.hostname,
-      path: `${parsedURL.pathname}${parsedURL.search}`,
-      port: parsedURL.port,
-      protocol: parsedURL.protocol,
-    }
+/**
+ * Create a Negotiator instance from a request.
+ * @param {object} request
+ * @public
+ */
 
-    return {
-      ...urlProps,
-      method: request.method,
-      headers: exportNodeCompatibleHeaders(headers),
-      agent,
-      ca,
-      cert,
-      ciphers,
-      clientCertEngine,
-      crl,
-      dhparam,
-      ecdhCurve,
-      family,
-      honorCipherOrder,
-      key,
-      passphrase,
-      pfx,
-      rejectUnauthorized,
-      secureOptions,
-      secureProtocol,
-      servername,
-      sessionIdContext,
-      timeout: request.timeout,
-    }
+function Negotiator(request) {
+  if (!(this instanceof Negotiator)) {
+    return new Negotiator(request);
   }
+
+  this.request = request;
 }
 
-module.exports = Request
+Negotiator.prototype.charset = function charset(available) {
+  var set = this.charsets(available);
+  return set && set[0];
+};
+
+Negotiator.prototype.charsets = function charsets(available) {
+  return preferredCharsets(this.request.headers['accept-charset'], available);
+};
+
+Negotiator.prototype.encoding = function encoding(available, opts) {
+  var set = this.encodings(available, opts);
+  return set && set[0];
+};
+
+Negotiator.prototype.encodings = function encodings(available, options) {
+  var opts = options || {};
+  return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred);
+};
+
+Negotiator.prototype.language = function language(available) {
+  var set = this.languages(available);
+  return set && set[0];
+};
+
+Negotiator.prototype.languages = function languages(available) {
+  return preferredLanguages(this.request.headers['accept-language'], available);
+};
+
+Negotiator.prototype.mediaType = function mediaType(available) {
+  var set = this.mediaTypes(available);
+  return set && set[0];
+};
 
-Object.defineProperties(Request.prototype, {
-  method: { enumerable: true },
-  url: { enumerable: true },
-  headers: { enumerable: true },
-  redirect: { enumerable: true },
-  clone: { enumerable: true },
-  signal: { enumerable: true },
-})
+Negotiator.prototype.mediaTypes = function mediaTypes(available) {
+  return preferredMediaTypes(this.request.headers.accept, available);
+};
+
+// Backwards compatibility
+Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
+Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
+Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
+Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
+Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
+Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
+Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
+Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
 
 
 /***/ }),
 
-/***/ 43852:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 79168:
+/***/ ((module) => {
 
 "use strict";
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
 
-const http = __nccwpck_require__(58611)
-const { STATUS_CODES } = http
 
-const Headers = __nccwpck_require__(98645)
-const Body = __nccwpck_require__(28515)
-const { clone, extractContentType } = Body
 
-const INTERNALS = Symbol('Response internals')
+/**
+ * Module exports.
+ * @public
+ */
 
-class Response extends Body {
-  constructor (body = null, opts = {}) {
-    super(body, opts)
+module.exports = preferredCharsets;
+module.exports.preferredCharsets = preferredCharsets;
 
-    const status = opts.status || 200
-    const headers = new Headers(opts.headers)
+/**
+ * Module variables.
+ * @private
+ */
 
-    if (body !== null && body !== undefined && !headers.has('Content-Type')) {
-      const contentType = extractContentType(body)
-      if (contentType) {
-        headers.append('Content-Type', contentType)
-      }
-    }
+var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
 
-    this[INTERNALS] = {
-      url: opts.url,
-      status,
-      statusText: opts.statusText || STATUS_CODES[status],
-      headers,
-      counter: opts.counter,
-      trailer: Promise.resolve(opts.trailer || new Headers()),
-    }
-  }
+/**
+ * Parse the Accept-Charset header.
+ * @private
+ */
 
-  get trailer () {
-    return this[INTERNALS].trailer
-  }
+function parseAcceptCharset(accept) {
+  var accepts = accept.split(',');
 
-  get url () {
-    return this[INTERNALS].url || ''
-  }
+  for (var i = 0, j = 0; i < accepts.length; i++) {
+    var charset = parseCharset(accepts[i].trim(), i);
 
-  get status () {
-    return this[INTERNALS].status
+    if (charset) {
+      accepts[j++] = charset;
+    }
   }
 
-  get ok () {
-    return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300
-  }
+  // trim accepts
+  accepts.length = j;
 
-  get redirected () {
-    return this[INTERNALS].counter > 0
-  }
+  return accepts;
+}
 
-  get statusText () {
-    return this[INTERNALS].statusText
-  }
+/**
+ * Parse a charset from the Accept-Charset header.
+ * @private
+ */
 
-  get headers () {
-    return this[INTERNALS].headers
-  }
+function parseCharset(str, i) {
+  var match = simpleCharsetRegExp.exec(str);
+  if (!match) return null;
 
-  clone () {
-    return new Response(clone(this), {
-      url: this.url,
-      status: this.status,
-      statusText: this.statusText,
-      headers: this.headers,
-      ok: this.ok,
-      redirected: this.redirected,
-      trailer: this.trailer,
-    })
+  var charset = match[1];
+  var q = 1;
+  if (match[2]) {
+    var params = match[2].split(';')
+    for (var j = 0; j < params.length; j++) {
+      var p = params[j].trim().split('=');
+      if (p[0] === 'q') {
+        q = parseFloat(p[1]);
+        break;
+      }
+    }
   }
 
-  get [Symbol.toStringTag] () {
-    return 'Response'
-  }
+  return {
+    charset: charset,
+    q: q,
+    i: i
+  };
 }
 
-module.exports = Response
-
-Object.defineProperties(Response.prototype, {
-  url: { enumerable: true },
-  status: { enumerable: true },
-  ok: { enumerable: true },
-  redirected: { enumerable: true },
-  statusText: { enumerable: true },
-  headers: { enumerable: true },
-  clone: { enumerable: true },
-})
+/**
+ * Get the priority of a charset.
+ * @private
+ */
 
+function getCharsetPriority(charset, accepted, index) {
+  var priority = {o: -1, q: 0, s: 0};
 
-/***/ }),
+  for (var i = 0; i < accepted.length; i++) {
+    var spec = specify(charset, accepted[i], index);
 
-/***/ 37633:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+      priority = spec;
+    }
+  }
 
-const Minipass = __nccwpck_require__(64387)
-const _flush = Symbol('_flush')
-const _flushed = Symbol('_flushed')
-const _flushing = Symbol('_flushing')
-class Flush extends Minipass {
-  constructor (opt = {}) {
-    if (typeof opt === 'function')
-      opt = { flush: opt }
+  return priority;
+}
 
-    super(opt)
+/**
+ * Get the specificity of the charset.
+ * @private
+ */
 
-    // or extend this class and provide a 'flush' method in your subclass
-    if (typeof opt.flush !== 'function' && typeof this.flush !== 'function')
-      throw new TypeError('must provide flush function in options')
+function specify(charset, spec, index) {
+  var s = 0;
+  if(spec.charset.toLowerCase() === charset.toLowerCase()){
+    s |= 1;
+  } else if (spec.charset !== '*' ) {
+    return null
+  }
 
-    this[_flush] = opt.flush || this.flush
+  return {
+    i: index,
+    o: spec.i,
+    q: spec.q,
+    s: s
   }
+}
 
-  emit (ev, ...data) {
-    if ((ev !== 'end' && ev !== 'finish') || this[_flushed])
-      return super.emit(ev, ...data)
+/**
+ * Get the preferred charsets from an Accept-Charset header.
+ * @public
+ */
 
-    if (this[_flushing])
-      return
+function preferredCharsets(accept, provided) {
+  // RFC 2616 sec 14.2: no header = *
+  var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');
 
-    this[_flushing] = true
+  if (!provided) {
+    // sorted list of all charsets
+    return accepts
+      .filter(isQuality)
+      .sort(compareSpecs)
+      .map(getFullCharset);
+  }
 
-    const afterFlush = er => {
-      this[_flushed] = true
-      er ? super.emit('error', er) : super.emit('end')
-    }
+  var priorities = provided.map(function getPriority(type, index) {
+    return getCharsetPriority(type, accepts, index);
+  });
 
-    const ret = this[_flush](afterFlush)
-    if (ret && ret.then)
-      ret.then(() => afterFlush(), er => afterFlush(er))
-  }
+  // sorted list of accepted charsets
+  return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
+    return provided[priorities.indexOf(priority)];
+  });
 }
 
-module.exports = Flush
+/**
+ * Compare two specs.
+ * @private
+ */
 
+function compareSpecs(a, b) {
+  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+}
 
-/***/ }),
+/**
+ * Get full charset string.
+ * @private
+ */
 
-/***/ 64387:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function getFullCharset(spec) {
+  return spec.charset;
+}
 
-"use strict";
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
 
-const proc = typeof process === 'object' && process ? process : {
-  stdout: null,
-  stderr: null,
+function isQuality(spec) {
+  return spec.q > 0;
 }
-const EE = __nccwpck_require__(24434)
-const Stream = __nccwpck_require__(2203)
-const SD = (__nccwpck_require__(13193).StringDecoder)
 
-const EOF = Symbol('EOF')
-const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
-const EMITTED_END = Symbol('emittedEnd')
-const EMITTING_END = Symbol('emittingEnd')
-const EMITTED_ERROR = Symbol('emittedError')
-const CLOSED = Symbol('closed')
-const READ = Symbol('read')
-const FLUSH = Symbol('flush')
-const FLUSHCHUNK = Symbol('flushChunk')
-const ENCODING = Symbol('encoding')
-const DECODER = Symbol('decoder')
-const FLOWING = Symbol('flowing')
-const PAUSED = Symbol('paused')
-const RESUME = Symbol('resume')
-const BUFFERLENGTH = Symbol('bufferLength')
-const BUFFERPUSH = Symbol('bufferPush')
-const BUFFERSHIFT = Symbol('bufferShift')
-const OBJECTMODE = Symbol('objectMode')
-const DESTROYED = Symbol('destroyed')
-const EMITDATA = Symbol('emitData')
-const EMITEND = Symbol('emitEnd')
-const EMITEND2 = Symbol('emitEnd2')
-const ASYNC = Symbol('async')
 
-const defer = fn => Promise.resolve().then(fn)
+/***/ }),
 
-// TODO remove when Node v8 support drops
-const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
-const ASYNCITERATOR = doIter && Symbol.asyncIterator
-  || Symbol('asyncIterator not implemented')
-const ITERATOR = doIter && Symbol.iterator
-  || Symbol('iterator not implemented')
+/***/ 25111:
+/***/ ((module) => {
 
-// events that mean 'the stream is over'
-// these are treated specially, and re-emitted
-// if they are listened for after emitting.
-const isEndish = ev =>
-  ev === 'end' ||
-  ev === 'finish' ||
-  ev === 'prefinish'
+"use strict";
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
 
-const isArrayBuffer = b => b instanceof ArrayBuffer ||
-  typeof b === 'object' &&
-  b.constructor &&
-  b.constructor.name === 'ArrayBuffer' &&
-  b.byteLength >= 0
 
-const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
 
-class Pipe {
-  constructor (src, dest, opts) {
-    this.src = src
-    this.dest = dest
-    this.opts = opts
-    this.ondrain = () => src[RESUME]()
-    dest.on('drain', this.ondrain)
-  }
-  unpipe () {
-    this.dest.removeListener('drain', this.ondrain)
-  }
-  // istanbul ignore next - only here for the prototype
-  proxyErrors () {}
-  end () {
-    this.unpipe()
-    if (this.opts.end)
-      this.dest.end()
-  }
-}
+/**
+ * Module exports.
+ * @public
+ */
 
-class PipeProxyErrors extends Pipe {
-  unpipe () {
-    this.src.removeListener('error', this.proxyErrors)
-    super.unpipe()
-  }
-  constructor (src, dest, opts) {
-    super(src, dest, opts)
-    this.proxyErrors = er => dest.emit('error', er)
-    src.on('error', this.proxyErrors)
-  }
-}
+module.exports = preferredEncodings;
+module.exports.preferredEncodings = preferredEncodings;
 
-module.exports = class Minipass extends Stream {
-  constructor (options) {
-    super()
-    this[FLOWING] = false
-    // whether we're explicitly paused
-    this[PAUSED] = false
-    this.pipes = []
-    this.buffer = []
-    this[OBJECTMODE] = options && options.objectMode || false
-    if (this[OBJECTMODE])
-      this[ENCODING] = null
-    else
-      this[ENCODING] = options && options.encoding || null
-    if (this[ENCODING] === 'buffer')
-      this[ENCODING] = null
-    this[ASYNC] = options && !!options.async || false
-    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
-    this[EOF] = false
-    this[EMITTED_END] = false
-    this[EMITTING_END] = false
-    this[CLOSED] = false
-    this[EMITTED_ERROR] = null
-    this.writable = true
-    this.readable = true
-    this[BUFFERLENGTH] = 0
-    this[DESTROYED] = false
-  }
+/**
+ * Module variables.
+ * @private
+ */
 
-  get bufferLength () { return this[BUFFERLENGTH] }
+var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
 
-  get encoding () { return this[ENCODING] }
-  set encoding (enc) {
-    if (this[OBJECTMODE])
-      throw new Error('cannot set encoding in objectMode')
+/**
+ * Parse the Accept-Encoding header.
+ * @private
+ */
 
-    if (this[ENCODING] && enc !== this[ENCODING] &&
-        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
-      throw new Error('cannot change encoding')
+function parseAcceptEncoding(accept) {
+  var accepts = accept.split(',');
+  var hasIdentity = false;
+  var minQuality = 1;
 
-    if (this[ENCODING] !== enc) {
-      this[DECODER] = enc ? new SD(enc) : null
-      if (this.buffer.length)
-        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
-    }
+  for (var i = 0, j = 0; i < accepts.length; i++) {
+    var encoding = parseEncoding(accepts[i].trim(), i);
 
-    this[ENCODING] = enc
+    if (encoding) {
+      accepts[j++] = encoding;
+      hasIdentity = hasIdentity || specify('identity', encoding);
+      minQuality = Math.min(minQuality, encoding.q || 1);
+    }
   }
 
-  setEncoding (enc) {
-    this.encoding = enc
+  if (!hasIdentity) {
+    /*
+     * If identity doesn't explicitly appear in the accept-encoding header,
+     * it's added to the list of acceptable encoding with the lowest q
+     */
+    accepts[j++] = {
+      encoding: 'identity',
+      q: minQuality,
+      i: i
+    };
   }
 
-  get objectMode () { return this[OBJECTMODE] }
-  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
+  // trim accepts
+  accepts.length = j;
 
-  get ['async'] () { return this[ASYNC] }
-  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }
+  return accepts;
+}
 
-  write (chunk, encoding, cb) {
-    if (this[EOF])
-      throw new Error('write after end')
+/**
+ * Parse an encoding from the Accept-Encoding header.
+ * @private
+ */
 
-    if (this[DESTROYED]) {
-      this.emit('error', Object.assign(
-        new Error('Cannot call write after a stream was destroyed'),
-        { code: 'ERR_STREAM_DESTROYED' }
-      ))
-      return true
+function parseEncoding(str, i) {
+  var match = simpleEncodingRegExp.exec(str);
+  if (!match) return null;
+
+  var encoding = match[1];
+  var q = 1;
+  if (match[2]) {
+    var params = match[2].split(';');
+    for (var j = 0; j < params.length; j++) {
+      var p = params[j].trim().split('=');
+      if (p[0] === 'q') {
+        q = parseFloat(p[1]);
+        break;
+      }
     }
+  }
 
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
+  return {
+    encoding: encoding,
+    q: q,
+    i: i
+  };
+}
 
-    if (!encoding)
-      encoding = 'utf8'
+/**
+ * Get the priority of an encoding.
+ * @private
+ */
 
-    const fn = this[ASYNC] ? defer : f => f()
+function getEncodingPriority(encoding, accepted, index) {
+  var priority = {encoding: encoding, o: -1, q: 0, s: 0};
 
-    // convert array buffers and typed array views into buffers
-    // at some point in the future, we may want to do the opposite!
-    // leave strings and buffers as-is
-    // anything else switches us into object mode
-    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
-      if (isArrayBufferView(chunk))
-        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
-      else if (isArrayBuffer(chunk))
-        chunk = Buffer.from(chunk)
-      else if (typeof chunk !== 'string')
-        // use the setter so we throw if we have encoding set
-        this.objectMode = true
+  for (var i = 0; i < accepted.length; i++) {
+    var spec = specify(encoding, accepted[i], index);
+
+    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+      priority = spec;
     }
+  }
 
-    // handle object mode up front, since it's simpler
-    // this yields better performance, fewer checks later.
-    if (this[OBJECTMODE]) {
-      /* istanbul ignore if - maybe impossible? */
-      if (this.flowing && this[BUFFERLENGTH] !== 0)
-        this[FLUSH](true)
+  return priority;
+}
+
+/**
+ * Get the specificity of the encoding.
+ * @private
+ */
 
-      if (this.flowing)
-        this.emit('data', chunk)
-      else
-        this[BUFFERPUSH](chunk)
+function specify(encoding, spec, index) {
+  var s = 0;
+  if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
+    s |= 1;
+  } else if (spec.encoding !== '*' ) {
+    return null
+  }
 
-      if (this[BUFFERLENGTH] !== 0)
-        this.emit('readable')
+  return {
+    encoding: encoding,
+    i: index,
+    o: spec.i,
+    q: spec.q,
+    s: s
+  }
+};
 
-      if (cb)
-        fn(cb)
+/**
+ * Get the preferred encodings from an Accept-Encoding header.
+ * @public
+ */
 
-      return this.flowing
+function preferredEncodings(accept, provided, preferred) {
+  var accepts = parseAcceptEncoding(accept || '');
+
+  var comparator = preferred ? function comparator (a, b) {
+    if (a.q !== b.q) {
+      return b.q - a.q // higher quality first
     }
 
-    // at this point the chunk is a buffer or string
-    // don't buffer it up or send it to the decoder
-    if (!chunk.length) {
-      if (this[BUFFERLENGTH] !== 0)
-        this.emit('readable')
-      if (cb)
-        fn(cb)
-      return this.flowing
+    var aPreferred = preferred.indexOf(a.encoding)
+    var bPreferred = preferred.indexOf(b.encoding)
+
+    if (aPreferred === -1 && bPreferred === -1) {
+      // consider the original specifity/order
+      return (b.s - a.s) || (a.o - b.o) || (a.i - b.i)
     }
 
-    // fast-path writing strings of same encoding to a stream with
-    // an empty buffer, skipping the buffer/decoder dance
-    if (typeof chunk === 'string' &&
-        // unless it is a string already ready for us to use
-        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
-      chunk = Buffer.from(chunk, encoding)
+    if (aPreferred !== -1 && bPreferred !== -1) {
+      return aPreferred - bPreferred // consider the preferred order
     }
 
-    if (Buffer.isBuffer(chunk) && this[ENCODING])
-      chunk = this[DECODER].write(chunk)
+    return aPreferred === -1 ? 1 : -1 // preferred first
+  } : compareSpecs;
 
-    // Note: flushing CAN potentially switch us into not-flowing mode
-    if (this.flowing && this[BUFFERLENGTH] !== 0)
-      this[FLUSH](true)
+  if (!provided) {
+    // sorted list of all encodings
+    return accepts
+      .filter(isQuality)
+      .sort(comparator)
+      .map(getFullEncoding);
+  }
 
-    if (this.flowing)
-      this.emit('data', chunk)
-    else
-      this[BUFFERPUSH](chunk)
+  var priorities = provided.map(function getPriority(type, index) {
+    return getEncodingPriority(type, accepts, index);
+  });
 
-    if (this[BUFFERLENGTH] !== 0)
-      this.emit('readable')
+  // sorted list of accepted encodings
+  return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) {
+    return provided[priorities.indexOf(priority)];
+  });
+}
 
-    if (cb)
-      fn(cb)
+/**
+ * Compare two specs.
+ * @private
+ */
 
-    return this.flowing
-  }
+function compareSpecs(a, b) {
+  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i);
+}
 
-  read (n) {
-    if (this[DESTROYED])
-      return null
+/**
+ * Get full encoding string.
+ * @private
+ */
 
-    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
-      this[MAYBE_EMIT_END]()
-      return null
-    }
+function getFullEncoding(spec) {
+  return spec.encoding;
+}
 
-    if (this[OBJECTMODE])
-      n = null
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
 
-    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
-      if (this.encoding)
-        this.buffer = [this.buffer.join('')]
-      else
-        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
-    }
+function isQuality(spec) {
+  return spec.q > 0;
+}
 
-    const ret = this[READ](n || null, this.buffer[0])
-    this[MAYBE_EMIT_END]()
-    return ret
-  }
 
-  [READ] (n, chunk) {
-    if (n === chunk.length || n === null)
-      this[BUFFERSHIFT]()
-    else {
-      this.buffer[0] = chunk.slice(n)
-      chunk = chunk.slice(0, n)
-      this[BUFFERLENGTH] -= n
-    }
+/***/ }),
 
-    this.emit('data', chunk)
+/***/ 56008:
+/***/ ((module) => {
 
-    if (!this.buffer.length && !this[EOF])
-      this.emit('drain')
+"use strict";
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
 
-    return chunk
-  }
 
-  end (chunk, encoding, cb) {
-    if (typeof chunk === 'function')
-      cb = chunk, chunk = null
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
-    if (chunk)
-      this.write(chunk, encoding)
-    if (cb)
-      this.once('end', cb)
-    this[EOF] = true
-    this.writable = false
 
-    // if we haven't written anything, then go ahead and emit,
-    // even if we're not reading.
-    // we'll re-emit if a new 'end' listener is added anyway.
-    // This makes MP more suitable to write-only use cases.
-    if (this.flowing || !this[PAUSED])
-      this[MAYBE_EMIT_END]()
-    return this
-  }
+/**
+ * Module exports.
+ * @public
+ */
 
-  // don't let the internal resume be overwritten
-  [RESUME] () {
-    if (this[DESTROYED])
-      return
+module.exports = preferredLanguages;
+module.exports.preferredLanguages = preferredLanguages;
 
-    this[PAUSED] = false
-    this[FLOWING] = true
-    this.emit('resume')
-    if (this.buffer.length)
-      this[FLUSH]()
-    else if (this[EOF])
-      this[MAYBE_EMIT_END]()
-    else
-      this.emit('drain')
-  }
+/**
+ * Module variables.
+ * @private
+ */
 
-  resume () {
-    return this[RESUME]()
-  }
+var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
 
-  pause () {
-    this[FLOWING] = false
-    this[PAUSED] = true
-  }
+/**
+ * Parse the Accept-Language header.
+ * @private
+ */
 
-  get destroyed () {
-    return this[DESTROYED]
-  }
+function parseAcceptLanguage(accept) {
+  var accepts = accept.split(',');
 
-  get flowing () {
-    return this[FLOWING]
-  }
+  for (var i = 0, j = 0; i < accepts.length; i++) {
+    var language = parseLanguage(accepts[i].trim(), i);
 
-  get paused () {
-    return this[PAUSED]
+    if (language) {
+      accepts[j++] = language;
+    }
   }
 
-  [BUFFERPUSH] (chunk) {
-    if (this[OBJECTMODE])
-      this[BUFFERLENGTH] += 1
-    else
-      this[BUFFERLENGTH] += chunk.length
-    this.buffer.push(chunk)
-  }
+  // trim accepts
+  accepts.length = j;
 
-  [BUFFERSHIFT] () {
-    if (this.buffer.length) {
-      if (this[OBJECTMODE])
-        this[BUFFERLENGTH] -= 1
-      else
-        this[BUFFERLENGTH] -= this.buffer[0].length
-    }
-    return this.buffer.shift()
-  }
+  return accepts;
+}
 
-  [FLUSH] (noDrain) {
-    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
+/**
+ * Parse a language from the Accept-Language header.
+ * @private
+ */
 
-    if (!noDrain && !this.buffer.length && !this[EOF])
-      this.emit('drain')
-  }
+function parseLanguage(str, i) {
+  var match = simpleLanguageRegExp.exec(str);
+  if (!match) return null;
 
-  [FLUSHCHUNK] (chunk) {
-    return chunk ? (this.emit('data', chunk), this.flowing) : false
+  var prefix = match[1]
+  var suffix = match[2]
+  var full = prefix
+
+  if (suffix) full += "-" + suffix;
+
+  var q = 1;
+  if (match[3]) {
+    var params = match[3].split(';')
+    for (var j = 0; j < params.length; j++) {
+      var p = params[j].split('=');
+      if (p[0] === 'q') q = parseFloat(p[1]);
+    }
   }
 
-  pipe (dest, opts) {
-    if (this[DESTROYED])
-      return
+  return {
+    prefix: prefix,
+    suffix: suffix,
+    q: q,
+    i: i,
+    full: full
+  };
+}
 
-    const ended = this[EMITTED_END]
-    opts = opts || {}
-    if (dest === proc.stdout || dest === proc.stderr)
-      opts.end = false
-    else
-      opts.end = opts.end !== false
-    opts.proxyErrors = !!opts.proxyErrors
+/**
+ * Get the priority of a language.
+ * @private
+ */
 
-    // piping an ended stream ends immediately
-    if (ended) {
-      if (opts.end)
-        dest.end()
-    } else {
-      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
-        : new PipeProxyErrors(this, dest, opts))
-      if (this[ASYNC])
-        defer(() => this[RESUME]())
-      else
-        this[RESUME]()
-    }
+function getLanguagePriority(language, accepted, index) {
+  var priority = {o: -1, q: 0, s: 0};
 
-    return dest
-  }
+  for (var i = 0; i < accepted.length; i++) {
+    var spec = specify(language, accepted[i], index);
 
-  unpipe (dest) {
-    const p = this.pipes.find(p => p.dest === dest)
-    if (p) {
-      this.pipes.splice(this.pipes.indexOf(p), 1)
-      p.unpipe()
+    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+      priority = spec;
     }
   }
 
-  addListener (ev, fn) {
-    return this.on(ev, fn)
-  }
+  return priority;
+}
 
-  on (ev, fn) {
-    const ret = super.on(ev, fn)
-    if (ev === 'data' && !this.pipes.length && !this.flowing)
-      this[RESUME]()
-    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
-      super.emit('readable')
-    else if (isEndish(ev) && this[EMITTED_END]) {
-      super.emit(ev)
-      this.removeAllListeners(ev)
-    } else if (ev === 'error' && this[EMITTED_ERROR]) {
-      if (this[ASYNC])
-        defer(() => fn.call(this, this[EMITTED_ERROR]))
-      else
-        fn.call(this, this[EMITTED_ERROR])
-    }
-    return ret
-  }
+/**
+ * Get the specificity of the language.
+ * @private
+ */
 
-  get emittedEnd () {
-    return this[EMITTED_END]
+function specify(language, spec, index) {
+  var p = parseLanguage(language)
+  if (!p) return null;
+  var s = 0;
+  if(spec.full.toLowerCase() === p.full.toLowerCase()){
+    s |= 4;
+  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
+    s |= 2;
+  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
+    s |= 1;
+  } else if (spec.full !== '*' ) {
+    return null
   }
 
-  [MAYBE_EMIT_END] () {
-    if (!this[EMITTING_END] &&
-        !this[EMITTED_END] &&
-        !this[DESTROYED] &&
-        this.buffer.length === 0 &&
-        this[EOF]) {
-      this[EMITTING_END] = true
-      this.emit('end')
-      this.emit('prefinish')
-      this.emit('finish')
-      if (this[CLOSED])
-        this.emit('close')
-      this[EMITTING_END] = false
-    }
+  return {
+    i: index,
+    o: spec.i,
+    q: spec.q,
+    s: s
   }
+};
 
-  emit (ev, data, ...extra) {
-    // error and close are only events allowed after calling destroy()
-    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
-      return
-    else if (ev === 'data') {
-      return !data ? false
-        : this[ASYNC] ? defer(() => this[EMITDATA](data))
-        : this[EMITDATA](data)
-    } else if (ev === 'end') {
-      return this[EMITEND]()
-    } else if (ev === 'close') {
-      this[CLOSED] = true
-      // don't emit close before 'end' and 'finish'
-      if (!this[EMITTED_END] && !this[DESTROYED])
-        return
-      const ret = super.emit('close')
-      this.removeAllListeners('close')
-      return ret
-    } else if (ev === 'error') {
-      this[EMITTED_ERROR] = data
-      const ret = super.emit('error', data)
-      this[MAYBE_EMIT_END]()
-      return ret
-    } else if (ev === 'resume') {
-      const ret = super.emit('resume')
-      this[MAYBE_EMIT_END]()
-      return ret
-    } else if (ev === 'finish' || ev === 'prefinish') {
-      const ret = super.emit(ev)
-      this.removeAllListeners(ev)
-      return ret
-    }
+/**
+ * Get the preferred languages from an Accept-Language header.
+ * @public
+ */
 
-    // Some other unknown event
-    const ret = super.emit(ev, data, ...extra)
-    this[MAYBE_EMIT_END]()
-    return ret
-  }
+function preferredLanguages(accept, provided) {
+  // RFC 2616 sec 14.4: no header = *
+  var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');
 
-  [EMITDATA] (data) {
-    for (const p of this.pipes) {
-      if (p.dest.write(data) === false)
-        this.pause()
-    }
-    const ret = super.emit('data', data)
-    this[MAYBE_EMIT_END]()
-    return ret
+  if (!provided) {
+    // sorted list of all languages
+    return accepts
+      .filter(isQuality)
+      .sort(compareSpecs)
+      .map(getFullLanguage);
   }
 
-  [EMITEND] () {
-    if (this[EMITTED_END])
-      return
+  var priorities = provided.map(function getPriority(type, index) {
+    return getLanguagePriority(type, accepts, index);
+  });
 
-    this[EMITTED_END] = true
-    this.readable = false
-    if (this[ASYNC])
-      defer(() => this[EMITEND2]())
-    else
-      this[EMITEND2]()
-  }
+  // sorted list of accepted languages
+  return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
+    return provided[priorities.indexOf(priority)];
+  });
+}
 
-  [EMITEND2] () {
-    if (this[DECODER]) {
-      const data = this[DECODER].end()
-      if (data) {
-        for (const p of this.pipes) {
-          p.dest.write(data)
-        }
-        super.emit('data', data)
-      }
-    }
+/**
+ * Compare two specs.
+ * @private
+ */
 
-    for (const p of this.pipes) {
-      p.end()
-    }
-    const ret = super.emit('end')
-    this.removeAllListeners('end')
-    return ret
-  }
+function compareSpecs(a, b) {
+  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+}
 
-  // const all = await stream.collect()
-  collect () {
-    const buf = []
-    if (!this[OBJECTMODE])
-      buf.dataLength = 0
-    // set the promise first, in case an error is raised
-    // by triggering the flow here.
-    const p = this.promise()
-    this.on('data', c => {
-      buf.push(c)
-      if (!this[OBJECTMODE])
-        buf.dataLength += c.length
-    })
-    return p.then(() => buf)
-  }
+/**
+ * Get full language string.
+ * @private
+ */
+
+function getFullLanguage(spec) {
+  return spec.full;
+}
+
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
+
+function isQuality(spec) {
+  return spec.q > 0;
+}
 
-  // const data = await stream.concat()
-  concat () {
-    return this[OBJECTMODE]
-      ? Promise.reject(new Error('cannot concat in objectMode'))
-      : this.collect().then(buf =>
-          this[OBJECTMODE]
-            ? Promise.reject(new Error('cannot concat in objectMode'))
-            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
-  }
 
-  // stream.promise().then(() => done, er => emitted error)
-  promise () {
-    return new Promise((resolve, reject) => {
-      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
-      this.on('error', er => reject(er))
-      this.on('end', () => resolve())
-    })
-  }
+/***/ }),
 
-  // for await (let chunk of stream)
-  [ASYNCITERATOR] () {
-    const next = () => {
-      const res = this.read()
-      if (res !== null)
-        return Promise.resolve({ done: false, value: res })
+/***/ 53672:
+/***/ ((module) => {
 
-      if (this[EOF])
-        return Promise.resolve({ done: true })
+"use strict";
+/**
+ * negotiator
+ * Copyright(c) 2012 Isaac Z. Schlueter
+ * Copyright(c) 2014 Federico Romero
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
 
-      let resolve = null
-      let reject = null
-      const onerr = er => {
-        this.removeListener('data', ondata)
-        this.removeListener('end', onend)
-        reject(er)
-      }
-      const ondata = value => {
-        this.removeListener('error', onerr)
-        this.removeListener('end', onend)
-        this.pause()
-        resolve({ value: value, done: !!this[EOF] })
-      }
-      const onend = () => {
-        this.removeListener('error', onerr)
-        this.removeListener('data', ondata)
-        resolve({ done: true })
-      }
-      const ondestroy = () => onerr(new Error('stream destroyed'))
-      return new Promise((res, rej) => {
-        reject = rej
-        resolve = res
-        this.once(DESTROYED, ondestroy)
-        this.once('error', onerr)
-        this.once('end', onend)
-        this.once('data', ondata)
-      })
-    }
 
-    return { next }
-  }
 
-  // for (let chunk of stream)
-  [ITERATOR] () {
-    const next = () => {
-      const value = this.read()
-      const done = value === null
-      return { value, done }
-    }
-    return { next }
-  }
+/**
+ * Module exports.
+ * @public
+ */
 
-  destroy (er) {
-    if (this[DESTROYED]) {
-      if (er)
-        this.emit('error', er)
-      else
-        this.emit(DESTROYED)
-      return this
-    }
+module.exports = preferredMediaTypes;
+module.exports.preferredMediaTypes = preferredMediaTypes;
 
-    this[DESTROYED] = true
+/**
+ * Module variables.
+ * @private
+ */
 
-    // throw away all buffered data, it's never coming out
-    this.buffer.length = 0
-    this[BUFFERLENGTH] = 0
+var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
 
-    if (typeof this.close === 'function' && !this[CLOSED])
-      this.close()
+/**
+ * Parse the Accept header.
+ * @private
+ */
 
-    if (er)
-      this.emit('error', er)
-    else // if no error to emit, still reject pending promises
-      this.emit(DESTROYED)
+function parseAccept(accept) {
+  var accepts = splitMediaTypes(accept);
 
-    return this
-  }
+  for (var i = 0, j = 0; i < accepts.length; i++) {
+    var mediaType = parseMediaType(accepts[i].trim(), i);
 
-  static isStream (s) {
-    return !!s && (s instanceof Minipass || s instanceof Stream ||
-      s instanceof EE && (
-        typeof s.pipe === 'function' || // readable
-        (typeof s.write === 'function' && typeof s.end === 'function') // writable
-      ))
+    if (mediaType) {
+      accepts[j++] = mediaType;
+    }
   }
+
+  // trim accepts
+  accepts.length = j;
+
+  return accepts;
 }
 
+/**
+ * Parse a media type from the Accept header.
+ * @private
+ */
 
-/***/ }),
+function parseMediaType(str, i) {
+  var match = simpleMediaTypeRegExp.exec(str);
+  if (!match) return null;
 
-/***/ 52899:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+  var params = Object.create(null);
+  var q = 1;
+  var subtype = match[2];
+  var type = match[1];
 
-const Minipass = __nccwpck_require__(45485)
-const EE = __nccwpck_require__(24434)
-const isStream = s => s && s instanceof EE && (
-  typeof s.pipe === 'function' || // readable
-  (typeof s.write === 'function' && typeof s.end === 'function') // writable
-)
+  if (match[3]) {
+    var kvps = splitParameters(match[3]).map(splitKeyValuePair);
 
-const _head = Symbol('_head')
-const _tail = Symbol('_tail')
-const _linkStreams = Symbol('_linkStreams')
-const _setHead = Symbol('_setHead')
-const _setTail = Symbol('_setTail')
-const _onError = Symbol('_onError')
-const _onData = Symbol('_onData')
-const _onEnd = Symbol('_onEnd')
-const _onDrain = Symbol('_onDrain')
-const _streams = Symbol('_streams')
-class Pipeline extends Minipass {
-  constructor (opts, ...streams) {
-    if (isStream(opts)) {
-      streams.unshift(opts)
-      opts = {}
-    }
+    for (var j = 0; j < kvps.length; j++) {
+      var pair = kvps[j];
+      var key = pair[0].toLowerCase();
+      var val = pair[1];
 
-    super(opts)
-    this[_streams] = []
-    if (streams.length)
-      this.push(...streams)
-  }
+      // get the value, unwrapping quotes
+      var value = val && val[0] === '"' && val[val.length - 1] === '"'
+        ? val.slice(1, -1)
+        : val;
 
-  [_linkStreams] (streams) {
-    // reduce takes (left,right), and we return right to make it the
-    // new left value.
-    return streams.reduce((src, dest) => {
-      src.on('error', er => dest.emit('error', er))
-      src.pipe(dest)
-      return dest
-    })
+      if (key === 'q') {
+        q = parseFloat(value);
+        break;
+      }
+
+      // store parameter
+      params[key] = value;
+    }
   }
 
-  push (...streams) {
-    this[_streams].push(...streams)
-    if (this[_tail])
-      streams.unshift(this[_tail])
+  return {
+    type: type,
+    subtype: subtype,
+    params: params,
+    q: q,
+    i: i
+  };
+}
 
-    const linkRet = this[_linkStreams](streams)
+/**
+ * Get the priority of a media type.
+ * @private
+ */
 
-    this[_setTail](linkRet)
-    if (!this[_head])
-      this[_setHead](streams[0])
-  }
+function getMediaTypePriority(type, accepted, index) {
+  var priority = {o: -1, q: 0, s: 0};
 
-  unshift (...streams) {
-    this[_streams].unshift(...streams)
-    if (this[_head])
-      streams.push(this[_head])
+  for (var i = 0; i < accepted.length; i++) {
+    var spec = specify(type, accepted[i], index);
 
-    const linkRet = this[_linkStreams](streams)
-    this[_setHead](streams[0])
-    if (!this[_tail])
-      this[_setTail](linkRet)
+    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+      priority = spec;
+    }
   }
 
-  destroy (er) {
-    // set fire to the whole thing.
-    this[_streams].forEach(s =>
-      typeof s.destroy === 'function' && s.destroy())
-    return super.destroy(er)
-  }
+  return priority;
+}
 
-  // readable interface -> tail
-  [_setTail] (stream) {
-    this[_tail] = stream
-    stream.on('error', er => this[_onError](stream, er))
-    stream.on('data', chunk => this[_onData](stream, chunk))
-    stream.on('end', () => this[_onEnd](stream))
-    stream.on('finish', () => this[_onEnd](stream))
-  }
+/**
+ * Get the specificity of the media type.
+ * @private
+ */
 
-  // errors proxied down the pipeline
-  // they're considered part of the "read" interface
-  [_onError] (stream, er) {
-    if (stream === this[_tail])
-      this.emit('error', er)
-  }
-  [_onData] (stream, chunk) {
-    if (stream === this[_tail])
-      super.write(chunk)
-  }
-  [_onEnd] (stream) {
-    if (stream === this[_tail])
-      super.end()
-  }
-  pause () {
-    super.pause()
-    return this[_tail] && this[_tail].pause && this[_tail].pause()
-  }
+function specify(type, spec, index) {
+  var p = parseMediaType(type);
+  var s = 0;
 
-  // NB: Minipass calls its internal private [RESUME] method during
-  // pipe drains, to avoid hazards where stream.resume() is overridden.
-  // Thus, we need to listen to the resume *event*, not override the
-  // resume() method, and proxy *that* to the tail.
-  emit (ev, ...args) {
-    if (ev === 'resume' && this[_tail] && this[_tail].resume)
-      this[_tail].resume()
-    return super.emit(ev, ...args)
+  if (!p) {
+    return null;
   }
 
-  // writable interface -> head
-  [_setHead] (stream) {
-    this[_head] = stream
-    stream.on('drain', () => this[_onDrain](stream))
+  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
+    s |= 4
+  } else if(spec.type != '*') {
+    return null;
   }
-  [_onDrain] (stream) {
-    if (stream === this[_head])
-      this.emit('drain')
+
+  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
+    s |= 2
+  } else if(spec.subtype != '*') {
+    return null;
   }
-  write (chunk, enc, cb) {
-    return this[_head].write(chunk, enc, cb) &&
-      (this.flowing || this.buffer.length === 0)
+
+  var keys = Object.keys(spec.params);
+  if (keys.length > 0) {
+    if (keys.every(function (k) {
+      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
+    })) {
+      s |= 1
+    } else {
+      return null
+    }
   }
-  end (chunk, enc, cb) {
-    this[_head].end(chunk, enc, cb)
-    return this
+
+  return {
+    i: index,
+    o: spec.i,
+    q: spec.q,
+    s: s,
   }
 }
 
-module.exports = Pipeline
+/**
+ * Get the preferred media types from an Accept header.
+ * @public
+ */
 
+function preferredMediaTypes(accept, provided) {
+  // RFC 2616 sec 14.2: no header = */*
+  var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');
 
-/***/ }),
+  if (!provided) {
+    // sorted list of all types
+    return accepts
+      .filter(isQuality)
+      .sort(compareSpecs)
+      .map(getFullType);
+  }
 
-/***/ 45485:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+  var priorities = provided.map(function getPriority(type, index) {
+    return getMediaTypePriority(type, accepts, index);
+  });
 
-"use strict";
+  // sorted list of accepted types
+  return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
+    return provided[priorities.indexOf(priority)];
+  });
+}
 
-const proc = typeof process === 'object' && process ? process : {
-  stdout: null,
-  stderr: null,
+/**
+ * Compare two specs.
+ * @private
+ */
+
+function compareSpecs(a, b) {
+  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
 }
-const EE = __nccwpck_require__(24434)
-const Stream = __nccwpck_require__(2203)
-const SD = (__nccwpck_require__(13193).StringDecoder)
 
-const EOF = Symbol('EOF')
-const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
-const EMITTED_END = Symbol('emittedEnd')
-const EMITTING_END = Symbol('emittingEnd')
-const EMITTED_ERROR = Symbol('emittedError')
-const CLOSED = Symbol('closed')
-const READ = Symbol('read')
-const FLUSH = Symbol('flush')
-const FLUSHCHUNK = Symbol('flushChunk')
-const ENCODING = Symbol('encoding')
-const DECODER = Symbol('decoder')
-const FLOWING = Symbol('flowing')
-const PAUSED = Symbol('paused')
-const RESUME = Symbol('resume')
-const BUFFERLENGTH = Symbol('bufferLength')
-const BUFFERPUSH = Symbol('bufferPush')
-const BUFFERSHIFT = Symbol('bufferShift')
-const OBJECTMODE = Symbol('objectMode')
-const DESTROYED = Symbol('destroyed')
-const EMITDATA = Symbol('emitData')
-const EMITEND = Symbol('emitEnd')
-const EMITEND2 = Symbol('emitEnd2')
-const ASYNC = Symbol('async')
+/**
+ * Get full type string.
+ * @private
+ */
 
-const defer = fn => Promise.resolve().then(fn)
+function getFullType(spec) {
+  return spec.type + '/' + spec.subtype;
+}
 
-// TODO remove when Node v8 support drops
-const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
-const ASYNCITERATOR = doIter && Symbol.asyncIterator
-  || Symbol('asyncIterator not implemented')
-const ITERATOR = doIter && Symbol.iterator
-  || Symbol('iterator not implemented')
+/**
+ * Check if a spec has any quality.
+ * @private
+ */
 
-// events that mean 'the stream is over'
-// these are treated specially, and re-emitted
-// if they are listened for after emitting.
-const isEndish = ev =>
-  ev === 'end' ||
-  ev === 'finish' ||
-  ev === 'prefinish'
+function isQuality(spec) {
+  return spec.q > 0;
+}
 
-const isArrayBuffer = b => b instanceof ArrayBuffer ||
-  typeof b === 'object' &&
-  b.constructor &&
-  b.constructor.name === 'ArrayBuffer' &&
-  b.byteLength >= 0
+/**
+ * Count the number of quotes in a string.
+ * @private
+ */
 
-const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
+function quoteCount(string) {
+  var count = 0;
+  var index = 0;
 
-class Pipe {
-  constructor (src, dest, opts) {
-    this.src = src
-    this.dest = dest
-    this.opts = opts
-    this.ondrain = () => src[RESUME]()
-    dest.on('drain', this.ondrain)
-  }
-  unpipe () {
-    this.dest.removeListener('drain', this.ondrain)
-  }
-  // istanbul ignore next - only here for the prototype
-  proxyErrors () {}
-  end () {
-    this.unpipe()
-    if (this.opts.end)
-      this.dest.end()
+  while ((index = string.indexOf('"', index)) !== -1) {
+    count++;
+    index++;
   }
+
+  return count;
 }
 
-class PipeProxyErrors extends Pipe {
-  unpipe () {
-    this.src.removeListener('error', this.proxyErrors)
-    super.unpipe()
-  }
-  constructor (src, dest, opts) {
-    super(src, dest, opts)
-    this.proxyErrors = er => dest.emit('error', er)
-    src.on('error', this.proxyErrors)
+/**
+ * Split a key value pair.
+ * @private
+ */
+
+function splitKeyValuePair(str) {
+  var index = str.indexOf('=');
+  var key;
+  var val;
+
+  if (index === -1) {
+    key = str;
+  } else {
+    key = str.slice(0, index);
+    val = str.slice(index + 1);
   }
+
+  return [key, val];
 }
 
-module.exports = class Minipass extends Stream {
-  constructor (options) {
-    super()
-    this[FLOWING] = false
-    // whether we're explicitly paused
-    this[PAUSED] = false
-    this.pipes = []
-    this.buffer = []
-    this[OBJECTMODE] = options && options.objectMode || false
-    if (this[OBJECTMODE])
-      this[ENCODING] = null
-    else
-      this[ENCODING] = options && options.encoding || null
-    if (this[ENCODING] === 'buffer')
-      this[ENCODING] = null
-    this[ASYNC] = options && !!options.async || false
-    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
-    this[EOF] = false
-    this[EMITTED_END] = false
-    this[EMITTING_END] = false
-    this[CLOSED] = false
-    this[EMITTED_ERROR] = null
-    this.writable = true
-    this.readable = true
-    this[BUFFERLENGTH] = 0
-    this[DESTROYED] = false
+/**
+ * Split an Accept header into media types.
+ * @private
+ */
+
+function splitMediaTypes(accept) {
+  var accepts = accept.split(',');
+
+  for (var i = 1, j = 0; i < accepts.length; i++) {
+    if (quoteCount(accepts[j]) % 2 == 0) {
+      accepts[++j] = accepts[i];
+    } else {
+      accepts[j] += ',' + accepts[i];
+    }
   }
 
-  get bufferLength () { return this[BUFFERLENGTH] }
+  // trim accepts
+  accepts.length = j + 1;
 
-  get encoding () { return this[ENCODING] }
-  set encoding (enc) {
-    if (this[OBJECTMODE])
-      throw new Error('cannot set encoding in objectMode')
+  return accepts;
+}
 
-    if (this[ENCODING] && enc !== this[ENCODING] &&
-        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
-      throw new Error('cannot change encoding')
+/**
+ * Split a string of parameters.
+ * @private
+ */
 
-    if (this[ENCODING] !== enc) {
-      this[DECODER] = enc ? new SD(enc) : null
-      if (this.buffer.length)
-        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
+function splitParameters(str) {
+  var parameters = str.split(';');
+
+  for (var i = 1, j = 0; i < parameters.length; i++) {
+    if (quoteCount(parameters[j]) % 2 == 0) {
+      parameters[++j] = parameters[i];
+    } else {
+      parameters[j] += ';' + parameters[i];
     }
+  }
 
-    this[ENCODING] = enc
+  // trim parameters
+  parameters.length = j + 1;
+
+  for (var i = 0; i < parameters.length; i++) {
+    parameters[i] = parameters[i].trim();
   }
 
-  setEncoding (enc) {
-    this.encoding = enc
+  return parameters;
+}
+
+
+/***/ }),
+
+/***/ 55560:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+var wrappy = __nccwpck_require__(58264)
+module.exports = wrappy(once)
+module.exports.strict = wrappy(onceStrict)
+
+once.proto = once(function () {
+  Object.defineProperty(Function.prototype, 'once', {
+    value: function () {
+      return once(this)
+    },
+    configurable: true
+  })
+
+  Object.defineProperty(Function.prototype, 'onceStrict', {
+    value: function () {
+      return onceStrict(this)
+    },
+    configurable: true
+  })
+})
+
+function once (fn) {
+  var f = function () {
+    if (f.called) return f.value
+    f.called = true
+    return f.value = fn.apply(this, arguments)
   }
+  f.called = false
+  return f
+}
 
-  get objectMode () { return this[OBJECTMODE] }
-  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
+function onceStrict (fn) {
+  var f = function () {
+    if (f.called)
+      throw new Error(f.onceError)
+    f.called = true
+    return f.value = fn.apply(this, arguments)
+  }
+  var name = fn.name || 'Function wrapped with `once`'
+  f.onceError = name + " shouldn't be called more than once"
+  f.called = false
+  return f
+}
 
-  get ['async'] () { return this[ASYNC] }
-  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }
 
-  write (chunk, encoding, cb) {
-    if (this[EOF])
-      throw new Error('write after end')
+/***/ }),
 
-    if (this[DESTROYED]) {
-      this.emit('error', Object.assign(
-        new Error('Cannot call write after a stream was destroyed'),
-        { code: 'ERR_STREAM_DESTROYED' }
-      ))
-      return true
-    }
+/***/ 26687:
+/***/ ((module) => {
 
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
+const META = Symbol('proc-log.meta')
+module.exports = {
+  META: META,
+  output: {
+    LEVELS: [
+      'standard',
+      'error',
+      'buffer',
+      'flush',
+    ],
+    KEYS: {
+      standard: 'standard',
+      error: 'error',
+      buffer: 'buffer',
+      flush: 'flush',
+    },
+    standard: function (...args) {
+      return process.emit('output', 'standard', ...args)
+    },
+    error: function (...args) {
+      return process.emit('output', 'error', ...args)
+    },
+    buffer: function (...args) {
+      return process.emit('output', 'buffer', ...args)
+    },
+    flush: function (...args) {
+      return process.emit('output', 'flush', ...args)
+    },
+  },
+  log: {
+    LEVELS: [
+      'notice',
+      'error',
+      'warn',
+      'info',
+      'verbose',
+      'http',
+      'silly',
+      'timing',
+      'pause',
+      'resume',
+    ],
+    KEYS: {
+      notice: 'notice',
+      error: 'error',
+      warn: 'warn',
+      info: 'info',
+      verbose: 'verbose',
+      http: 'http',
+      silly: 'silly',
+      timing: 'timing',
+      pause: 'pause',
+      resume: 'resume',
+    },
+    error: function (...args) {
+      return process.emit('log', 'error', ...args)
+    },
+    notice: function (...args) {
+      return process.emit('log', 'notice', ...args)
+    },
+    warn: function (...args) {
+      return process.emit('log', 'warn', ...args)
+    },
+    info: function (...args) {
+      return process.emit('log', 'info', ...args)
+    },
+    verbose: function (...args) {
+      return process.emit('log', 'verbose', ...args)
+    },
+    http: function (...args) {
+      return process.emit('log', 'http', ...args)
+    },
+    silly: function (...args) {
+      return process.emit('log', 'silly', ...args)
+    },
+    timing: function (...args) {
+      return process.emit('log', 'timing', ...args)
+    },
+    pause: function () {
+      return process.emit('log', 'pause')
+    },
+    resume: function () {
+      return process.emit('log', 'resume')
+    },
+  },
+  time: {
+    LEVELS: [
+      'start',
+      'end',
+    ],
+    KEYS: {
+      start: 'start',
+      end: 'end',
+    },
+    start: function (name, fn) {
+      process.emit('time', 'start', name)
+      function end () {
+        return process.emit('time', 'end', name)
+      }
+      if (typeof fn === 'function') {
+        const res = fn()
+        if (res && res.finally) {
+          return res.finally(end)
+        }
+        end()
+        return res
+      }
+      return end
+    },
+    end: function (name) {
+      return process.emit('time', 'end', name)
+    },
+  },
+  input: {
+    LEVELS: [
+      'start',
+      'end',
+      'read',
+    ],
+    KEYS: {
+      start: 'start',
+      end: 'end',
+      read: 'read',
+    },
+    start: function (fn) {
+      process.emit('input', 'start')
+      function end () {
+        return process.emit('input', 'end')
+      }
+      if (typeof fn === 'function') {
+        const res = fn()
+        if (res && res.finally) {
+          return res.finally(end)
+        }
+        end()
+        return res
+      }
+      return end
+    },
+    end: function () {
+      return process.emit('input', 'end')
+    },
+    read: function (...args) {
+      let resolve, reject
+      const promise = new Promise((_resolve, _reject) => {
+        resolve = _resolve
+        reject = _reject
+      })
+      process.emit('input', 'read', resolve, reject, ...args)
+      return promise
+    },
+  },
+}
 
-    if (!encoding)
-      encoding = 'utf8'
 
-    const fn = this[ASYNC] ? defer : f => f()
+/***/ }),
 
-    // convert array buffers and typed array views into buffers
-    // at some point in the future, we may want to do the opposite!
-    // leave strings and buffers as-is
-    // anything else switches us into object mode
-    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
-      if (isArrayBufferView(chunk))
-        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
-      else if (isArrayBuffer(chunk))
-        chunk = Buffer.from(chunk)
-      else if (typeof chunk !== 'string')
-        // use the setter so we throw if we have encoding set
-        this.objectMode = true
-    }
+/***/ 90390:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    // handle object mode up front, since it's simpler
-    // this yields better performance, fewer checks later.
-    if (this[OBJECTMODE]) {
-      /* istanbul ignore if - maybe impossible? */
-      if (this.flowing && this[BUFFERLENGTH] !== 0)
-        this[FLUSH](true)
+"use strict";
 
-      if (this.flowing)
-        this.emit('data', chunk)
-      else
-        this[BUFFERPUSH](chunk)
 
-      if (this[BUFFERLENGTH] !== 0)
-        this.emit('readable')
+var errcode = __nccwpck_require__(14339);
+var retry = __nccwpck_require__(5546);
 
-      if (cb)
-        fn(cb)
+var hasOwn = Object.prototype.hasOwnProperty;
 
-      return this.flowing
-    }
+function isRetryError(err) {
+    return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried');
+}
 
-    // at this point the chunk is a buffer or string
-    // don't buffer it up or send it to the decoder
-    if (!chunk.length) {
-      if (this[BUFFERLENGTH] !== 0)
-        this.emit('readable')
-      if (cb)
-        fn(cb)
-      return this.flowing
-    }
+function promiseRetry(fn, options) {
+    var temp;
+    var operation;
 
-    // fast-path writing strings of same encoding to a stream with
-    // an empty buffer, skipping the buffer/decoder dance
-    if (typeof chunk === 'string' &&
-        // unless it is a string already ready for us to use
-        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
-      chunk = Buffer.from(chunk, encoding)
+    if (typeof fn === 'object' && typeof options === 'function') {
+        // Swap options and fn when using alternate signature (options, fn)
+        temp = options;
+        options = fn;
+        fn = temp;
     }
 
-    if (Buffer.isBuffer(chunk) && this[ENCODING])
-      chunk = this[DECODER].write(chunk)
+    operation = retry.operation(options);
 
-    // Note: flushing CAN potentially switch us into not-flowing mode
-    if (this.flowing && this[BUFFERLENGTH] !== 0)
-      this[FLUSH](true)
+    return new Promise(function (resolve, reject) {
+        operation.attempt(function (number) {
+            Promise.resolve()
+            .then(function () {
+                return fn(function (err) {
+                    if (isRetryError(err)) {
+                        err = err.retried;
+                    }
 
-    if (this.flowing)
-      this.emit('data', chunk)
-    else
-      this[BUFFERPUSH](chunk)
+                    throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err });
+                }, number);
+            })
+            .then(resolve, function (err) {
+                if (isRetryError(err)) {
+                    err = err.retried;
 
-    if (this[BUFFERLENGTH] !== 0)
-      this.emit('readable')
+                    if (operation.retry(err || new Error())) {
+                        return;
+                    }
+                }
 
-    if (cb)
-      fn(cb)
+                reject(err);
+            });
+        });
+    });
+}
 
-    return this.flowing
-  }
+module.exports = promiseRetry;
 
-  read (n) {
-    if (this[DESTROYED])
-      return null
 
-    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
-      this[MAYBE_EMIT_END]()
-      return null
-    }
+/***/ }),
 
-    if (this[OBJECTMODE])
-      n = null
+/***/ 5546:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
-      if (this.encoding)
-        this.buffer = [this.buffer.join('')]
-      else
-        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
-    }
+module.exports = __nccwpck_require__(67084);
 
-    const ret = this[READ](n || null, this.buffer[0])
-    this[MAYBE_EMIT_END]()
-    return ret
-  }
+/***/ }),
 
-  [READ] (n, chunk) {
-    if (n === chunk.length || n === null)
-      this[BUFFERSHIFT]()
-    else {
-      this.buffer[0] = chunk.slice(n)
-      chunk = chunk.slice(0, n)
-      this[BUFFERLENGTH] -= n
-    }
+/***/ 67084:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
-    this.emit('data', chunk)
+var RetryOperation = __nccwpck_require__(39538);
 
-    if (!this.buffer.length && !this[EOF])
-      this.emit('drain')
+exports.operation = function(options) {
+  var timeouts = exports.timeouts(options);
+  return new RetryOperation(timeouts, {
+      forever: options && options.forever,
+      unref: options && options.unref,
+      maxRetryTime: options && options.maxRetryTime
+  });
+};
 
-    return chunk
+exports.timeouts = function(options) {
+  if (options instanceof Array) {
+    return [].concat(options);
   }
 
-  end (chunk, encoding, cb) {
-    if (typeof chunk === 'function')
-      cb = chunk, chunk = null
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
-    if (chunk)
-      this.write(chunk, encoding)
-    if (cb)
-      this.once('end', cb)
-    this[EOF] = true
-    this.writable = false
+  var opts = {
+    retries: 10,
+    factor: 2,
+    minTimeout: 1 * 1000,
+    maxTimeout: Infinity,
+    randomize: false
+  };
+  for (var key in options) {
+    opts[key] = options[key];
+  }
 
-    // if we haven't written anything, then go ahead and emit,
-    // even if we're not reading.
-    // we'll re-emit if a new 'end' listener is added anyway.
-    // This makes MP more suitable to write-only use cases.
-    if (this.flowing || !this[PAUSED])
-      this[MAYBE_EMIT_END]()
-    return this
+  if (opts.minTimeout > opts.maxTimeout) {
+    throw new Error('minTimeout is greater than maxTimeout');
   }
 
-  // don't let the internal resume be overwritten
-  [RESUME] () {
-    if (this[DESTROYED])
-      return
+  var timeouts = [];
+  for (var i = 0; i < opts.retries; i++) {
+    timeouts.push(this.createTimeout(i, opts));
+  }
 
-    this[PAUSED] = false
-    this[FLOWING] = true
-    this.emit('resume')
-    if (this.buffer.length)
-      this[FLUSH]()
-    else if (this[EOF])
-      this[MAYBE_EMIT_END]()
-    else
-      this.emit('drain')
+  if (options && options.forever && !timeouts.length) {
+    timeouts.push(this.createTimeout(i, opts));
   }
 
-  resume () {
-    return this[RESUME]()
+  // sort the array numerically ascending
+  timeouts.sort(function(a,b) {
+    return a - b;
+  });
+
+  return timeouts;
+};
+
+exports.createTimeout = function(attempt, opts) {
+  var random = (opts.randomize)
+    ? (Math.random() + 1)
+    : 1;
+
+  var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
+  timeout = Math.min(timeout, opts.maxTimeout);
+
+  return timeout;
+};
+
+exports.wrap = function(obj, options, methods) {
+  if (options instanceof Array) {
+    methods = options;
+    options = null;
   }
 
-  pause () {
-    this[FLOWING] = false
-    this[PAUSED] = true
+  if (!methods) {
+    methods = [];
+    for (var key in obj) {
+      if (typeof obj[key] === 'function') {
+        methods.push(key);
+      }
+    }
   }
 
-  get destroyed () {
-    return this[DESTROYED]
+  for (var i = 0; i < methods.length; i++) {
+    var method   = methods[i];
+    var original = obj[method];
+
+    obj[method] = function retryWrapper(original) {
+      var op       = exports.operation(options);
+      var args     = Array.prototype.slice.call(arguments, 1);
+      var callback = args.pop();
+
+      args.push(function(err) {
+        if (op.retry(err)) {
+          return;
+        }
+        if (err) {
+          arguments[0] = op.mainError();
+        }
+        callback.apply(this, arguments);
+      });
+
+      op.attempt(function() {
+        original.apply(obj, args);
+      });
+    }.bind(obj, original);
+    obj[method].options = options;
   }
+};
 
-  get flowing () {
-    return this[FLOWING]
-  }
 
-  get paused () {
-    return this[PAUSED]
-  }
+/***/ }),
 
-  [BUFFERPUSH] (chunk) {
-    if (this[OBJECTMODE])
-      this[BUFFERLENGTH] += 1
-    else
-      this[BUFFERLENGTH] += chunk.length
-    this.buffer.push(chunk)
-  }
+/***/ 39538:
+/***/ ((module) => {
 
-  [BUFFERSHIFT] () {
-    if (this.buffer.length) {
-      if (this[OBJECTMODE])
-        this[BUFFERLENGTH] -= 1
-      else
-        this[BUFFERLENGTH] -= this.buffer[0].length
-    }
-    return this.buffer.shift()
+function RetryOperation(timeouts, options) {
+  // Compatibility for the old (timeouts, retryForever) signature
+  if (typeof options === 'boolean') {
+    options = { forever: options };
   }
 
-  [FLUSH] (noDrain) {
-    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
-
-    if (!noDrain && !this.buffer.length && !this[EOF])
-      this.emit('drain')
-  }
+  this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
+  this._timeouts = timeouts;
+  this._options = options || {};
+  this._maxRetryTime = options && options.maxRetryTime || Infinity;
+  this._fn = null;
+  this._errors = [];
+  this._attempts = 1;
+  this._operationTimeout = null;
+  this._operationTimeoutCb = null;
+  this._timeout = null;
+  this._operationStart = null;
 
-  [FLUSHCHUNK] (chunk) {
-    return chunk ? (this.emit('data', chunk), this.flowing) : false
+  if (this._options.forever) {
+    this._cachedTimeouts = this._timeouts.slice(0);
   }
+}
+module.exports = RetryOperation;
 
-  pipe (dest, opts) {
-    if (this[DESTROYED])
-      return
+RetryOperation.prototype.reset = function() {
+  this._attempts = 1;
+  this._timeouts = this._originalTimeouts;
+}
 
-    const ended = this[EMITTED_END]
-    opts = opts || {}
-    if (dest === proc.stdout || dest === proc.stderr)
-      opts.end = false
-    else
-      opts.end = opts.end !== false
-    opts.proxyErrors = !!opts.proxyErrors
+RetryOperation.prototype.stop = function() {
+  if (this._timeout) {
+    clearTimeout(this._timeout);
+  }
 
-    // piping an ended stream ends immediately
-    if (ended) {
-      if (opts.end)
-        dest.end()
-    } else {
-      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
-        : new PipeProxyErrors(this, dest, opts))
-      if (this[ASYNC])
-        defer(() => this[RESUME]())
-      else
-        this[RESUME]()
-    }
+  this._timeouts       = [];
+  this._cachedTimeouts = null;
+};
 
-    return dest
+RetryOperation.prototype.retry = function(err) {
+  if (this._timeout) {
+    clearTimeout(this._timeout);
   }
 
-  unpipe (dest) {
-    const p = this.pipes.find(p => p.dest === dest)
-    if (p) {
-      this.pipes.splice(this.pipes.indexOf(p), 1)
-      p.unpipe()
-    }
+  if (!err) {
+    return false;
   }
-
-  addListener (ev, fn) {
-    return this.on(ev, fn)
+  var currentTime = new Date().getTime();
+  if (err && currentTime - this._operationStart >= this._maxRetryTime) {
+    this._errors.unshift(new Error('RetryOperation timeout occurred'));
+    return false;
   }
 
-  on (ev, fn) {
-    const ret = super.on(ev, fn)
-    if (ev === 'data' && !this.pipes.length && !this.flowing)
-      this[RESUME]()
-    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
-      super.emit('readable')
-    else if (isEndish(ev) && this[EMITTED_END]) {
-      super.emit(ev)
-      this.removeAllListeners(ev)
-    } else if (ev === 'error' && this[EMITTED_ERROR]) {
-      if (this[ASYNC])
-        defer(() => fn.call(this, this[EMITTED_ERROR]))
-      else
-        fn.call(this, this[EMITTED_ERROR])
+  this._errors.push(err);
+
+  var timeout = this._timeouts.shift();
+  if (timeout === undefined) {
+    if (this._cachedTimeouts) {
+      // retry forever, only keep last error
+      this._errors.splice(this._errors.length - 1, this._errors.length);
+      this._timeouts = this._cachedTimeouts.slice(0);
+      timeout = this._timeouts.shift();
+    } else {
+      return false;
     }
-    return ret
   }
 
-  get emittedEnd () {
-    return this[EMITTED_END]
-  }
+  var self = this;
+  var timer = setTimeout(function() {
+    self._attempts++;
 
-  [MAYBE_EMIT_END] () {
-    if (!this[EMITTING_END] &&
-        !this[EMITTED_END] &&
-        !this[DESTROYED] &&
-        this.buffer.length === 0 &&
-        this[EOF]) {
-      this[EMITTING_END] = true
-      this.emit('end')
-      this.emit('prefinish')
-      this.emit('finish')
-      if (this[CLOSED])
-        this.emit('close')
-      this[EMITTING_END] = false
-    }
-  }
+    if (self._operationTimeoutCb) {
+      self._timeout = setTimeout(function() {
+        self._operationTimeoutCb(self._attempts);
+      }, self._operationTimeout);
 
-  emit (ev, data, ...extra) {
-    // error and close are only events allowed after calling destroy()
-    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
-      return
-    else if (ev === 'data') {
-      return !data ? false
-        : this[ASYNC] ? defer(() => this[EMITDATA](data))
-        : this[EMITDATA](data)
-    } else if (ev === 'end') {
-      return this[EMITEND]()
-    } else if (ev === 'close') {
-      this[CLOSED] = true
-      // don't emit close before 'end' and 'finish'
-      if (!this[EMITTED_END] && !this[DESTROYED])
-        return
-      const ret = super.emit('close')
-      this.removeAllListeners('close')
-      return ret
-    } else if (ev === 'error') {
-      this[EMITTED_ERROR] = data
-      const ret = super.emit('error', data)
-      this[MAYBE_EMIT_END]()
-      return ret
-    } else if (ev === 'resume') {
-      const ret = super.emit('resume')
-      this[MAYBE_EMIT_END]()
-      return ret
-    } else if (ev === 'finish' || ev === 'prefinish') {
-      const ret = super.emit(ev)
-      this.removeAllListeners(ev)
-      return ret
+      if (self._options.unref) {
+          self._timeout.unref();
+      }
     }
 
-    // Some other unknown event
-    const ret = super.emit(ev, data, ...extra)
-    this[MAYBE_EMIT_END]()
-    return ret
-  }
+    self._fn(self._attempts);
+  }, timeout);
 
-  [EMITDATA] (data) {
-    for (const p of this.pipes) {
-      if (p.dest.write(data) === false)
-        this.pause()
-    }
-    const ret = super.emit('data', data)
-    this[MAYBE_EMIT_END]()
-    return ret
+  if (this._options.unref) {
+      timer.unref();
   }
 
-  [EMITEND] () {
-    if (this[EMITTED_END])
-      return
+  return true;
+};
 
-    this[EMITTED_END] = true
-    this.readable = false
-    if (this[ASYNC])
-      defer(() => this[EMITEND2]())
-    else
-      this[EMITEND2]()
-  }
+RetryOperation.prototype.attempt = function(fn, timeoutOps) {
+  this._fn = fn;
 
-  [EMITEND2] () {
-    if (this[DECODER]) {
-      const data = this[DECODER].end()
-      if (data) {
-        for (const p of this.pipes) {
-          p.dest.write(data)
-        }
-        super.emit('data', data)
-      }
+  if (timeoutOps) {
+    if (timeoutOps.timeout) {
+      this._operationTimeout = timeoutOps.timeout;
     }
-
-    for (const p of this.pipes) {
-      p.end()
+    if (timeoutOps.cb) {
+      this._operationTimeoutCb = timeoutOps.cb;
     }
-    const ret = super.emit('end')
-    this.removeAllListeners('end')
-    return ret
-  }
-
-  // const all = await stream.collect()
-  collect () {
-    const buf = []
-    if (!this[OBJECTMODE])
-      buf.dataLength = 0
-    // set the promise first, in case an error is raised
-    // by triggering the flow here.
-    const p = this.promise()
-    this.on('data', c => {
-      buf.push(c)
-      if (!this[OBJECTMODE])
-        buf.dataLength += c.length
-    })
-    return p.then(() => buf)
   }
 
-  // const data = await stream.concat()
-  concat () {
-    return this[OBJECTMODE]
-      ? Promise.reject(new Error('cannot concat in objectMode'))
-      : this.collect().then(buf =>
-          this[OBJECTMODE]
-            ? Promise.reject(new Error('cannot concat in objectMode'))
-            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
+  var self = this;
+  if (this._operationTimeoutCb) {
+    this._timeout = setTimeout(function() {
+      self._operationTimeoutCb();
+    }, self._operationTimeout);
   }
 
-  // stream.promise().then(() => done, er => emitted error)
-  promise () {
-    return new Promise((resolve, reject) => {
-      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
-      this.on('error', er => reject(er))
-      this.on('end', () => resolve())
-    })
-  }
+  this._operationStart = new Date().getTime();
 
-  // for await (let chunk of stream)
-  [ASYNCITERATOR] () {
-    const next = () => {
-      const res = this.read()
-      if (res !== null)
-        return Promise.resolve({ done: false, value: res })
+  this._fn(this._attempts);
+};
 
-      if (this[EOF])
-        return Promise.resolve({ done: true })
+RetryOperation.prototype.try = function(fn) {
+  console.log('Using RetryOperation.try() is deprecated');
+  this.attempt(fn);
+};
 
-      let resolve = null
-      let reject = null
-      const onerr = er => {
-        this.removeListener('data', ondata)
-        this.removeListener('end', onend)
-        reject(er)
-      }
-      const ondata = value => {
-        this.removeListener('error', onerr)
-        this.removeListener('end', onend)
-        this.pause()
-        resolve({ value: value, done: !!this[EOF] })
-      }
-      const onend = () => {
-        this.removeListener('error', onerr)
-        this.removeListener('data', ondata)
-        resolve({ done: true })
-      }
-      const ondestroy = () => onerr(new Error('stream destroyed'))
-      return new Promise((res, rej) => {
-        reject = rej
-        resolve = res
-        this.once(DESTROYED, ondestroy)
-        this.once('error', onerr)
-        this.once('end', onend)
-        this.once('data', ondata)
-      })
-    }
+RetryOperation.prototype.start = function(fn) {
+  console.log('Using RetryOperation.start() is deprecated');
+  this.attempt(fn);
+};
 
-    return { next }
-  }
+RetryOperation.prototype.start = RetryOperation.prototype.try;
 
-  // for (let chunk of stream)
-  [ITERATOR] () {
-    const next = () => {
-      const value = this.read()
-      const done = value === null
-      return { value, done }
-    }
-    return { next }
-  }
+RetryOperation.prototype.errors = function() {
+  return this._errors;
+};
 
-  destroy (er) {
-    if (this[DESTROYED]) {
-      if (er)
-        this.emit('error', er)
-      else
-        this.emit(DESTROYED)
-      return this
-    }
+RetryOperation.prototype.attempts = function() {
+  return this._attempts;
+};
 
-    this[DESTROYED] = true
+RetryOperation.prototype.mainError = function() {
+  if (this._errors.length === 0) {
+    return null;
+  }
 
-    // throw away all buffered data, it's never coming out
-    this.buffer.length = 0
-    this[BUFFERLENGTH] = 0
+  var counts = {};
+  var mainError = null;
+  var mainErrorCount = 0;
 
-    if (typeof this.close === 'function' && !this[CLOSED])
-      this.close()
+  for (var i = 0; i < this._errors.length; i++) {
+    var error = this._errors[i];
+    var message = error.message;
+    var count = (counts[message] || 0) + 1;
 
-    if (er)
-      this.emit('error', er)
-    else // if no error to emit, still reject pending promises
-      this.emit(DESTROYED)
+    counts[message] = count;
 
-    return this
+    if (count >= mainErrorCount) {
+      mainError = error;
+      mainErrorCount = count;
+    }
   }
 
-  static isStream (s) {
-    return !!s && (s instanceof Minipass || s instanceof Stream ||
-      s instanceof EE && (
-        typeof s.pipe === 'function' || // readable
-        (typeof s.write === 'function' && typeof s.end === 'function') // writable
-      ))
-  }
-}
+  return mainError;
+};
 
 
 /***/ }),
 
-/***/ 48484:
+/***/ 12803:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-const Minipass = __nccwpck_require__(56670)
+"use strict";
+/* eslint-disable node/no-deprecated-api */
 
-class SizeError extends Error {
-  constructor (found, expect) {
-    super(`Bad data size: expected ${expect} bytes, but got ${found}`)
-    this.expect = expect
-    this.found = found
-    this.code = 'EBADSIZE'
-	  Error.captureStackTrace(this, this.constructor)
-  }
-  get name () {
-    return 'SizeError'
-  }
-}
 
-class MinipassSized extends Minipass {
-  constructor (options = {}) {
-    super(options)
 
-    if (options.objectMode)
-      throw new TypeError(`${
-        this.constructor.name
-      } streams only work with string and buffer data`)
+var buffer = __nccwpck_require__(20181)
+var Buffer = buffer.Buffer
 
-    this.found = 0
-    this.expect = options.size
-    if (typeof this.expect !== 'number' ||
-        this.expect > Number.MAX_SAFE_INTEGER ||
-        isNaN(this.expect) ||
-        this.expect < 0 ||
-        !isFinite(this.expect) ||
-        this.expect !== Math.floor(this.expect))
-      throw new Error('invalid expected size: ' + this.expect)
-  }
+var safer = {}
 
-  write (chunk, encoding, cb) {
-    const buffer = Buffer.isBuffer(chunk) ? chunk
-      : typeof chunk === 'string' ?
-        Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8')
-      : chunk
+var key
 
-    if (!Buffer.isBuffer(buffer)) {
-      this.emit('error', new TypeError(`${
-        this.constructor.name
-      } streams only work with string and buffer data`))
-      return false
-    }
+for (key in buffer) {
+  if (!buffer.hasOwnProperty(key)) continue
+  if (key === 'SlowBuffer' || key === 'Buffer') continue
+  safer[key] = buffer[key]
+}
 
-    this.found += buffer.length
-    if (this.found > this.expect)
-      this.emit('error', new SizeError(this.found, this.expect))
+var Safer = safer.Buffer = {}
+for (key in Buffer) {
+  if (!Buffer.hasOwnProperty(key)) continue
+  if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
+  Safer[key] = Buffer[key]
+}
 
-    return super.write(chunk, encoding, cb)
+safer.Buffer.prototype = Buffer.prototype
+
+if (!Safer.from || Safer.from === Uint8Array.from) {
+  Safer.from = function (value, encodingOrOffset, length) {
+    if (typeof value === 'number') {
+      throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
+    }
+    if (value && typeof value.length === 'undefined') {
+      throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
+    }
+    return Buffer(value, encodingOrOffset, length)
   }
+}
 
-  emit (ev, ...data) {
-    if (ev === 'end') {
-      if (this.found !== this.expect)
-        this.emit('error', new SizeError(this.found, this.expect))
+if (!Safer.alloc) {
+  Safer.alloc = function (size, fill, encoding) {
+    if (typeof size !== 'number') {
+      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
     }
-    return super.emit(ev, ...data)
+    if (size < 0 || size >= 2 * (1 << 30)) {
+      throw new RangeError('The value "' + size + '" is invalid for option "size"')
+    }
+    var buf = Buffer(size)
+    if (!fill || fill.length === 0) {
+      buf.fill(0)
+    } else if (typeof encoding === 'string') {
+      buf.fill(fill, encoding)
+    } else {
+      buf.fill(fill)
+    }
+    return buf
   }
 }
 
-MinipassSized.SizeError = SizeError
+if (!safer.kStringMaxLength) {
+  try {
+    safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
+  } catch (e) {
+    // we can't determine kStringMaxLength in environments where process.binding
+    // is unsupported, so let's not set it
+  }
+}
+
+if (!safer.constants) {
+  safer.constants = {
+    MAX_LENGTH: safer.kMaxLength
+  }
+  if (safer.kStringMaxLength) {
+    safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
+  }
+}
 
-module.exports = MinipassSized
+module.exports = safer
 
 
 /***/ }),
 
-/***/ 56670:
+/***/ 89379:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+const ANY = Symbol('SemVer ANY')
+// hoisted class for cyclic dependency
+class Comparator {
+  static get ANY () {
+    return ANY
+  }
 
-const proc = typeof process === 'object' && process ? process : {
-  stdout: null,
-  stderr: null,
-}
-const EE = __nccwpck_require__(24434)
-const Stream = __nccwpck_require__(2203)
-const SD = (__nccwpck_require__(13193).StringDecoder)
+  constructor (comp, options) {
+    options = parseOptions(options)
 
-const EOF = Symbol('EOF')
-const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
-const EMITTED_END = Symbol('emittedEnd')
-const EMITTING_END = Symbol('emittingEnd')
-const EMITTED_ERROR = Symbol('emittedError')
-const CLOSED = Symbol('closed')
-const READ = Symbol('read')
-const FLUSH = Symbol('flush')
-const FLUSHCHUNK = Symbol('flushChunk')
-const ENCODING = Symbol('encoding')
-const DECODER = Symbol('decoder')
-const FLOWING = Symbol('flowing')
-const PAUSED = Symbol('paused')
-const RESUME = Symbol('resume')
-const BUFFERLENGTH = Symbol('bufferLength')
-const BUFFERPUSH = Symbol('bufferPush')
-const BUFFERSHIFT = Symbol('bufferShift')
-const OBJECTMODE = Symbol('objectMode')
-const DESTROYED = Symbol('destroyed')
-const EMITDATA = Symbol('emitData')
-const EMITEND = Symbol('emitEnd')
-const EMITEND2 = Symbol('emitEnd2')
-const ASYNC = Symbol('async')
+    if (comp instanceof Comparator) {
+      if (comp.loose === !!options.loose) {
+        return comp
+      } else {
+        comp = comp.value
+      }
+    }
 
-const defer = fn => Promise.resolve().then(fn)
+    comp = comp.trim().split(/\s+/).join(' ')
+    debug('comparator', comp, options)
+    this.options = options
+    this.loose = !!options.loose
+    this.parse(comp)
 
-// TODO remove when Node v8 support drops
-const doIter = global._MP_NO_ITERATOR_SYMBOLS_  !== '1'
-const ASYNCITERATOR = doIter && Symbol.asyncIterator
-  || Symbol('asyncIterator not implemented')
-const ITERATOR = doIter && Symbol.iterator
-  || Symbol('iterator not implemented')
+    if (this.semver === ANY) {
+      this.value = ''
+    } else {
+      this.value = this.operator + this.semver.version
+    }
 
-// events that mean 'the stream is over'
-// these are treated specially, and re-emitted
-// if they are listened for after emitting.
-const isEndish = ev =>
-  ev === 'end' ||
-  ev === 'finish' ||
-  ev === 'prefinish'
+    debug('comp', this)
+  }
 
-const isArrayBuffer = b => b instanceof ArrayBuffer ||
-  typeof b === 'object' &&
-  b.constructor &&
-  b.constructor.name === 'ArrayBuffer' &&
-  b.byteLength >= 0
+  parse (comp) {
+    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
+    const m = comp.match(r)
 
-const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
+    if (!m) {
+      throw new TypeError(`Invalid comparator: ${comp}`)
+    }
 
-class Pipe {
-  constructor (src, dest, opts) {
-    this.src = src
-    this.dest = dest
-    this.opts = opts
-    this.ondrain = () => src[RESUME]()
-    dest.on('drain', this.ondrain)
-  }
-  unpipe () {
-    this.dest.removeListener('drain', this.ondrain)
-  }
-  // istanbul ignore next - only here for the prototype
-  proxyErrors () {}
-  end () {
-    this.unpipe()
-    if (this.opts.end)
-      this.dest.end()
-  }
-}
+    this.operator = m[1] !== undefined ? m[1] : ''
+    if (this.operator === '=') {
+      this.operator = ''
+    }
 
-class PipeProxyErrors extends Pipe {
-  unpipe () {
-    this.src.removeListener('error', this.proxyErrors)
-    super.unpipe()
-  }
-  constructor (src, dest, opts) {
-    super(src, dest, opts)
-    this.proxyErrors = er => dest.emit('error', er)
-    src.on('error', this.proxyErrors)
+    // if it literally is just '>' or '' then allow anything.
+    if (!m[2]) {
+      this.semver = ANY
+    } else {
+      this.semver = new SemVer(m[2], this.options.loose)
+    }
   }
-}
 
-module.exports = class Minipass extends Stream {
-  constructor (options) {
-    super()
-    this[FLOWING] = false
-    // whether we're explicitly paused
-    this[PAUSED] = false
-    this.pipes = []
-    this.buffer = []
-    this[OBJECTMODE] = options && options.objectMode || false
-    if (this[OBJECTMODE])
-      this[ENCODING] = null
-    else
-      this[ENCODING] = options && options.encoding || null
-    if (this[ENCODING] === 'buffer')
-      this[ENCODING] = null
-    this[ASYNC] = options && !!options.async || false
-    this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
-    this[EOF] = false
-    this[EMITTED_END] = false
-    this[EMITTING_END] = false
-    this[CLOSED] = false
-    this[EMITTED_ERROR] = null
-    this.writable = true
-    this.readable = true
-    this[BUFFERLENGTH] = 0
-    this[DESTROYED] = false
+  toString () {
+    return this.value
   }
 
-  get bufferLength () { return this[BUFFERLENGTH] }
-
-  get encoding () { return this[ENCODING] }
-  set encoding (enc) {
-    if (this[OBJECTMODE])
-      throw new Error('cannot set encoding in objectMode')
+  test (version) {
+    debug('Comparator.test', version, this.options.loose)
 
-    if (this[ENCODING] && enc !== this[ENCODING] &&
-        (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
-      throw new Error('cannot change encoding')
+    if (this.semver === ANY || version === ANY) {
+      return true
+    }
 
-    if (this[ENCODING] !== enc) {
-      this[DECODER] = enc ? new SD(enc) : null
-      if (this.buffer.length)
-        this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
+    if (typeof version === 'string') {
+      try {
+        version = new SemVer(version, this.options)
+      } catch (er) {
+        return false
+      }
     }
 
-    this[ENCODING] = enc
+    return cmp(version, this.operator, this.semver, this.options)
   }
 
-  setEncoding (enc) {
-    this.encoding = enc
-  }
+  intersects (comp, options) {
+    if (!(comp instanceof Comparator)) {
+      throw new TypeError('a Comparator is required')
+    }
 
-  get objectMode () { return this[OBJECTMODE] }
-  set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
+    if (this.operator === '') {
+      if (this.value === '') {
+        return true
+      }
+      return new Range(comp.value, options).test(this.value)
+    } else if (comp.operator === '') {
+      if (comp.value === '') {
+        return true
+      }
+      return new Range(this.value, options).test(comp.semver)
+    }
 
-  get ['async'] () { return this[ASYNC] }
-  set ['async'] (a) { this[ASYNC] = this[ASYNC] || !!a }
+    options = parseOptions(options)
 
-  write (chunk, encoding, cb) {
-    if (this[EOF])
-      throw new Error('write after end')
+    // Special cases where nothing can possibly be lower
+    if (options.includePrerelease &&
+      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
+      return false
+    }
+    if (!options.includePrerelease &&
+      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
+      return false
+    }
 
-    if (this[DESTROYED]) {
-      this.emit('error', Object.assign(
-        new Error('Cannot call write after a stream was destroyed'),
-        { code: 'ERR_STREAM_DESTROYED' }
-      ))
+    // Same direction increasing (> or >=)
+    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
       return true
     }
+    // Same direction decreasing (< or <=)
+    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
+      return true
+    }
+    // same SemVer and both sides are inclusive (<= or >=)
+    if (
+      (this.semver.version === comp.semver.version) &&
+      this.operator.includes('=') && comp.operator.includes('=')) {
+      return true
+    }
+    // opposite directions less than
+    if (cmp(this.semver, '<', comp.semver, options) &&
+      this.operator.startsWith('>') && comp.operator.startsWith('<')) {
+      return true
+    }
+    // opposite directions greater than
+    if (cmp(this.semver, '>', comp.semver, options) &&
+      this.operator.startsWith('<') && comp.operator.startsWith('>')) {
+      return true
+    }
+    return false
+  }
+}
 
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
-
-    if (!encoding)
-      encoding = 'utf8'
-
-    const fn = this[ASYNC] ? defer : f => f()
+module.exports = Comparator
 
-    // convert array buffers and typed array views into buffers
-    // at some point in the future, we may want to do the opposite!
-    // leave strings and buffers as-is
-    // anything else switches us into object mode
-    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
-      if (isArrayBufferView(chunk))
-        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
-      else if (isArrayBuffer(chunk))
-        chunk = Buffer.from(chunk)
-      else if (typeof chunk !== 'string')
-        // use the setter so we throw if we have encoding set
-        this.objectMode = true
-    }
+const parseOptions = __nccwpck_require__(70356)
+const { safeRe: re, t } = __nccwpck_require__(95471)
+const cmp = __nccwpck_require__(28646)
+const debug = __nccwpck_require__(1159)
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(96782)
 
-    // handle object mode up front, since it's simpler
-    // this yields better performance, fewer checks later.
-    if (this[OBJECTMODE]) {
-      /* istanbul ignore if - maybe impossible? */
-      if (this.flowing && this[BUFFERLENGTH] !== 0)
-        this[FLUSH](true)
 
-      if (this.flowing)
-        this.emit('data', chunk)
-      else
-        this[BUFFERPUSH](chunk)
+/***/ }),
 
-      if (this[BUFFERLENGTH] !== 0)
-        this.emit('readable')
+/***/ 96782:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-      if (cb)
-        fn(cb)
+const SPACE_CHARACTERS = /\s+/g
 
-      return this.flowing
-    }
+// hoisted class for cyclic dependency
+class Range {
+  constructor (range, options) {
+    options = parseOptions(options)
 
-    // at this point the chunk is a buffer or string
-    // don't buffer it up or send it to the decoder
-    if (!chunk.length) {
-      if (this[BUFFERLENGTH] !== 0)
-        this.emit('readable')
-      if (cb)
-        fn(cb)
-      return this.flowing
+    if (range instanceof Range) {
+      if (
+        range.loose === !!options.loose &&
+        range.includePrerelease === !!options.includePrerelease
+      ) {
+        return range
+      } else {
+        return new Range(range.raw, options)
+      }
     }
 
-    // fast-path writing strings of same encoding to a stream with
-    // an empty buffer, skipping the buffer/decoder dance
-    if (typeof chunk === 'string' &&
-        // unless it is a string already ready for us to use
-        !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
-      chunk = Buffer.from(chunk, encoding)
+    if (range instanceof Comparator) {
+      // just put it in the set and return
+      this.raw = range.value
+      this.set = [[range]]
+      this.formatted = undefined
+      return this
     }
 
-    if (Buffer.isBuffer(chunk) && this[ENCODING])
-      chunk = this[DECODER].write(chunk)
+    this.options = options
+    this.loose = !!options.loose
+    this.includePrerelease = !!options.includePrerelease
 
-    // Note: flushing CAN potentially switch us into not-flowing mode
-    if (this.flowing && this[BUFFERLENGTH] !== 0)
-      this[FLUSH](true)
+    // First reduce all whitespace as much as possible so we do not have to rely
+    // on potentially slow regexes like \s*. This is then stored and used for
+    // future error messages as well.
+    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')
 
-    if (this.flowing)
-      this.emit('data', chunk)
-    else
-      this[BUFFERPUSH](chunk)
+    // First, split on ||
+    this.set = this.raw
+      .split('||')
+      // map the range to a 2d array of comparators
+      .map(r => this.parseRange(r.trim()))
+      // throw out any comparator lists that are empty
+      // this generally means that it was not a valid range, which is allowed
+      // in loose mode, but will still throw if the WHOLE range is invalid.
+      .filter(c => c.length)
 
-    if (this[BUFFERLENGTH] !== 0)
-      this.emit('readable')
+    if (!this.set.length) {
+      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
+    }
 
-    if (cb)
-      fn(cb)
+    // if we have any that are not the null set, throw out null sets.
+    if (this.set.length > 1) {
+      // keep the first one, in case they're all null sets
+      const first = this.set[0]
+      this.set = this.set.filter(c => !isNullSet(c[0]))
+      if (this.set.length === 0) {
+        this.set = [first]
+      } else if (this.set.length > 1) {
+        // if we have any that are *, then the range is just *
+        for (const c of this.set) {
+          if (c.length === 1 && isAny(c[0])) {
+            this.set = [c]
+            break
+          }
+        }
+      }
+    }
 
-    return this.flowing
+    this.formatted = undefined
   }
 
-  read (n) {
-    if (this[DESTROYED])
-      return null
-
-    if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH]) {
-      this[MAYBE_EMIT_END]()
-      return null
+  get range () {
+    if (this.formatted === undefined) {
+      this.formatted = ''
+      for (let i = 0; i < this.set.length; i++) {
+        if (i > 0) {
+          this.formatted += '||'
+        }
+        const comps = this.set[i]
+        for (let k = 0; k < comps.length; k++) {
+          if (k > 0) {
+            this.formatted += ' '
+          }
+          this.formatted += comps[k].toString().trim()
+        }
+      }
     }
+    return this.formatted
+  }
 
-    if (this[OBJECTMODE])
-      n = null
-
-    if (this.buffer.length > 1 && !this[OBJECTMODE]) {
-      if (this.encoding)
-        this.buffer = [this.buffer.join('')]
-      else
-        this.buffer = [Buffer.concat(this.buffer, this[BUFFERLENGTH])]
-    }
+  format () {
+    return this.range
+  }
 
-    const ret = this[READ](n || null, this.buffer[0])
-    this[MAYBE_EMIT_END]()
-    return ret
+  toString () {
+    return this.range
   }
 
-  [READ] (n, chunk) {
-    if (n === chunk.length || n === null)
-      this[BUFFERSHIFT]()
-    else {
-      this.buffer[0] = chunk.slice(n)
-      chunk = chunk.slice(0, n)
-      this[BUFFERLENGTH] -= n
+  parseRange (range) {
+    // memoize range parsing for performance.
+    // this is a very hot path, and fully deterministic.
+    const memoOpts =
+      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
+      (this.options.loose && FLAG_LOOSE)
+    const memoKey = memoOpts + ':' + range
+    const cached = cache.get(memoKey)
+    if (cached) {
+      return cached
     }
 
-    this.emit('data', chunk)
+    const loose = this.options.loose
+    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
+    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
+    range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
+    debug('hyphen replace', range)
 
-    if (!this.buffer.length && !this[EOF])
-      this.emit('drain')
+    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
+    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
+    debug('comparator trim', range)
 
-    return chunk
-  }
+    // `~ 1.2.3` => `~1.2.3`
+    range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
+    debug('tilde trim', range)
 
-  end (chunk, encoding, cb) {
-    if (typeof chunk === 'function')
-      cb = chunk, chunk = null
-    if (typeof encoding === 'function')
-      cb = encoding, encoding = 'utf8'
-    if (chunk)
-      this.write(chunk, encoding)
-    if (cb)
-      this.once('end', cb)
-    this[EOF] = true
-    this.writable = false
+    // `^ 1.2.3` => `^1.2.3`
+    range = range.replace(re[t.CARETTRIM], caretTrimReplace)
+    debug('caret trim', range)
 
-    // if we haven't written anything, then go ahead and emit,
-    // even if we're not reading.
-    // we'll re-emit if a new 'end' listener is added anyway.
-    // This makes MP more suitable to write-only use cases.
-    if (this.flowing || !this[PAUSED])
-      this[MAYBE_EMIT_END]()
-    return this
-  }
+    // At this point, the range is completely trimmed and
+    // ready to be split into comparators.
 
-  // don't let the internal resume be overwritten
-  [RESUME] () {
-    if (this[DESTROYED])
-      return
+    let rangeList = range
+      .split(' ')
+      .map(comp => parseComparator(comp, this.options))
+      .join(' ')
+      .split(/\s+/)
+      // >=0.0.0 is equivalent to *
+      .map(comp => replaceGTE0(comp, this.options))
 
-    this[PAUSED] = false
-    this[FLOWING] = true
-    this.emit('resume')
-    if (this.buffer.length)
-      this[FLUSH]()
-    else if (this[EOF])
-      this[MAYBE_EMIT_END]()
-    else
-      this.emit('drain')
-  }
+    if (loose) {
+      // in loose mode, throw out any that are not valid comparators
+      rangeList = rangeList.filter(comp => {
+        debug('loose invalid filter', comp, this.options)
+        return !!comp.match(re[t.COMPARATORLOOSE])
+      })
+    }
+    debug('range list', rangeList)
 
-  resume () {
-    return this[RESUME]()
-  }
+    // if any comparators are the null set, then replace with JUST null set
+    // if more than one comparator, remove any * comparators
+    // also, don't include the same comparator more than once
+    const rangeMap = new Map()
+    const comparators = rangeList.map(comp => new Comparator(comp, this.options))
+    for (const comp of comparators) {
+      if (isNullSet(comp)) {
+        return [comp]
+      }
+      rangeMap.set(comp.value, comp)
+    }
+    if (rangeMap.size > 1 && rangeMap.has('')) {
+      rangeMap.delete('')
+    }
 
-  pause () {
-    this[FLOWING] = false
-    this[PAUSED] = true
+    const result = [...rangeMap.values()]
+    cache.set(memoKey, result)
+    return result
   }
 
-  get destroyed () {
-    return this[DESTROYED]
-  }
+  intersects (range, options) {
+    if (!(range instanceof Range)) {
+      throw new TypeError('a Range is required')
+    }
 
-  get flowing () {
-    return this[FLOWING]
+    return this.set.some((thisComparators) => {
+      return (
+        isSatisfiable(thisComparators, options) &&
+        range.set.some((rangeComparators) => {
+          return (
+            isSatisfiable(rangeComparators, options) &&
+            thisComparators.every((thisComparator) => {
+              return rangeComparators.every((rangeComparator) => {
+                return thisComparator.intersects(rangeComparator, options)
+              })
+            })
+          )
+        })
+      )
+    })
   }
 
-  get paused () {
-    return this[PAUSED]
-  }
+  // if ANY of the sets match ALL of its comparators, then pass
+  test (version) {
+    if (!version) {
+      return false
+    }
 
-  [BUFFERPUSH] (chunk) {
-    if (this[OBJECTMODE])
-      this[BUFFERLENGTH] += 1
-    else
-      this[BUFFERLENGTH] += chunk.length
-    this.buffer.push(chunk)
-  }
+    if (typeof version === 'string') {
+      try {
+        version = new SemVer(version, this.options)
+      } catch (er) {
+        return false
+      }
+    }
 
-  [BUFFERSHIFT] () {
-    if (this.buffer.length) {
-      if (this[OBJECTMODE])
-        this[BUFFERLENGTH] -= 1
-      else
-        this[BUFFERLENGTH] -= this.buffer[0].length
+    for (let i = 0; i < this.set.length; i++) {
+      if (testSet(this.set[i], version, this.options)) {
+        return true
+      }
     }
-    return this.buffer.shift()
+    return false
   }
+}
 
-  [FLUSH] (noDrain) {
-    do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
+module.exports = Range
 
-    if (!noDrain && !this.buffer.length && !this[EOF])
-      this.emit('drain')
-  }
+const LRU = __nccwpck_require__(61383)
+const cache = new LRU()
 
-  [FLUSHCHUNK] (chunk) {
-    return chunk ? (this.emit('data', chunk), this.flowing) : false
-  }
+const parseOptions = __nccwpck_require__(70356)
+const Comparator = __nccwpck_require__(89379)
+const debug = __nccwpck_require__(1159)
+const SemVer = __nccwpck_require__(7163)
+const {
+  safeRe: re,
+  t,
+  comparatorTrimReplace,
+  tildeTrimReplace,
+  caretTrimReplace,
+} = __nccwpck_require__(95471)
+const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(45101)
 
-  pipe (dest, opts) {
-    if (this[DESTROYED])
-      return
+const isNullSet = c => c.value === '<0.0.0-0'
+const isAny = c => c.value === ''
 
-    const ended = this[EMITTED_END]
-    opts = opts || {}
-    if (dest === proc.stdout || dest === proc.stderr)
-      opts.end = false
-    else
-      opts.end = opts.end !== false
-    opts.proxyErrors = !!opts.proxyErrors
+// take a set of comparators and determine whether there
+// exists a version which can satisfy it
+const isSatisfiable = (comparators, options) => {
+  let result = true
+  const remainingComparators = comparators.slice()
+  let testComparator = remainingComparators.pop()
 
-    // piping an ended stream ends immediately
-    if (ended) {
-      if (opts.end)
-        dest.end()
-    } else {
-      this.pipes.push(!opts.proxyErrors ? new Pipe(this, dest, opts)
-        : new PipeProxyErrors(this, dest, opts))
-      if (this[ASYNC])
-        defer(() => this[RESUME]())
-      else
-        this[RESUME]()
-    }
+  while (result && remainingComparators.length) {
+    result = remainingComparators.every((otherComparator) => {
+      return testComparator.intersects(otherComparator, options)
+    })
 
-    return dest
+    testComparator = remainingComparators.pop()
   }
 
-  unpipe (dest) {
-    const p = this.pipes.find(p => p.dest === dest)
-    if (p) {
-      this.pipes.splice(this.pipes.indexOf(p), 1)
-      p.unpipe()
-    }
-  }
+  return result
+}
 
-  addListener (ev, fn) {
-    return this.on(ev, fn)
-  }
+// comprised of xranges, tildes, stars, and gtlt's at this point.
+// already replaced the hyphen ranges
+// turn into a set of JUST comparators.
+const parseComparator = (comp, options) => {
+  debug('comp', comp, options)
+  comp = replaceCarets(comp, options)
+  debug('caret', comp)
+  comp = replaceTildes(comp, options)
+  debug('tildes', comp)
+  comp = replaceXRanges(comp, options)
+  debug('xrange', comp)
+  comp = replaceStars(comp, options)
+  debug('stars', comp)
+  return comp
+}
 
-  on (ev, fn) {
-    const ret = super.on(ev, fn)
-    if (ev === 'data' && !this.pipes.length && !this.flowing)
-      this[RESUME]()
-    else if (ev === 'readable' && this[BUFFERLENGTH] !== 0)
-      super.emit('readable')
-    else if (isEndish(ev) && this[EMITTED_END]) {
-      super.emit(ev)
-      this.removeAllListeners(ev)
-    } else if (ev === 'error' && this[EMITTED_ERROR]) {
-      if (this[ASYNC])
-        defer(() => fn.call(this, this[EMITTED_ERROR]))
-      else
-        fn.call(this, this[EMITTED_ERROR])
+const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
+
+// ~, ~> --> * (any, kinda silly)
+// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
+// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
+// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
+// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
+// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
+// ~0.0.1 --> >=0.0.1 <0.1.0-0
+const replaceTildes = (comp, options) => {
+  return comp
+    .trim()
+    .split(/\s+/)
+    .map((c) => replaceTilde(c, options))
+    .join(' ')
+}
+
+const replaceTilde = (comp, options) => {
+  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
+  return comp.replace(r, (_, M, m, p, pr) => {
+    debug('tilde', comp, _, M, m, p, pr)
+    let ret
+
+    if (isX(M)) {
+      ret = ''
+    } else if (isX(m)) {
+      ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
+    } else if (isX(p)) {
+      // ~1.2 == >=1.2.0 <1.3.0-0
+      ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
+    } else if (pr) {
+      debug('replaceTilde pr', pr)
+      ret = `>=${M}.${m}.${p}-${pr
+      } <${M}.${+m + 1}.0-0`
+    } else {
+      // ~1.2.3 == >=1.2.3 <1.3.0-0
+      ret = `>=${M}.${m}.${p
+      } <${M}.${+m + 1}.0-0`
     }
+
+    debug('tilde return', ret)
     return ret
-  }
+  })
+}
 
-  get emittedEnd () {
-    return this[EMITTED_END]
-  }
+// ^ --> * (any, kinda silly)
+// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
+// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
+// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
+// ^1.2.3 --> >=1.2.3 <2.0.0-0
+// ^1.2.0 --> >=1.2.0 <2.0.0-0
+// ^0.0.1 --> >=0.0.1 <0.0.2-0
+// ^0.1.0 --> >=0.1.0 <0.2.0-0
+const replaceCarets = (comp, options) => {
+  return comp
+    .trim()
+    .split(/\s+/)
+    .map((c) => replaceCaret(c, options))
+    .join(' ')
+}
 
-  [MAYBE_EMIT_END] () {
-    if (!this[EMITTING_END] &&
-        !this[EMITTED_END] &&
-        !this[DESTROYED] &&
-        this.buffer.length === 0 &&
-        this[EOF]) {
-      this[EMITTING_END] = true
-      this.emit('end')
-      this.emit('prefinish')
-      this.emit('finish')
-      if (this[CLOSED])
-        this.emit('close')
-      this[EMITTING_END] = false
-    }
-  }
+const replaceCaret = (comp, options) => {
+  debug('caret', comp, options)
+  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
+  const z = options.includePrerelease ? '-0' : ''
+  return comp.replace(r, (_, M, m, p, pr) => {
+    debug('caret', comp, _, M, m, p, pr)
+    let ret
 
-  emit (ev, data, ...extra) {
-    // error and close are only events allowed after calling destroy()
-    if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
-      return
-    else if (ev === 'data') {
-      return !data ? false
-        : this[ASYNC] ? defer(() => this[EMITDATA](data))
-        : this[EMITDATA](data)
-    } else if (ev === 'end') {
-      return this[EMITEND]()
-    } else if (ev === 'close') {
-      this[CLOSED] = true
-      // don't emit close before 'end' and 'finish'
-      if (!this[EMITTED_END] && !this[DESTROYED])
-        return
-      const ret = super.emit('close')
-      this.removeAllListeners('close')
-      return ret
-    } else if (ev === 'error') {
-      this[EMITTED_ERROR] = data
-      const ret = super.emit('error', data)
-      this[MAYBE_EMIT_END]()
-      return ret
-    } else if (ev === 'resume') {
-      const ret = super.emit('resume')
-      this[MAYBE_EMIT_END]()
-      return ret
-    } else if (ev === 'finish' || ev === 'prefinish') {
-      const ret = super.emit(ev)
-      this.removeAllListeners(ev)
-      return ret
+    if (isX(M)) {
+      ret = ''
+    } else if (isX(m)) {
+      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
+    } else if (isX(p)) {
+      if (M === '0') {
+        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
+      } else {
+        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
+      }
+    } else if (pr) {
+      debug('replaceCaret pr', pr)
+      if (M === '0') {
+        if (m === '0') {
+          ret = `>=${M}.${m}.${p}-${pr
+          } <${M}.${m}.${+p + 1}-0`
+        } else {
+          ret = `>=${M}.${m}.${p}-${pr
+          } <${M}.${+m + 1}.0-0`
+        }
+      } else {
+        ret = `>=${M}.${m}.${p}-${pr
+        } <${+M + 1}.0.0-0`
+      }
+    } else {
+      debug('no pr')
+      if (M === '0') {
+        if (m === '0') {
+          ret = `>=${M}.${m}.${p
+          }${z} <${M}.${m}.${+p + 1}-0`
+        } else {
+          ret = `>=${M}.${m}.${p
+          }${z} <${M}.${+m + 1}.0-0`
+        }
+      } else {
+        ret = `>=${M}.${m}.${p
+        } <${+M + 1}.0.0-0`
+      }
     }
 
-    // Some other unknown event
-    const ret = super.emit(ev, data, ...extra)
-    this[MAYBE_EMIT_END]()
+    debug('caret return', ret)
     return ret
-  }
+  })
+}
 
-  [EMITDATA] (data) {
-    for (const p of this.pipes) {
-      if (p.dest.write(data) === false)
-        this.pause()
+const replaceXRanges = (comp, options) => {
+  debug('replaceXRanges', comp, options)
+  return comp
+    .split(/\s+/)
+    .map((c) => replaceXRange(c, options))
+    .join(' ')
+}
+
+const replaceXRange = (comp, options) => {
+  comp = comp.trim()
+  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
+  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
+    debug('xRange', comp, ret, gtlt, M, m, p, pr)
+    const xM = isX(M)
+    const xm = xM || isX(m)
+    const xp = xm || isX(p)
+    const anyX = xp
+
+    if (gtlt === '=' && anyX) {
+      gtlt = ''
     }
-    const ret = super.emit('data', data)
-    this[MAYBE_EMIT_END]()
-    return ret
-  }
 
-  [EMITEND] () {
-    if (this[EMITTED_END])
-      return
+    // if we're including prereleases in the match, then we need
+    // to fix this to -0, the lowest possible prerelease value
+    pr = options.includePrerelease ? '-0' : ''
 
-    this[EMITTED_END] = true
-    this.readable = false
-    if (this[ASYNC])
-      defer(() => this[EMITEND2]())
-    else
-      this[EMITEND2]()
-  }
+    if (xM) {
+      if (gtlt === '>' || gtlt === '<') {
+        // nothing is allowed
+        ret = '<0.0.0-0'
+      } else {
+        // nothing is forbidden
+        ret = '*'
+      }
+    } else if (gtlt && anyX) {
+      // we know patch is an x, because we have any x at all.
+      // replace X with 0
+      if (xm) {
+        m = 0
+      }
+      p = 0
 
-  [EMITEND2] () {
-    if (this[DECODER]) {
-      const data = this[DECODER].end()
-      if (data) {
-        for (const p of this.pipes) {
-          p.dest.write(data)
+      if (gtlt === '>') {
+        // >1 => >=2.0.0
+        // >1.2 => >=1.3.0
+        gtlt = '>='
+        if (xm) {
+          M = +M + 1
+          m = 0
+          p = 0
+        } else {
+          m = +m + 1
+          p = 0
+        }
+      } else if (gtlt === '<=') {
+        // <=0.7.x is actually <0.8.0, since any 0.7.x should
+        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
+        gtlt = '<'
+        if (xm) {
+          M = +M + 1
+        } else {
+          m = +m + 1
         }
-        super.emit('data', data)
       }
-    }
 
-    for (const p of this.pipes) {
-      p.end()
+      if (gtlt === '<') {
+        pr = '-0'
+      }
+
+      ret = `${gtlt + M}.${m}.${p}${pr}`
+    } else if (xm) {
+      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
+    } else if (xp) {
+      ret = `>=${M}.${m}.0${pr
+      } <${M}.${+m + 1}.0-0`
     }
-    const ret = super.emit('end')
-    this.removeAllListeners('end')
+
+    debug('xRange return', ret)
+
     return ret
+  })
+}
+
+// Because * is AND-ed with everything else in the comparator,
+// and '' means "any version", just remove the *s entirely.
+const replaceStars = (comp, options) => {
+  debug('replaceStars', comp, options)
+  // Looseness is ignored here.  star is always as loose as it gets!
+  return comp
+    .trim()
+    .replace(re[t.STAR], '')
+}
+
+const replaceGTE0 = (comp, options) => {
+  debug('replaceGTE0', comp, options)
+  return comp
+    .trim()
+    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
+}
+
+// This function is passed to string.replace(re[t.HYPHENRANGE])
+// M, m, patch, prerelease, build
+// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
+// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
+// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
+// TODO build?
+const hyphenReplace = incPr => ($0,
+  from, fM, fm, fp, fpr, fb,
+  to, tM, tm, tp, tpr) => {
+  if (isX(fM)) {
+    from = ''
+  } else if (isX(fm)) {
+    from = `>=${fM}.0.0${incPr ? '-0' : ''}`
+  } else if (isX(fp)) {
+    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
+  } else if (fpr) {
+    from = `>=${from}`
+  } else {
+    from = `>=${from}${incPr ? '-0' : ''}`
   }
 
-  // const all = await stream.collect()
-  collect () {
-    const buf = []
-    if (!this[OBJECTMODE])
-      buf.dataLength = 0
-    // set the promise first, in case an error is raised
-    // by triggering the flow here.
-    const p = this.promise()
-    this.on('data', c => {
-      buf.push(c)
-      if (!this[OBJECTMODE])
-        buf.dataLength += c.length
-    })
-    return p.then(() => buf)
+  if (isX(tM)) {
+    to = ''
+  } else if (isX(tm)) {
+    to = `<${+tM + 1}.0.0-0`
+  } else if (isX(tp)) {
+    to = `<${tM}.${+tm + 1}.0-0`
+  } else if (tpr) {
+    to = `<=${tM}.${tm}.${tp}-${tpr}`
+  } else if (incPr) {
+    to = `<${tM}.${tm}.${+tp + 1}-0`
+  } else {
+    to = `<=${to}`
+  }
+
+  return `${from} ${to}`.trim()
+}
+
+const testSet = (set, version, options) => {
+  for (let i = 0; i < set.length; i++) {
+    if (!set[i].test(version)) {
+      return false
+    }
   }
 
-  // const data = await stream.concat()
-  concat () {
-    return this[OBJECTMODE]
-      ? Promise.reject(new Error('cannot concat in objectMode'))
-      : this.collect().then(buf =>
-          this[OBJECTMODE]
-            ? Promise.reject(new Error('cannot concat in objectMode'))
-            : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
+  if (version.prerelease.length && !options.includePrerelease) {
+    // Find the set of versions that are allowed to have prereleases
+    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
+    // That should allow `1.2.3-pr.2` to pass.
+    // However, `1.2.4-alpha.notready` should NOT be allowed,
+    // even though it's within the range set by the comparators.
+    for (let i = 0; i < set.length; i++) {
+      debug(set[i].semver)
+      if (set[i].semver === Comparator.ANY) {
+        continue
+      }
+
+      if (set[i].semver.prerelease.length > 0) {
+        const allowed = set[i].semver
+        if (allowed.major === version.major &&
+            allowed.minor === version.minor &&
+            allowed.patch === version.patch) {
+          return true
+        }
+      }
+    }
+
+    // Version has a -pre, but it's not one of the ones we like.
+    return false
   }
 
-  // stream.promise().then(() => done, er => emitted error)
-  promise () {
-    return new Promise((resolve, reject) => {
-      this.on(DESTROYED, () => reject(new Error('stream destroyed')))
-      this.on('error', er => reject(er))
-      this.on('end', () => resolve())
-    })
-  }
+  return true
+}
 
-  // for await (let chunk of stream)
-  [ASYNCITERATOR] () {
-    const next = () => {
-      const res = this.read()
-      if (res !== null)
-        return Promise.resolve({ done: false, value: res })
 
-      if (this[EOF])
-        return Promise.resolve({ done: true })
+/***/ }),
 
-      let resolve = null
-      let reject = null
-      const onerr = er => {
-        this.removeListener('data', ondata)
-        this.removeListener('end', onend)
-        reject(er)
-      }
-      const ondata = value => {
-        this.removeListener('error', onerr)
-        this.removeListener('end', onend)
-        this.pause()
-        resolve({ value: value, done: !!this[EOF] })
-      }
-      const onend = () => {
-        this.removeListener('error', onerr)
-        this.removeListener('data', ondata)
-        resolve({ done: true })
+/***/ 7163:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const debug = __nccwpck_require__(1159)
+const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(45101)
+const { safeRe: re, safeSrc: src, t } = __nccwpck_require__(95471)
+
+const parseOptions = __nccwpck_require__(70356)
+const { compareIdentifiers } = __nccwpck_require__(73348)
+class SemVer {
+  constructor (version, options) {
+    options = parseOptions(options)
+
+    if (version instanceof SemVer) {
+      if (version.loose === !!options.loose &&
+        version.includePrerelease === !!options.includePrerelease) {
+        return version
+      } else {
+        version = version.version
       }
-      const ondestroy = () => onerr(new Error('stream destroyed'))
-      return new Promise((res, rej) => {
-        reject = rej
-        resolve = res
-        this.once(DESTROYED, ondestroy)
-        this.once('error', onerr)
-        this.once('end', onend)
-        this.once('data', ondata)
-      })
+    } else if (typeof version !== 'string') {
+      throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
     }
 
-    return { next }
-  }
+    if (version.length > MAX_LENGTH) {
+      throw new TypeError(
+        `version is longer than ${MAX_LENGTH} characters`
+      )
+    }
 
-  // for (let chunk of stream)
-  [ITERATOR] () {
-    const next = () => {
-      const value = this.read()
-      const done = value === null
-      return { value, done }
+    debug('SemVer', version, options)
+    this.options = options
+    this.loose = !!options.loose
+    // this isn't actually relevant for versions, but keep it so that we
+    // don't run into trouble passing this.options around.
+    this.includePrerelease = !!options.includePrerelease
+
+    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
+
+    if (!m) {
+      throw new TypeError(`Invalid Version: ${version}`)
     }
-    return { next }
-  }
 
-  destroy (er) {
-    if (this[DESTROYED]) {
-      if (er)
-        this.emit('error', er)
-      else
-        this.emit(DESTROYED)
-      return this
+    this.raw = version
+
+    // these are actually numbers
+    this.major = +m[1]
+    this.minor = +m[2]
+    this.patch = +m[3]
+
+    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+      throw new TypeError('Invalid major version')
     }
 
-    this[DESTROYED] = true
+    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+      throw new TypeError('Invalid minor version')
+    }
 
-    // throw away all buffered data, it's never coming out
-    this.buffer.length = 0
-    this[BUFFERLENGTH] = 0
+    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
+      throw new TypeError('Invalid patch version')
+    }
 
-    if (typeof this.close === 'function' && !this[CLOSED])
-      this.close()
+    // numberify any prerelease numeric ids
+    if (!m[4]) {
+      this.prerelease = []
+    } else {
+      this.prerelease = m[4].split('.').map((id) => {
+        if (/^[0-9]+$/.test(id)) {
+          const num = +id
+          if (num >= 0 && num < MAX_SAFE_INTEGER) {
+            return num
+          }
+        }
+        return id
+      })
+    }
 
-    if (er)
-      this.emit('error', er)
-    else // if no error to emit, still reject pending promises
-      this.emit(DESTROYED)
+    this.build = m[5] ? m[5].split('.') : []
+    this.format()
+  }
 
-    return this
+  format () {
+    this.version = `${this.major}.${this.minor}.${this.patch}`
+    if (this.prerelease.length) {
+      this.version += `-${this.prerelease.join('.')}`
+    }
+    return this.version
   }
 
-  static isStream (s) {
-    return !!s && (s instanceof Minipass || s instanceof Stream ||
-      s instanceof EE && (
-        typeof s.pipe === 'function' || // readable
-        (typeof s.write === 'function' && typeof s.end === 'function') // writable
-      ))
+  toString () {
+    return this.version
   }
-}
 
+  compare (other) {
+    debug('SemVer.compare', this.version, this.options, other)
+    if (!(other instanceof SemVer)) {
+      if (typeof other === 'string' && other === this.version) {
+        return 0
+      }
+      other = new SemVer(other, this.options)
+    }
 
-/***/ }),
+    if (other.version === this.version) {
+      return 0
+    }
 
-/***/ 70744:
-/***/ ((module) => {
+    return this.compareMain(other) || this.comparePre(other)
+  }
 
-/**
- * Helpers.
- */
+  compareMain (other) {
+    if (!(other instanceof SemVer)) {
+      other = new SemVer(other, this.options)
+    }
 
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var w = d * 7;
-var y = d * 365.25;
+    return (
+      compareIdentifiers(this.major, other.major) ||
+      compareIdentifiers(this.minor, other.minor) ||
+      compareIdentifiers(this.patch, other.patch)
+    )
+  }
 
-/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- *  - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
- */
+  comparePre (other) {
+    if (!(other instanceof SemVer)) {
+      other = new SemVer(other, this.options)
+    }
 
-module.exports = function(val, options) {
-  options = options || {};
-  var type = typeof val;
-  if (type === 'string' && val.length > 0) {
-    return parse(val);
-  } else if (type === 'number' && isFinite(val)) {
-    return options.long ? fmtLong(val) : fmtShort(val);
+    // NOT having a prerelease is > having one
+    if (this.prerelease.length && !other.prerelease.length) {
+      return -1
+    } else if (!this.prerelease.length && other.prerelease.length) {
+      return 1
+    } else if (!this.prerelease.length && !other.prerelease.length) {
+      return 0
+    }
+
+    let i = 0
+    do {
+      const a = this.prerelease[i]
+      const b = other.prerelease[i]
+      debug('prerelease compare', i, a, b)
+      if (a === undefined && b === undefined) {
+        return 0
+      } else if (b === undefined) {
+        return 1
+      } else if (a === undefined) {
+        return -1
+      } else if (a === b) {
+        continue
+      } else {
+        return compareIdentifiers(a, b)
+      }
+    } while (++i)
   }
-  throw new Error(
-    'val is not a non-empty string or a valid number. val=' +
-      JSON.stringify(val)
-  );
-};
 
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
+  compareBuild (other) {
+    if (!(other instanceof SemVer)) {
+      other = new SemVer(other, this.options)
+    }
 
-function parse(str) {
-  str = String(str);
-  if (str.length > 100) {
-    return;
-  }
-  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
-    str
-  );
-  if (!match) {
-    return;
-  }
-  var n = parseFloat(match[1]);
-  var type = (match[2] || 'ms').toLowerCase();
-  switch (type) {
-    case 'years':
-    case 'year':
-    case 'yrs':
-    case 'yr':
-    case 'y':
-      return n * y;
-    case 'weeks':
-    case 'week':
-    case 'w':
-      return n * w;
-    case 'days':
-    case 'day':
-    case 'd':
-      return n * d;
-    case 'hours':
-    case 'hour':
-    case 'hrs':
-    case 'hr':
-    case 'h':
-      return n * h;
-    case 'minutes':
-    case 'minute':
-    case 'mins':
-    case 'min':
-    case 'm':
-      return n * m;
-    case 'seconds':
-    case 'second':
-    case 'secs':
-    case 'sec':
-    case 's':
-      return n * s;
-    case 'milliseconds':
-    case 'millisecond':
-    case 'msecs':
-    case 'msec':
-    case 'ms':
-      return n;
-    default:
-      return undefined;
+    let i = 0
+    do {
+      const a = this.build[i]
+      const b = other.build[i]
+      debug('build compare', i, a, b)
+      if (a === undefined && b === undefined) {
+        return 0
+      } else if (b === undefined) {
+        return 1
+      } else if (a === undefined) {
+        return -1
+      } else if (a === b) {
+        continue
+      } else {
+        return compareIdentifiers(a, b)
+      }
+    } while (++i)
   }
-}
 
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
+  // preminor will bump the version up to the next minor release, and immediately
+  // down to pre-release. premajor and prepatch work the same way.
+  inc (release, identifier, identifierBase) {
+    if (release.startsWith('pre')) {
+      if (!identifier && identifierBase === false) {
+        throw new Error('invalid increment argument: identifier is empty')
+      }
+      // Avoid an invalid semver results
+      if (identifier) {
+        const r = new RegExp(`^${this.options.loose ? src[t.PRERELEASELOOSE] : src[t.PRERELEASE]}$`)
+        const match = `-${identifier}`.match(r)
+        if (!match || match[1] !== identifier) {
+          throw new Error(`invalid identifier: ${identifier}`)
+        }
+      }
+    }
 
-function fmtShort(ms) {
-  var msAbs = Math.abs(ms);
-  if (msAbs >= d) {
-    return Math.round(ms / d) + 'd';
-  }
-  if (msAbs >= h) {
-    return Math.round(ms / h) + 'h';
-  }
-  if (msAbs >= m) {
-    return Math.round(ms / m) + 'm';
-  }
-  if (msAbs >= s) {
-    return Math.round(ms / s) + 's';
-  }
-  return ms + 'ms';
-}
+    switch (release) {
+      case 'premajor':
+        this.prerelease.length = 0
+        this.patch = 0
+        this.minor = 0
+        this.major++
+        this.inc('pre', identifier, identifierBase)
+        break
+      case 'preminor':
+        this.prerelease.length = 0
+        this.patch = 0
+        this.minor++
+        this.inc('pre', identifier, identifierBase)
+        break
+      case 'prepatch':
+        // If this is already a prerelease, it will bump to the next version
+        // drop any prereleases that might already exist, since they are not
+        // relevant at this point.
+        this.prerelease.length = 0
+        this.inc('patch', identifier, identifierBase)
+        this.inc('pre', identifier, identifierBase)
+        break
+      // If the input is a non-prerelease version, this acts the same as
+      // prepatch.
+      case 'prerelease':
+        if (this.prerelease.length === 0) {
+          this.inc('patch', identifier, identifierBase)
+        }
+        this.inc('pre', identifier, identifierBase)
+        break
+      case 'release':
+        if (this.prerelease.length === 0) {
+          throw new Error(`version ${this.raw} is not a prerelease`)
+        }
+        this.prerelease.length = 0
+        break
 
-/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
+      case 'major':
+        // If this is a pre-major version, bump up to the same major version.
+        // Otherwise increment major.
+        // 1.0.0-5 bumps to 1.0.0
+        // 1.1.0 bumps to 2.0.0
+        if (
+          this.minor !== 0 ||
+          this.patch !== 0 ||
+          this.prerelease.length === 0
+        ) {
+          this.major++
+        }
+        this.minor = 0
+        this.patch = 0
+        this.prerelease = []
+        break
+      case 'minor':
+        // If this is a pre-minor version, bump up to the same minor version.
+        // Otherwise increment minor.
+        // 1.2.0-5 bumps to 1.2.0
+        // 1.2.1 bumps to 1.3.0
+        if (this.patch !== 0 || this.prerelease.length === 0) {
+          this.minor++
+        }
+        this.patch = 0
+        this.prerelease = []
+        break
+      case 'patch':
+        // If this is not a pre-release version, it will increment the patch.
+        // If it is a pre-release it will bump up to the same patch version.
+        // 1.2.0-5 patches to 1.2.0
+        // 1.2.0 patches to 1.2.1
+        if (this.prerelease.length === 0) {
+          this.patch++
+        }
+        this.prerelease = []
+        break
+      // This probably shouldn't be used publicly.
+      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
+      case 'pre': {
+        const base = Number(identifierBase) ? 1 : 0
 
-function fmtLong(ms) {
-  var msAbs = Math.abs(ms);
-  if (msAbs >= d) {
-    return plural(ms, msAbs, d, 'day');
-  }
-  if (msAbs >= h) {
-    return plural(ms, msAbs, h, 'hour');
-  }
-  if (msAbs >= m) {
-    return plural(ms, msAbs, m, 'minute');
-  }
-  if (msAbs >= s) {
-    return plural(ms, msAbs, s, 'second');
+        if (this.prerelease.length === 0) {
+          this.prerelease = [base]
+        } else {
+          let i = this.prerelease.length
+          while (--i >= 0) {
+            if (typeof this.prerelease[i] === 'number') {
+              this.prerelease[i]++
+              i = -2
+            }
+          }
+          if (i === -1) {
+            // didn't increment anything
+            if (identifier === this.prerelease.join('.') && identifierBase === false) {
+              throw new Error('invalid increment argument: identifier already exists')
+            }
+            this.prerelease.push(base)
+          }
+        }
+        if (identifier) {
+          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
+          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
+          let prerelease = [identifier, base]
+          if (identifierBase === false) {
+            prerelease = [identifier]
+          }
+          if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
+            if (isNaN(this.prerelease[1])) {
+              this.prerelease = prerelease
+            }
+          } else {
+            this.prerelease = prerelease
+          }
+        }
+        break
+      }
+      default:
+        throw new Error(`invalid increment argument: ${release}`)
+    }
+    this.raw = this.format()
+    if (this.build.length) {
+      this.raw += `+${this.build.join('.')}`
+    }
+    return this
   }
-  return ms + ' ms';
 }
 
-/**
- * Pluralization helper.
- */
-
-function plural(ms, msAbs, n, name) {
-  var isPlural = msAbs >= n * 1.5;
-  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
-}
+module.exports = SemVer
 
 
 /***/ }),
 
-/***/ 60668:
+/***/ 1799:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
-/*!
- * negotiator
- * Copyright(c) 2012 Federico Romero
- * Copyright(c) 2012-2014 Isaac Z. Schlueter
- * Copyright(c) 2015 Douglas Christopher Wilson
- * MIT Licensed
- */
-
-
-
-var preferredCharsets = __nccwpck_require__(79168)
-var preferredEncodings = __nccwpck_require__(25111)
-var preferredLanguages = __nccwpck_require__(56008)
-var preferredMediaTypes = __nccwpck_require__(53672)
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = Negotiator;
-module.exports.Negotiator = Negotiator;
-
-/**
- * Create a Negotiator instance from a request.
- * @param {object} request
- * @public
- */
-
-function Negotiator(request) {
-  if (!(this instanceof Negotiator)) {
-    return new Negotiator(request);
-  }
-
-  this.request = request;
+const parse = __nccwpck_require__(16353)
+const clean = (version, options) => {
+  const s = parse(version.trim().replace(/^[=v]+/, ''), options)
+  return s ? s.version : null
 }
-
-Negotiator.prototype.charset = function charset(available) {
-  var set = this.charsets(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.charsets = function charsets(available) {
-  return preferredCharsets(this.request.headers['accept-charset'], available);
-};
-
-Negotiator.prototype.encoding = function encoding(available, opts) {
-  var set = this.encodings(available, opts);
-  return set && set[0];
-};
-
-Negotiator.prototype.encodings = function encodings(available, options) {
-  var opts = options || {};
-  return preferredEncodings(this.request.headers['accept-encoding'], available, opts.preferred);
-};
-
-Negotiator.prototype.language = function language(available) {
-  var set = this.languages(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.languages = function languages(available) {
-  return preferredLanguages(this.request.headers['accept-language'], available);
-};
-
-Negotiator.prototype.mediaType = function mediaType(available) {
-  var set = this.mediaTypes(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.mediaTypes = function mediaTypes(available) {
-  return preferredMediaTypes(this.request.headers.accept, available);
-};
-
-// Backwards compatibility
-Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
-Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
-Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
-Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
-Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
-Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
-Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
-Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
+module.exports = clean
 
 
 /***/ }),
 
-/***/ 79168:
-/***/ ((module) => {
-
-"use strict";
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
+/***/ 28646:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
+const eq = __nccwpck_require__(55082)
+const neq = __nccwpck_require__(4974)
+const gt = __nccwpck_require__(16599)
+const gte = __nccwpck_require__(41236)
+const lt = __nccwpck_require__(3872)
+const lte = __nccwpck_require__(56717)
 
+const cmp = (a, op, b, loose) => {
+  switch (op) {
+    case '===':
+      if (typeof a === 'object') {
+        a = a.version
+      }
+      if (typeof b === 'object') {
+        b = b.version
+      }
+      return a === b
 
-/**
- * Module exports.
- * @public
- */
+    case '!==':
+      if (typeof a === 'object') {
+        a = a.version
+      }
+      if (typeof b === 'object') {
+        b = b.version
+      }
+      return a !== b
 
-module.exports = preferredCharsets;
-module.exports.preferredCharsets = preferredCharsets;
+    case '':
+    case '=':
+    case '==':
+      return eq(a, b, loose)
 
-/**
- * Module variables.
- * @private
- */
+    case '!=':
+      return neq(a, b, loose)
 
-var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
+    case '>':
+      return gt(a, b, loose)
 
-/**
- * Parse the Accept-Charset header.
- * @private
- */
+    case '>=':
+      return gte(a, b, loose)
 
-function parseAcceptCharset(accept) {
-  var accepts = accept.split(',');
+    case '<':
+      return lt(a, b, loose)
 
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var charset = parseCharset(accepts[i].trim(), i);
+    case '<=':
+      return lte(a, b, loose)
 
-    if (charset) {
-      accepts[j++] = charset;
-    }
+    default:
+      throw new TypeError(`Invalid operator: ${op}`)
   }
+}
+module.exports = cmp
 
-  // trim accepts
-  accepts.length = j;
 
-  return accepts;
-}
+/***/ }),
 
-/**
- * Parse a charset from the Accept-Charset header.
- * @private
- */
+/***/ 35385:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function parseCharset(str, i) {
-  var match = simpleCharsetRegExp.exec(str);
-  if (!match) return null;
+const SemVer = __nccwpck_require__(7163)
+const parse = __nccwpck_require__(16353)
+const { safeRe: re, t } = __nccwpck_require__(95471)
 
-  var charset = match[1];
-  var q = 1;
-  if (match[2]) {
-    var params = match[2].split(';')
-    for (var j = 0; j < params.length; j++) {
-      var p = params[j].trim().split('=');
-      if (p[0] === 'q') {
-        q = parseFloat(p[1]);
-        break;
-      }
-    }
+const coerce = (version, options) => {
+  if (version instanceof SemVer) {
+    return version
   }
 
-  return {
-    charset: charset,
-    q: q,
-    i: i
-  };
-}
-
-/**
- * Get the priority of a charset.
- * @private
- */
+  if (typeof version === 'number') {
+    version = String(version)
+  }
 
-function getCharsetPriority(charset, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
+  if (typeof version !== 'string') {
+    return null
+  }
 
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(charset, accepted[i], index);
+  options = options || {}
 
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
+  let match = null
+  if (!options.rtl) {
+    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
+  } else {
+    // Find the right-most coercible string that does not share
+    // a terminus with a more left-ward coercible string.
+    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
+    // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
+    //
+    // Walk through the string checking with a /g regexp
+    // Manually set the index so as to pick up overlapping matches.
+    // Stop when we get a match that ends at the string end, since no
+    // coercible string can be more right-ward without the same terminus.
+    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
+    let next
+    while ((next = coerceRtlRegex.exec(version)) &&
+        (!match || match.index + match[0].length !== version.length)
+    ) {
+      if (!match ||
+            next.index + next[0].length !== match.index + match[0].length) {
+        match = next
+      }
+      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
     }
+    // leave it in a clean state
+    coerceRtlRegex.lastIndex = -1
   }
 
-  return priority;
-}
-
-/**
- * Get the specificity of the charset.
- * @private
- */
-
-function specify(charset, spec, index) {
-  var s = 0;
-  if(spec.charset.toLowerCase() === charset.toLowerCase()){
-    s |= 1;
-  } else if (spec.charset !== '*' ) {
+  if (match === null) {
     return null
   }
 
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s
-  }
-}
-
-/**
- * Get the preferred charsets from an Accept-Charset header.
- * @public
- */
-
-function preferredCharsets(accept, provided) {
-  // RFC 2616 sec 14.2: no header = *
-  var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');
+  const major = match[2]
+  const minor = match[3] || '0'
+  const patch = match[4] || '0'
+  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
+  const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
 
-  if (!provided) {
-    // sorted list of all charsets
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullCharset);
-  }
+  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
+}
+module.exports = coerce
 
-  var priorities = provided.map(function getPriority(type, index) {
-    return getCharsetPriority(type, accepts, index);
-  });
 
-  // sorted list of accepted charsets
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
+/***/ }),
 
-/**
- * Compare two specs.
- * @private
- */
+/***/ 37648:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
+const SemVer = __nccwpck_require__(7163)
+const compareBuild = (a, b, loose) => {
+  const versionA = new SemVer(a, loose)
+  const versionB = new SemVer(b, loose)
+  return versionA.compare(versionB) || versionA.compareBuild(versionB)
 }
+module.exports = compareBuild
 
-/**
- * Get full charset string.
- * @private
- */
 
-function getFullCharset(spec) {
-  return spec.charset;
-}
+/***/ }),
 
-/**
- * Check if a spec has any quality.
- * @private
- */
+/***/ 56874:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function isQuality(spec) {
-  return spec.q > 0;
-}
+const compare = __nccwpck_require__(78469)
+const compareLoose = (a, b) => compare(a, b, true)
+module.exports = compareLoose
 
 
 /***/ }),
 
-/***/ 25111:
-/***/ ((module) => {
+/***/ 78469:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
+const SemVer = __nccwpck_require__(7163)
+const compare = (a, b, loose) =>
+  new SemVer(a, loose).compare(new SemVer(b, loose))
 
+module.exports = compare
 
 
-/**
- * Module exports.
- * @public
- */
+/***/ }),
 
-module.exports = preferredEncodings;
-module.exports.preferredEncodings = preferredEncodings;
+/***/ 70711:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-/**
- * Module variables.
- * @private
- */
+const parse = __nccwpck_require__(16353)
 
-var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
+const diff = (version1, version2) => {
+  const v1 = parse(version1, null, true)
+  const v2 = parse(version2, null, true)
+  const comparison = v1.compare(v2)
 
-/**
- * Parse the Accept-Encoding header.
- * @private
- */
+  if (comparison === 0) {
+    return null
+  }
 
-function parseAcceptEncoding(accept) {
-  var accepts = accept.split(',');
-  var hasIdentity = false;
-  var minQuality = 1;
+  const v1Higher = comparison > 0
+  const highVersion = v1Higher ? v1 : v2
+  const lowVersion = v1Higher ? v2 : v1
+  const highHasPre = !!highVersion.prerelease.length
+  const lowHasPre = !!lowVersion.prerelease.length
 
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var encoding = parseEncoding(accepts[i].trim(), i);
+  if (lowHasPre && !highHasPre) {
+    // Going from prerelease -> no prerelease requires some special casing
 
-    if (encoding) {
-      accepts[j++] = encoding;
-      hasIdentity = hasIdentity || specify('identity', encoding);
-      minQuality = Math.min(minQuality, encoding.q || 1);
+    // If the low version has only a major, then it will always be a major
+    // Some examples:
+    // 1.0.0-1 -> 1.0.0
+    // 1.0.0-1 -> 1.1.1
+    // 1.0.0-1 -> 2.0.0
+    if (!lowVersion.patch && !lowVersion.minor) {
+      return 'major'
     }
-  }
 
-  if (!hasIdentity) {
-    /*
-     * If identity doesn't explicitly appear in the accept-encoding header,
-     * it's added to the list of acceptable encoding with the lowest q
-     */
-    accepts[j++] = {
-      encoding: 'identity',
-      q: minQuality,
-      i: i
-    };
+    // If the main part has no difference
+    if (lowVersion.compareMain(highVersion) === 0) {
+      if (lowVersion.minor && !lowVersion.patch) {
+        return 'minor'
+      }
+      return 'patch'
+    }
   }
 
-  // trim accepts
-  accepts.length = j;
-
-  return accepts;
-}
+  // add the `pre` prefix if we are going to a prerelease version
+  const prefix = highHasPre ? 'pre' : ''
 
-/**
- * Parse an encoding from the Accept-Encoding header.
- * @private
- */
+  if (v1.major !== v2.major) {
+    return prefix + 'major'
+  }
 
-function parseEncoding(str, i) {
-  var match = simpleEncodingRegExp.exec(str);
-  if (!match) return null;
+  if (v1.minor !== v2.minor) {
+    return prefix + 'minor'
+  }
 
-  var encoding = match[1];
-  var q = 1;
-  if (match[2]) {
-    var params = match[2].split(';');
-    for (var j = 0; j < params.length; j++) {
-      var p = params[j].trim().split('=');
-      if (p[0] === 'q') {
-        q = parseFloat(p[1]);
-        break;
-      }
-    }
+  if (v1.patch !== v2.patch) {
+    return prefix + 'patch'
   }
 
-  return {
-    encoding: encoding,
-    q: q,
-    i: i
-  };
+  // high and low are preleases
+  return 'prerelease'
 }
 
-/**
- * Get the priority of an encoding.
- * @private
- */
+module.exports = diff
 
-function getEncodingPriority(encoding, accepted, index) {
-  var priority = {encoding: encoding, o: -1, q: 0, s: 0};
 
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(encoding, accepted[i], index);
+/***/ }),
 
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
-  }
+/***/ 55082:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  return priority;
-}
+const compare = __nccwpck_require__(78469)
+const eq = (a, b, loose) => compare(a, b, loose) === 0
+module.exports = eq
 
-/**
- * Get the specificity of the encoding.
- * @private
- */
 
-function specify(encoding, spec, index) {
-  var s = 0;
-  if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
-    s |= 1;
-  } else if (spec.encoding !== '*' ) {
-    return null
-  }
+/***/ }),
 
-  return {
-    encoding: encoding,
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s
-  }
-};
+/***/ 16599:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-/**
- * Get the preferred encodings from an Accept-Encoding header.
- * @public
- */
+const compare = __nccwpck_require__(78469)
+const gt = (a, b, loose) => compare(a, b, loose) > 0
+module.exports = gt
 
-function preferredEncodings(accept, provided, preferred) {
-  var accepts = parseAcceptEncoding(accept || '');
 
-  var comparator = preferred ? function comparator (a, b) {
-    if (a.q !== b.q) {
-      return b.q - a.q // higher quality first
-    }
+/***/ }),
+
+/***/ 41236:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const compare = __nccwpck_require__(78469)
+const gte = (a, b, loose) => compare(a, b, loose) >= 0
+module.exports = gte
 
-    var aPreferred = preferred.indexOf(a.encoding)
-    var bPreferred = preferred.indexOf(b.encoding)
 
-    if (aPreferred === -1 && bPreferred === -1) {
-      // consider the original specifity/order
-      return (b.s - a.s) || (a.o - b.o) || (a.i - b.i)
-    }
+/***/ }),
 
-    if (aPreferred !== -1 && bPreferred !== -1) {
-      return aPreferred - bPreferred // consider the preferred order
-    }
+/***/ 62338:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    return aPreferred === -1 ? 1 : -1 // preferred first
-  } : compareSpecs;
+const SemVer = __nccwpck_require__(7163)
 
-  if (!provided) {
-    // sorted list of all encodings
-    return accepts
-      .filter(isQuality)
-      .sort(comparator)
-      .map(getFullEncoding);
+const inc = (version, release, options, identifier, identifierBase) => {
+  if (typeof (options) === 'string') {
+    identifierBase = identifier
+    identifier = options
+    options = undefined
   }
 
-  var priorities = provided.map(function getPriority(type, index) {
-    return getEncodingPriority(type, accepts, index);
-  });
-
-  // sorted list of accepted encodings
-  return priorities.filter(isQuality).sort(comparator).map(function getEncoding(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
+  try {
+    return new SemVer(
+      version instanceof SemVer ? version.version : version,
+      options
+    ).inc(release, identifier, identifierBase).version
+  } catch (er) {
+    return null
+  }
 }
+module.exports = inc
 
-/**
- * Compare two specs.
- * @private
- */
 
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i);
-}
+/***/ }),
 
-/**
- * Get full encoding string.
- * @private
- */
+/***/ 3872:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function getFullEncoding(spec) {
-  return spec.encoding;
-}
+const compare = __nccwpck_require__(78469)
+const lt = (a, b, loose) => compare(a, b, loose) < 0
+module.exports = lt
 
-/**
- * Check if a spec has any quality.
- * @private
- */
 
-function isQuality(spec) {
-  return spec.q > 0;
-}
+/***/ }),
+
+/***/ 56717:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const compare = __nccwpck_require__(78469)
+const lte = (a, b, loose) => compare(a, b, loose) <= 0
+module.exports = lte
 
 
 /***/ }),
 
-/***/ 56008:
-/***/ ((module) => {
+/***/ 68511:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
+const SemVer = __nccwpck_require__(7163)
+const major = (a, loose) => new SemVer(a, loose).major
+module.exports = major
 
 
+/***/ }),
 
-/**
- * Module exports.
- * @public
- */
+/***/ 32603:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-module.exports = preferredLanguages;
-module.exports.preferredLanguages = preferredLanguages;
+const SemVer = __nccwpck_require__(7163)
+const minor = (a, loose) => new SemVer(a, loose).minor
+module.exports = minor
 
-/**
- * Module variables.
- * @private
- */
 
-var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
+/***/ }),
 
-/**
- * Parse the Accept-Language header.
- * @private
- */
+/***/ 4974:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function parseAcceptLanguage(accept) {
-  var accepts = accept.split(',');
+const compare = __nccwpck_require__(78469)
+const neq = (a, b, loose) => compare(a, b, loose) !== 0
+module.exports = neq
 
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var language = parseLanguage(accepts[i].trim(), i);
 
-    if (language) {
-      accepts[j++] = language;
+/***/ }),
+
+/***/ 16353:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const SemVer = __nccwpck_require__(7163)
+const parse = (version, options, throwErrors = false) => {
+  if (version instanceof SemVer) {
+    return version
+  }
+  try {
+    return new SemVer(version, options)
+  } catch (er) {
+    if (!throwErrors) {
+      return null
     }
+    throw er
   }
+}
 
-  // trim accepts
-  accepts.length = j;
+module.exports = parse
 
-  return accepts;
-}
 
-/**
- * Parse a language from the Accept-Language header.
- * @private
- */
+/***/ }),
 
-function parseLanguage(str, i) {
-  var match = simpleLanguageRegExp.exec(str);
-  if (!match) return null;
+/***/ 48756:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  var prefix = match[1]
-  var suffix = match[2]
-  var full = prefix
+const SemVer = __nccwpck_require__(7163)
+const patch = (a, loose) => new SemVer(a, loose).patch
+module.exports = patch
 
-  if (suffix) full += "-" + suffix;
 
-  var q = 1;
-  if (match[3]) {
-    var params = match[3].split(';')
-    for (var j = 0; j < params.length; j++) {
-      var p = params[j].split('=');
-      if (p[0] === 'q') q = parseFloat(p[1]);
-    }
-  }
+/***/ }),
 
-  return {
-    prefix: prefix,
-    suffix: suffix,
-    q: q,
-    i: i,
-    full: full
-  };
+/***/ 15714:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const parse = __nccwpck_require__(16353)
+const prerelease = (version, options) => {
+  const parsed = parse(version, options)
+  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
 }
+module.exports = prerelease
 
-/**
- * Get the priority of a language.
- * @private
- */
 
-function getLanguagePriority(language, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
+/***/ }),
 
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(language, accepted[i], index);
+/***/ 32173:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
-  }
+const compare = __nccwpck_require__(78469)
+const rcompare = (a, b, loose) => compare(b, a, loose)
+module.exports = rcompare
 
-  return priority;
-}
 
-/**
- * Get the specificity of the language.
- * @private
- */
+/***/ }),
 
-function specify(language, spec, index) {
-  var p = parseLanguage(language)
-  if (!p) return null;
-  var s = 0;
-  if(spec.full.toLowerCase() === p.full.toLowerCase()){
-    s |= 4;
-  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
-    s |= 2;
-  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
-    s |= 1;
-  } else if (spec.full !== '*' ) {
-    return null
-  }
+/***/ 87192:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s
-  }
-};
+const compareBuild = __nccwpck_require__(37648)
+const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
+module.exports = rsort
 
-/**
- * Get the preferred languages from an Accept-Language header.
- * @public
- */
 
-function preferredLanguages(accept, provided) {
-  // RFC 2616 sec 14.4: no header = *
-  var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');
+/***/ }),
 
-  if (!provided) {
-    // sorted list of all languages
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullLanguage);
+/***/ 68011:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const Range = __nccwpck_require__(96782)
+const satisfies = (version, range, options) => {
+  try {
+    range = new Range(range, options)
+  } catch (er) {
+    return false
   }
+  return range.test(version)
+}
+module.exports = satisfies
 
-  var priorities = provided.map(function getPriority(type, index) {
-    return getLanguagePriority(type, accepts, index);
-  });
 
-  // sorted list of accepted languages
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
+/***/ }),
 
-/**
- * Compare two specs.
- * @private
- */
+/***/ 29872:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
-}
+const compareBuild = __nccwpck_require__(37648)
+const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
+module.exports = sort
 
-/**
- * Get full language string.
- * @private
- */
 
-function getFullLanguage(spec) {
-  return spec.full;
+/***/ }),
+
+/***/ 58780:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const parse = __nccwpck_require__(16353)
+const valid = (version, options) => {
+  const v = parse(version, options)
+  return v ? v.version : null
 }
+module.exports = valid
 
-/**
- * Check if a spec has any quality.
- * @private
- */
 
-function isQuality(spec) {
-  return spec.q > 0;
+/***/ }),
+
+/***/ 62088:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+// just pre-load all the stuff that index.js lazily exports
+const internalRe = __nccwpck_require__(95471)
+const constants = __nccwpck_require__(45101)
+const SemVer = __nccwpck_require__(7163)
+const identifiers = __nccwpck_require__(73348)
+const parse = __nccwpck_require__(16353)
+const valid = __nccwpck_require__(58780)
+const clean = __nccwpck_require__(1799)
+const inc = __nccwpck_require__(62338)
+const diff = __nccwpck_require__(70711)
+const major = __nccwpck_require__(68511)
+const minor = __nccwpck_require__(32603)
+const patch = __nccwpck_require__(48756)
+const prerelease = __nccwpck_require__(15714)
+const compare = __nccwpck_require__(78469)
+const rcompare = __nccwpck_require__(32173)
+const compareLoose = __nccwpck_require__(56874)
+const compareBuild = __nccwpck_require__(37648)
+const sort = __nccwpck_require__(29872)
+const rsort = __nccwpck_require__(87192)
+const gt = __nccwpck_require__(16599)
+const lt = __nccwpck_require__(3872)
+const eq = __nccwpck_require__(55082)
+const neq = __nccwpck_require__(4974)
+const gte = __nccwpck_require__(41236)
+const lte = __nccwpck_require__(56717)
+const cmp = __nccwpck_require__(28646)
+const coerce = __nccwpck_require__(35385)
+const Comparator = __nccwpck_require__(89379)
+const Range = __nccwpck_require__(96782)
+const satisfies = __nccwpck_require__(68011)
+const toComparators = __nccwpck_require__(54750)
+const maxSatisfying = __nccwpck_require__(73193)
+const minSatisfying = __nccwpck_require__(68595)
+const minVersion = __nccwpck_require__(51866)
+const validRange = __nccwpck_require__(64737)
+const outside = __nccwpck_require__(10280)
+const gtr = __nccwpck_require__(12276)
+const ltr = __nccwpck_require__(15213)
+const intersects = __nccwpck_require__(23465)
+const simplifyRange = __nccwpck_require__(82028)
+const subset = __nccwpck_require__(61489)
+module.exports = {
+  parse,
+  valid,
+  clean,
+  inc,
+  diff,
+  major,
+  minor,
+  patch,
+  prerelease,
+  compare,
+  rcompare,
+  compareLoose,
+  compareBuild,
+  sort,
+  rsort,
+  gt,
+  lt,
+  eq,
+  neq,
+  gte,
+  lte,
+  cmp,
+  coerce,
+  Comparator,
+  Range,
+  satisfies,
+  toComparators,
+  maxSatisfying,
+  minSatisfying,
+  minVersion,
+  validRange,
+  outside,
+  gtr,
+  ltr,
+  intersects,
+  simplifyRange,
+  subset,
+  SemVer,
+  re: internalRe.re,
+  src: internalRe.src,
+  tokens: internalRe.t,
+  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
+  RELEASE_TYPES: constants.RELEASE_TYPES,
+  compareIdentifiers: identifiers.compareIdentifiers,
+  rcompareIdentifiers: identifiers.rcompareIdentifiers,
 }
 
 
 /***/ }),
 
-/***/ 53672:
+/***/ 45101:
 /***/ ((module) => {
 
-"use strict";
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
+// Note: this is the semver.org version of the spec that it implements
+// Not necessarily the package version of this code.
+const SEMVER_SPEC_VERSION = '2.0.0'
 
+const MAX_LENGTH = 256
+const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
+/* istanbul ignore next */ 9007199254740991
 
+// Max safe segment length for coercion.
+const MAX_SAFE_COMPONENT_LENGTH = 16
 
-/**
- * Module exports.
- * @public
- */
+// Max safe length for a build identifier. The max length minus 6 characters for
+// the shortest version with a build 0.0.0+BUILD.
+const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
 
-module.exports = preferredMediaTypes;
-module.exports.preferredMediaTypes = preferredMediaTypes;
+const RELEASE_TYPES = [
+  'major',
+  'premajor',
+  'minor',
+  'preminor',
+  'patch',
+  'prepatch',
+  'prerelease',
+]
 
-/**
- * Module variables.
- * @private
- */
+module.exports = {
+  MAX_LENGTH,
+  MAX_SAFE_COMPONENT_LENGTH,
+  MAX_SAFE_BUILD_LENGTH,
+  MAX_SAFE_INTEGER,
+  RELEASE_TYPES,
+  SEMVER_SPEC_VERSION,
+  FLAG_INCLUDE_PRERELEASE: 0b001,
+  FLAG_LOOSE: 0b010,
+}
 
-var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
 
-/**
- * Parse the Accept header.
- * @private
- */
+/***/ }),
 
-function parseAccept(accept) {
-  var accepts = splitMediaTypes(accept);
+/***/ 1159:
+/***/ ((module) => {
 
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var mediaType = parseMediaType(accepts[i].trim(), i);
+const debug = (
+  typeof process === 'object' &&
+  process.env &&
+  process.env.NODE_DEBUG &&
+  /\bsemver\b/i.test(process.env.NODE_DEBUG)
+) ? (...args) => console.error('SEMVER', ...args)
+  : () => {}
 
-    if (mediaType) {
-      accepts[j++] = mediaType;
-    }
+module.exports = debug
+
+
+/***/ }),
+
+/***/ 73348:
+/***/ ((module) => {
+
+const numeric = /^[0-9]+$/
+const compareIdentifiers = (a, b) => {
+  const anum = numeric.test(a)
+  const bnum = numeric.test(b)
+
+  if (anum && bnum) {
+    a = +a
+    b = +b
   }
 
-  // trim accepts
-  accepts.length = j;
+  return a === b ? 0
+    : (anum && !bnum) ? -1
+    : (bnum && !anum) ? 1
+    : a < b ? -1
+    : 1
+}
 
-  return accepts;
+const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
+
+module.exports = {
+  compareIdentifiers,
+  rcompareIdentifiers,
 }
 
-/**
- * Parse a media type from the Accept header.
- * @private
- */
 
-function parseMediaType(str, i) {
-  var match = simpleMediaTypeRegExp.exec(str);
-  if (!match) return null;
+/***/ }),
 
-  var params = Object.create(null);
-  var q = 1;
-  var subtype = match[2];
-  var type = match[1];
+/***/ 61383:
+/***/ ((module) => {
 
-  if (match[3]) {
-    var kvps = splitParameters(match[3]).map(splitKeyValuePair);
+class LRUCache {
+  constructor () {
+    this.max = 1000
+    this.map = new Map()
+  }
 
-    for (var j = 0; j < kvps.length; j++) {
-      var pair = kvps[j];
-      var key = pair[0].toLowerCase();
-      var val = pair[1];
+  get (key) {
+    const value = this.map.get(key)
+    if (value === undefined) {
+      return undefined
+    } else {
+      // Remove the key from the map and add it to the end
+      this.map.delete(key)
+      this.map.set(key, value)
+      return value
+    }
+  }
 
-      // get the value, unwrapping quotes
-      var value = val && val[0] === '"' && val[val.length - 1] === '"'
-        ? val.slice(1, -1)
-        : val;
+  delete (key) {
+    return this.map.delete(key)
+  }
 
-      if (key === 'q') {
-        q = parseFloat(value);
-        break;
+  set (key, value) {
+    const deleted = this.delete(key)
+
+    if (!deleted && value !== undefined) {
+      // If cache is full, delete the least recently used item
+      if (this.map.size >= this.max) {
+        const firstKey = this.map.keys().next().value
+        this.delete(firstKey)
       }
 
-      // store parameter
-      params[key] = value;
+      this.map.set(key, value)
     }
-  }
 
-  return {
-    type: type,
-    subtype: subtype,
-    params: params,
-    q: q,
-    i: i
-  };
+    return this
+  }
 }
 
-/**
- * Get the priority of a media type.
- * @private
- */
+module.exports = LRUCache
 
-function getMediaTypePriority(type, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
 
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(type, accepted[i], index);
+/***/ }),
+
+/***/ 70356:
+/***/ ((module) => {
+
+// parse out just the options we care about
+const looseOption = Object.freeze({ loose: true })
+const emptyOpts = Object.freeze({ })
+const parseOptions = options => {
+  if (!options) {
+    return emptyOpts
+  }
 
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
+  if (typeof options !== 'object') {
+    return looseOption
   }
 
-  return priority;
+  return options
 }
+module.exports = parseOptions
 
-/**
- * Get the specificity of the media type.
- * @private
- */
 
-function specify(type, spec, index) {
-  var p = parseMediaType(type);
-  var s = 0;
+/***/ }),
 
-  if (!p) {
-    return null;
-  }
+/***/ 95471:
+/***/ ((module, exports, __nccwpck_require__) => {
 
-  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
-    s |= 4
-  } else if(spec.type != '*') {
-    return null;
-  }
+const {
+  MAX_SAFE_COMPONENT_LENGTH,
+  MAX_SAFE_BUILD_LENGTH,
+  MAX_LENGTH,
+} = __nccwpck_require__(45101)
+const debug = __nccwpck_require__(1159)
+exports = module.exports = {}
 
-  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
-    s |= 2
-  } else if(spec.subtype != '*') {
-    return null;
-  }
+// The actual regexps go on exports.re
+const re = exports.re = []
+const safeRe = exports.safeRe = []
+const src = exports.src = []
+const safeSrc = exports.safeSrc = []
+const t = exports.t = {}
+let R = 0
 
-  var keys = Object.keys(spec.params);
-  if (keys.length > 0) {
-    if (keys.every(function (k) {
-      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
-    })) {
-      s |= 1
-    } else {
-      return null
-    }
-  }
+const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
 
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s,
+// Replace some greedy regex tokens to prevent regex dos issues. These regex are
+// used internally via the safeRe object since all inputs in this library get
+// normalized first to trim and collapse all extra whitespace. The original
+// regexes are exported for userland consumption and lower level usage. A
+// future breaking change could export the safer regex only with a note that
+// all input should have extra whitespace removed.
+const safeRegexReplacements = [
+  ['\\s', 1],
+  ['\\d', MAX_LENGTH],
+  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
+]
+
+const makeSafeRegex = (value) => {
+  for (const [token, max] of safeRegexReplacements) {
+    value = value
+      .split(`${token}*`).join(`${token}{0,${max}}`)
+      .split(`${token}+`).join(`${token}{1,${max}}`)
   }
+  return value
 }
 
-/**
- * Get the preferred media types from an Accept header.
- * @public
- */
-
-function preferredMediaTypes(accept, provided) {
-  // RFC 2616 sec 14.2: no header = */*
-  var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');
-
-  if (!provided) {
-    // sorted list of all types
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullType);
-  }
+const createToken = (name, value, isGlobal) => {
+  const safe = makeSafeRegex(value)
+  const index = R++
+  debug(name, index, value)
+  t[name] = index
+  src[index] = value
+  safeSrc[index] = safe
+  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
+  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
+}
 
-  var priorities = provided.map(function getPriority(type, index) {
-    return getMediaTypePriority(type, accepts, index);
-  });
+// The following Regular Expressions can be used for tokenizing,
+// validating, and parsing SemVer version strings.
 
-  // sorted list of accepted types
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
+// ## Numeric Identifier
+// A single `0`, or a non-zero digit followed by zero or more digits.
 
-/**
- * Compare two specs.
- * @private
- */
+createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
+createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
 
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
-}
+// ## Non-numeric Identifier
+// Zero or more digits, followed by a letter or hyphen, and then zero or
+// more letters, digits, or hyphens.
 
-/**
- * Get full type string.
- * @private
- */
+createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
 
-function getFullType(spec) {
-  return spec.type + '/' + spec.subtype;
-}
+// ## Main Version
+// Three dot-separated numeric identifiers.
 
-/**
- * Check if a spec has any quality.
- * @private
- */
+createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
+                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
+                   `(${src[t.NUMERICIDENTIFIER]})`)
 
-function isQuality(spec) {
-  return spec.q > 0;
-}
+createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
+                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
+                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)
 
-/**
- * Count the number of quotes in a string.
- * @private
- */
+// ## Pre-release Version Identifier
+// A numeric identifier, or a non-numeric identifier.
 
-function quoteCount(string) {
-  var count = 0;
-  var index = 0;
+createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
+}|${src[t.NONNUMERICIDENTIFIER]})`)
 
-  while ((index = string.indexOf('"', index)) !== -1) {
-    count++;
-    index++;
-  }
+createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
+}|${src[t.NONNUMERICIDENTIFIER]})`)
 
-  return count;
-}
+// ## Pre-release Version
+// Hyphen, followed by one or more dot-separated pre-release version
+// identifiers.
 
-/**
- * Split a key value pair.
- * @private
- */
+createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
+}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
 
-function splitKeyValuePair(str) {
-  var index = str.indexOf('=');
-  var key;
-  var val;
+createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
+}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
 
-  if (index === -1) {
-    key = str;
-  } else {
-    key = str.slice(0, index);
-    val = str.slice(index + 1);
-  }
+// ## Build Metadata Identifier
+// Any combination of digits, letters, or hyphens.
 
-  return [key, val];
-}
+createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
 
-/**
- * Split an Accept header into media types.
- * @private
- */
+// ## Build Metadata
+// Plus sign, followed by one or more period-separated build metadata
+// identifiers.
 
-function splitMediaTypes(accept) {
-  var accepts = accept.split(',');
+createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
+}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
 
-  for (var i = 1, j = 0; i < accepts.length; i++) {
-    if (quoteCount(accepts[j]) % 2 == 0) {
-      accepts[++j] = accepts[i];
-    } else {
-      accepts[j] += ',' + accepts[i];
-    }
-  }
+// ## Full Version String
+// A main version, followed optionally by a pre-release version and
+// build metadata.
 
-  // trim accepts
-  accepts.length = j + 1;
+// Note that the only major, minor, patch, and pre-release sections of
+// the version string are capturing groups.  The build metadata is not a
+// capturing group, because it should not ever be used in version
+// comparison.
 
-  return accepts;
-}
+createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
+}${src[t.PRERELEASE]}?${
+  src[t.BUILD]}?`)
 
-/**
- * Split a string of parameters.
- * @private
- */
+createToken('FULL', `^${src[t.FULLPLAIN]}$`)
 
-function splitParameters(str) {
-  var parameters = str.split(';');
+// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
+// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
+// common in the npm registry.
+createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
+}${src[t.PRERELEASELOOSE]}?${
+  src[t.BUILD]}?`)
 
-  for (var i = 1, j = 0; i < parameters.length; i++) {
-    if (quoteCount(parameters[j]) % 2 == 0) {
-      parameters[++j] = parameters[i];
-    } else {
-      parameters[j] += ';' + parameters[i];
-    }
-  }
+createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
 
-  // trim parameters
-  parameters.length = j + 1;
+createToken('GTLT', '((?:<|>)?=?)')
 
-  for (var i = 0; i < parameters.length; i++) {
-    parameters[i] = parameters[i].trim();
-  }
+// Something like "2.*" or "1.2.x".
+// Note that "x.x" is a valid xRange identifer, meaning "any version"
+// Only the first item is strictly required.
+createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
+createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
 
-  return parameters;
-}
+createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
+                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
+                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
+                   `(?:${src[t.PRERELEASE]})?${
+                     src[t.BUILD]}?` +
+                   `)?)?`)
 
+createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
+                        `(?:${src[t.PRERELEASELOOSE]})?${
+                          src[t.BUILD]}?` +
+                        `)?)?`)
 
-/***/ }),
+createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
+createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
 
-/***/ 55560:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// Coercion.
+// Extract anything that could conceivably be a part of a valid semver
+createToken('COERCEPLAIN', `${'(^|[^\\d])' +
+              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
+              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
+              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
+createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
+createToken('COERCEFULL', src[t.COERCEPLAIN] +
+              `(?:${src[t.PRERELEASE]})?` +
+              `(?:${src[t.BUILD]})?` +
+              `(?:$|[^\\d])`)
+createToken('COERCERTL', src[t.COERCE], true)
+createToken('COERCERTLFULL', src[t.COERCEFULL], true)
 
-var wrappy = __nccwpck_require__(58264)
-module.exports = wrappy(once)
-module.exports.strict = wrappy(onceStrict)
+// Tilde ranges.
+// Meaning is "reasonably at or greater than"
+createToken('LONETILDE', '(?:~>?)')
 
-once.proto = once(function () {
-  Object.defineProperty(Function.prototype, 'once', {
-    value: function () {
-      return once(this)
-    },
-    configurable: true
-  })
+createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
+exports.tildeTrimReplace = '$1~'
 
-  Object.defineProperty(Function.prototype, 'onceStrict', {
-    value: function () {
-      return onceStrict(this)
-    },
-    configurable: true
-  })
-})
+createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
+createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
 
-function once (fn) {
-  var f = function () {
-    if (f.called) return f.value
-    f.called = true
-    return f.value = fn.apply(this, arguments)
-  }
-  f.called = false
-  return f
-}
+// Caret ranges.
+// Meaning is "at least and backwards compatible with"
+createToken('LONECARET', '(?:\\^)')
 
-function onceStrict (fn) {
-  var f = function () {
-    if (f.called)
-      throw new Error(f.onceError)
-    f.called = true
-    return f.value = fn.apply(this, arguments)
-  }
-  var name = fn.name || 'Function wrapped with `once`'
-  f.onceError = name + " shouldn't be called more than once"
-  f.called = false
-  return f
-}
+createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
+exports.caretTrimReplace = '$1^'
 
+createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
+createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
 
-/***/ }),
+// A simple gt/lt/eq thing, or just "" to indicate "any version"
+createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
+createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
 
-/***/ 26687:
-/***/ ((module) => {
+// An expression to strip any whitespace between the gtlt and the thing
+// it modifies, so that `> 1.2.3` ==> `>1.2.3`
+createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
+}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
+exports.comparatorTrimReplace = '$1$2$3'
 
-const META = Symbol('proc-log.meta')
-module.exports = {
-  META: META,
-  output: {
-    LEVELS: [
-      'standard',
-      'error',
-      'buffer',
-      'flush',
-    ],
-    KEYS: {
-      standard: 'standard',
-      error: 'error',
-      buffer: 'buffer',
-      flush: 'flush',
-    },
-    standard: function (...args) {
-      return process.emit('output', 'standard', ...args)
-    },
-    error: function (...args) {
-      return process.emit('output', 'error', ...args)
-    },
-    buffer: function (...args) {
-      return process.emit('output', 'buffer', ...args)
-    },
-    flush: function (...args) {
-      return process.emit('output', 'flush', ...args)
-    },
-  },
-  log: {
-    LEVELS: [
-      'notice',
-      'error',
-      'warn',
-      'info',
-      'verbose',
-      'http',
-      'silly',
-      'timing',
-      'pause',
-      'resume',
-    ],
-    KEYS: {
-      notice: 'notice',
-      error: 'error',
-      warn: 'warn',
-      info: 'info',
-      verbose: 'verbose',
-      http: 'http',
-      silly: 'silly',
-      timing: 'timing',
-      pause: 'pause',
-      resume: 'resume',
-    },
-    error: function (...args) {
-      return process.emit('log', 'error', ...args)
-    },
-    notice: function (...args) {
-      return process.emit('log', 'notice', ...args)
-    },
-    warn: function (...args) {
-      return process.emit('log', 'warn', ...args)
-    },
-    info: function (...args) {
-      return process.emit('log', 'info', ...args)
-    },
-    verbose: function (...args) {
-      return process.emit('log', 'verbose', ...args)
-    },
-    http: function (...args) {
-      return process.emit('log', 'http', ...args)
-    },
-    silly: function (...args) {
-      return process.emit('log', 'silly', ...args)
-    },
-    timing: function (...args) {
-      return process.emit('log', 'timing', ...args)
-    },
-    pause: function () {
-      return process.emit('log', 'pause')
-    },
-    resume: function () {
-      return process.emit('log', 'resume')
-    },
-  },
-  time: {
-    LEVELS: [
-      'start',
-      'end',
-    ],
-    KEYS: {
-      start: 'start',
-      end: 'end',
-    },
-    start: function (name, fn) {
-      process.emit('time', 'start', name)
-      function end () {
-        return process.emit('time', 'end', name)
-      }
-      if (typeof fn === 'function') {
-        const res = fn()
-        if (res && res.finally) {
-          return res.finally(end)
-        }
-        end()
-        return res
-      }
-      return end
-    },
-    end: function (name) {
-      return process.emit('time', 'end', name)
-    },
-  },
-  input: {
-    LEVELS: [
-      'start',
-      'end',
-      'read',
-    ],
-    KEYS: {
-      start: 'start',
-      end: 'end',
-      read: 'read',
-    },
-    start: function (fn) {
-      process.emit('input', 'start')
-      function end () {
-        return process.emit('input', 'end')
-      }
-      if (typeof fn === 'function') {
-        const res = fn()
-        if (res && res.finally) {
-          return res.finally(end)
-        }
-        end()
-        return res
-      }
-      return end
-    },
-    end: function () {
-      return process.emit('input', 'end')
-    },
-    read: function (...args) {
-      let resolve, reject
-      const promise = new Promise((_resolve, _reject) => {
-        resolve = _resolve
-        reject = _reject
-      })
-      process.emit('input', 'read', resolve, reject, ...args)
-      return promise
-    },
-  },
-}
+// Something like `1.2.3 - 1.2.4`
+// Note that these all use the loose form, because they'll be
+// checked against either the strict or loose comparator form
+// later.
+createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
+                   `\\s+-\\s+` +
+                   `(${src[t.XRANGEPLAIN]})` +
+                   `\\s*$`)
+
+createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
+                        `\\s+-\\s+` +
+                        `(${src[t.XRANGEPLAINLOOSE]})` +
+                        `\\s*$`)
+
+// Star ranges basically just allow anything at all.
+createToken('STAR', '(<|>)?=?\\s*\\*')
+// >=0.0.0 is like a star
+createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
+createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
 
 
 /***/ }),
 
-/***/ 90390:
+/***/ 12276:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
+// Determine if version is greater than all the versions possible in the range.
+const outside = __nccwpck_require__(10280)
+const gtr = (version, range, options) => outside(version, range, '>', options)
+module.exports = gtr
 
 
-var errcode = __nccwpck_require__(14339);
-var retry = __nccwpck_require__(5546);
+/***/ }),
 
-var hasOwn = Object.prototype.hasOwnProperty;
+/***/ 23465:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function isRetryError(err) {
-    return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried');
+const Range = __nccwpck_require__(96782)
+const intersects = (r1, r2, options) => {
+  r1 = new Range(r1, options)
+  r2 = new Range(r2, options)
+  return r1.intersects(r2, options)
 }
+module.exports = intersects
 
-function promiseRetry(fn, options) {
-    var temp;
-    var operation;
 
-    if (typeof fn === 'object' && typeof options === 'function') {
-        // Swap options and fn when using alternate signature (options, fn)
-        temp = options;
-        options = fn;
-        fn = temp;
-    }
+/***/ }),
 
-    operation = retry.operation(options);
+/***/ 15213:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-    return new Promise(function (resolve, reject) {
-        operation.attempt(function (number) {
-            Promise.resolve()
-            .then(function () {
-                return fn(function (err) {
-                    if (isRetryError(err)) {
-                        err = err.retried;
-                    }
+const outside = __nccwpck_require__(10280)
+// Determine if version is less than all the versions possible in the range
+const ltr = (version, range, options) => outside(version, range, '<', options)
+module.exports = ltr
 
-                    throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err });
-                }, number);
-            })
-            .then(resolve, function (err) {
-                if (isRetryError(err)) {
-                    err = err.retried;
 
-                    if (operation.retry(err || new Error())) {
-                        return;
-                    }
-                }
+/***/ }),
 
-                reject(err);
-            });
-        });
-    });
-}
+/***/ 73193:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-module.exports = promiseRetry;
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(96782)
+
+const maxSatisfying = (versions, range, options) => {
+  let max = null
+  let maxSV = null
+  let rangeObj = null
+  try {
+    rangeObj = new Range(range, options)
+  } catch (er) {
+    return null
+  }
+  versions.forEach((v) => {
+    if (rangeObj.test(v)) {
+      // satisfies(v, range, options)
+      if (!max || maxSV.compare(v) === -1) {
+        // compare(max, v, true)
+        max = v
+        maxSV = new SemVer(max, options)
+      }
+    }
+  })
+  return max
+}
+module.exports = maxSatisfying
 
 
 /***/ }),
 
-/***/ 5546:
+/***/ 68595:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-module.exports = __nccwpck_require__(67084);
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(96782)
+const minSatisfying = (versions, range, options) => {
+  let min = null
+  let minSV = null
+  let rangeObj = null
+  try {
+    rangeObj = new Range(range, options)
+  } catch (er) {
+    return null
+  }
+  versions.forEach((v) => {
+    if (rangeObj.test(v)) {
+      // satisfies(v, range, options)
+      if (!min || minSV.compare(v) === 1) {
+        // compare(min, v, true)
+        min = v
+        minSV = new SemVer(min, options)
+      }
+    }
+  })
+  return min
+}
+module.exports = minSatisfying
+
 
 /***/ }),
 
-/***/ 67084:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 51866:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-var RetryOperation = __nccwpck_require__(39538);
+const SemVer = __nccwpck_require__(7163)
+const Range = __nccwpck_require__(96782)
+const gt = __nccwpck_require__(16599)
 
-exports.operation = function(options) {
-  var timeouts = exports.timeouts(options);
-  return new RetryOperation(timeouts, {
-      forever: options && options.forever,
-      unref: options && options.unref,
-      maxRetryTime: options && options.maxRetryTime
-  });
-};
+const minVersion = (range, loose) => {
+  range = new Range(range, loose)
 
-exports.timeouts = function(options) {
-  if (options instanceof Array) {
-    return [].concat(options);
+  let minver = new SemVer('0.0.0')
+  if (range.test(minver)) {
+    return minver
   }
 
-  var opts = {
-    retries: 10,
-    factor: 2,
-    minTimeout: 1 * 1000,
-    maxTimeout: Infinity,
-    randomize: false
-  };
-  for (var key in options) {
-    opts[key] = options[key];
+  minver = new SemVer('0.0.0-0')
+  if (range.test(minver)) {
+    return minver
   }
 
-  if (opts.minTimeout > opts.maxTimeout) {
-    throw new Error('minTimeout is greater than maxTimeout');
-  }
+  minver = null
+  for (let i = 0; i < range.set.length; ++i) {
+    const comparators = range.set[i]
 
-  var timeouts = [];
-  for (var i = 0; i < opts.retries; i++) {
-    timeouts.push(this.createTimeout(i, opts));
+    let setMin = null
+    comparators.forEach((comparator) => {
+      // Clone to avoid manipulating the comparator's semver object.
+      const compver = new SemVer(comparator.semver.version)
+      switch (comparator.operator) {
+        case '>':
+          if (compver.prerelease.length === 0) {
+            compver.patch++
+          } else {
+            compver.prerelease.push(0)
+          }
+          compver.raw = compver.format()
+          /* fallthrough */
+        case '':
+        case '>=':
+          if (!setMin || gt(compver, setMin)) {
+            setMin = compver
+          }
+          break
+        case '<':
+        case '<=':
+          /* Ignore maximum versions */
+          break
+        /* istanbul ignore next */
+        default:
+          throw new Error(`Unexpected operation: ${comparator.operator}`)
+      }
+    })
+    if (setMin && (!minver || gt(minver, setMin))) {
+      minver = setMin
+    }
   }
 
-  if (options && options.forever && !timeouts.length) {
-    timeouts.push(this.createTimeout(i, opts));
+  if (minver && range.test(minver)) {
+    return minver
   }
 
-  // sort the array numerically ascending
-  timeouts.sort(function(a,b) {
-    return a - b;
-  });
+  return null
+}
+module.exports = minVersion
 
-  return timeouts;
-};
 
-exports.createTimeout = function(attempt, opts) {
-  var random = (opts.randomize)
-    ? (Math.random() + 1)
-    : 1;
+/***/ }),
 
-  var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
-  timeout = Math.min(timeout, opts.maxTimeout);
+/***/ 10280:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-  return timeout;
-};
+const SemVer = __nccwpck_require__(7163)
+const Comparator = __nccwpck_require__(89379)
+const { ANY } = Comparator
+const Range = __nccwpck_require__(96782)
+const satisfies = __nccwpck_require__(68011)
+const gt = __nccwpck_require__(16599)
+const lt = __nccwpck_require__(3872)
+const lte = __nccwpck_require__(56717)
+const gte = __nccwpck_require__(41236)
 
-exports.wrap = function(obj, options, methods) {
-  if (options instanceof Array) {
-    methods = options;
-    options = null;
+const outside = (version, range, hilo, options) => {
+  version = new SemVer(version, options)
+  range = new Range(range, options)
+
+  let gtfn, ltefn, ltfn, comp, ecomp
+  switch (hilo) {
+    case '>':
+      gtfn = gt
+      ltefn = lte
+      ltfn = lt
+      comp = '>'
+      ecomp = '>='
+      break
+    case '<':
+      gtfn = lt
+      ltefn = gte
+      ltfn = gt
+      comp = '<'
+      ecomp = '<='
+      break
+    default:
+      throw new TypeError('Must provide a hilo val of "<" or ">"')
   }
 
-  if (!methods) {
-    methods = [];
-    for (var key in obj) {
-      if (typeof obj[key] === 'function') {
-        methods.push(key);
+  // If it satisfies the range it is not outside
+  if (satisfies(version, range, options)) {
+    return false
+  }
+
+  // From now on, variable terms are as if we're in "gtr" mode.
+  // but note that everything is flipped for the "ltr" function.
+
+  for (let i = 0; i < range.set.length; ++i) {
+    const comparators = range.set[i]
+
+    let high = null
+    let low = null
+
+    comparators.forEach((comparator) => {
+      if (comparator.semver === ANY) {
+        comparator = new Comparator('>=0.0.0')
+      }
+      high = high || comparator
+      low = low || comparator
+      if (gtfn(comparator.semver, high.semver, options)) {
+        high = comparator
+      } else if (ltfn(comparator.semver, low.semver, options)) {
+        low = comparator
       }
+    })
+
+    // If the edge version comparator has a operator then our version
+    // isn't outside it
+    if (high.operator === comp || high.operator === ecomp) {
+      return false
+    }
+
+    // If the lowest version comparator has an operator and our version
+    // is less than it then it isn't higher than the range
+    if ((!low.operator || low.operator === comp) &&
+        ltefn(version, low.semver)) {
+      return false
+    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
+      return false
     }
   }
+  return true
+}
 
-  for (var i = 0; i < methods.length; i++) {
-    var method   = methods[i];
-    var original = obj[method];
+module.exports = outside
 
-    obj[method] = function retryWrapper(original) {
-      var op       = exports.operation(options);
-      var args     = Array.prototype.slice.call(arguments, 1);
-      var callback = args.pop();
 
-      args.push(function(err) {
-        if (op.retry(err)) {
-          return;
-        }
-        if (err) {
-          arguments[0] = op.mainError();
-        }
-        callback.apply(this, arguments);
-      });
+/***/ }),
 
-      op.attempt(function() {
-        original.apply(obj, args);
-      });
-    }.bind(obj, original);
-    obj[method].options = options;
+/***/ 82028:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+// given a set of versions and a range, create a "simplified" range
+// that includes the same versions that the original range does
+// If the original range is shorter than the simplified one, return that.
+const satisfies = __nccwpck_require__(68011)
+const compare = __nccwpck_require__(78469)
+module.exports = (versions, range, options) => {
+  const set = []
+  let first = null
+  let prev = null
+  const v = versions.sort((a, b) => compare(a, b, options))
+  for (const version of v) {
+    const included = satisfies(version, range, options)
+    if (included) {
+      prev = version
+      if (!first) {
+        first = version
+      }
+    } else {
+      if (prev) {
+        set.push([first, prev])
+      }
+      prev = null
+      first = null
+    }
   }
-};
+  if (first) {
+    set.push([first, null])
+  }
+
+  const ranges = []
+  for (const [min, max] of set) {
+    if (min === max) {
+      ranges.push(min)
+    } else if (!max && min === v[0]) {
+      ranges.push('*')
+    } else if (!max) {
+      ranges.push(`>=${min}`)
+    } else if (min === v[0]) {
+      ranges.push(`<=${max}`)
+    } else {
+      ranges.push(`${min} - ${max}`)
+    }
+  }
+  const simplified = ranges.join(' || ')
+  const original = typeof range.raw === 'string' ? range.raw : String(range)
+  return simplified.length < original.length ? simplified : range
+}
 
 
 /***/ }),
 
-/***/ 39538:
-/***/ ((module) => {
+/***/ 61489:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-function RetryOperation(timeouts, options) {
-  // Compatibility for the old (timeouts, retryForever) signature
-  if (typeof options === 'boolean') {
-    options = { forever: options };
+const Range = __nccwpck_require__(96782)
+const Comparator = __nccwpck_require__(89379)
+const { ANY } = Comparator
+const satisfies = __nccwpck_require__(68011)
+const compare = __nccwpck_require__(78469)
+
+// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
+// - Every simple range `r1, r2, ...` is a null set, OR
+// - Every simple range `r1, r2, ...` which is not a null set is a subset of
+//   some `R1, R2, ...`
+//
+// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
+// - If c is only the ANY comparator
+//   - If C is only the ANY comparator, return true
+//   - Else if in prerelease mode, return false
+//   - else replace c with `[>=0.0.0]`
+// - If C is only the ANY comparator
+//   - if in prerelease mode, return true
+//   - else replace C with `[>=0.0.0]`
+// - Let EQ be the set of = comparators in c
+// - If EQ is more than one, return true (null set)
+// - Let GT be the highest > or >= comparator in c
+// - Let LT be the lowest < or <= comparator in c
+// - If GT and LT, and GT.semver > LT.semver, return true (null set)
+// - If any C is a = range, and GT or LT are set, return false
+// - If EQ
+//   - If GT, and EQ does not satisfy GT, return true (null set)
+//   - If LT, and EQ does not satisfy LT, return true (null set)
+//   - If EQ satisfies every C, return true
+//   - Else return false
+// - If GT
+//   - If GT.semver is lower than any > or >= comp in C, return false
+//   - If GT is >=, and GT.semver does not satisfy every C, return false
+//   - If GT.semver has a prerelease, and not in prerelease mode
+//     - If no C has a prerelease and the GT.semver tuple, return false
+// - If LT
+//   - If LT.semver is greater than any < or <= comp in C, return false
+//   - If LT is <=, and LT.semver does not satisfy every C, return false
+//   - If GT.semver has a prerelease, and not in prerelease mode
+//     - If no C has a prerelease and the LT.semver tuple, return false
+// - Else return true
+
+const subset = (sub, dom, options = {}) => {
+  if (sub === dom) {
+    return true
   }
 
-  this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
-  this._timeouts = timeouts;
-  this._options = options || {};
-  this._maxRetryTime = options && options.maxRetryTime || Infinity;
-  this._fn = null;
-  this._errors = [];
-  this._attempts = 1;
-  this._operationTimeout = null;
-  this._operationTimeoutCb = null;
-  this._timeout = null;
-  this._operationStart = null;
+  sub = new Range(sub, options)
+  dom = new Range(dom, options)
+  let sawNonNull = false
 
-  if (this._options.forever) {
-    this._cachedTimeouts = this._timeouts.slice(0);
+  OUTER: for (const simpleSub of sub.set) {
+    for (const simpleDom of dom.set) {
+      const isSub = simpleSubset(simpleSub, simpleDom, options)
+      sawNonNull = sawNonNull || isSub !== null
+      if (isSub) {
+        continue OUTER
+      }
+    }
+    // the null set is a subset of everything, but null simple ranges in
+    // a complex range should be ignored.  so if we saw a non-null range,
+    // then we know this isn't a subset, but if EVERY simple range was null,
+    // then it is a subset.
+    if (sawNonNull) {
+      return false
+    }
   }
+  return true
 }
-module.exports = RetryOperation;
 
-RetryOperation.prototype.reset = function() {
-  this._attempts = 1;
-  this._timeouts = this._originalTimeouts;
-}
+const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
+const minimumVersion = [new Comparator('>=0.0.0')]
 
-RetryOperation.prototype.stop = function() {
-  if (this._timeout) {
-    clearTimeout(this._timeout);
+const simpleSubset = (sub, dom, options) => {
+  if (sub === dom) {
+    return true
   }
 
-  this._timeouts       = [];
-  this._cachedTimeouts = null;
-};
-
-RetryOperation.prototype.retry = function(err) {
-  if (this._timeout) {
-    clearTimeout(this._timeout);
+  if (sub.length === 1 && sub[0].semver === ANY) {
+    if (dom.length === 1 && dom[0].semver === ANY) {
+      return true
+    } else if (options.includePrerelease) {
+      sub = minimumVersionWithPreRelease
+    } else {
+      sub = minimumVersion
+    }
   }
 
-  if (!err) {
-    return false;
+  if (dom.length === 1 && dom[0].semver === ANY) {
+    if (options.includePrerelease) {
+      return true
+    } else {
+      dom = minimumVersion
+    }
   }
-  var currentTime = new Date().getTime();
-  if (err && currentTime - this._operationStart >= this._maxRetryTime) {
-    this._errors.unshift(new Error('RetryOperation timeout occurred'));
-    return false;
+
+  const eqSet = new Set()
+  let gt, lt
+  for (const c of sub) {
+    if (c.operator === '>' || c.operator === '>=') {
+      gt = higherGT(gt, c, options)
+    } else if (c.operator === '<' || c.operator === '<=') {
+      lt = lowerLT(lt, c, options)
+    } else {
+      eqSet.add(c.semver)
+    }
   }
 
-  this._errors.push(err);
+  if (eqSet.size > 1) {
+    return null
+  }
 
-  var timeout = this._timeouts.shift();
-  if (timeout === undefined) {
-    if (this._cachedTimeouts) {
-      // retry forever, only keep last error
-      this._errors.splice(this._errors.length - 1, this._errors.length);
-      this._timeouts = this._cachedTimeouts.slice(0);
-      timeout = this._timeouts.shift();
-    } else {
-      return false;
+  let gtltComp
+  if (gt && lt) {
+    gtltComp = compare(gt.semver, lt.semver, options)
+    if (gtltComp > 0) {
+      return null
+    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
+      return null
     }
   }
 
-  var self = this;
-  var timer = setTimeout(function() {
-    self._attempts++;
+  // will iterate one or zero times
+  for (const eq of eqSet) {
+    if (gt && !satisfies(eq, String(gt), options)) {
+      return null
+    }
 
-    if (self._operationTimeoutCb) {
-      self._timeout = setTimeout(function() {
-        self._operationTimeoutCb(self._attempts);
-      }, self._operationTimeout);
+    if (lt && !satisfies(eq, String(lt), options)) {
+      return null
+    }
 
-      if (self._options.unref) {
-          self._timeout.unref();
+    for (const c of dom) {
+      if (!satisfies(eq, String(c), options)) {
+        return false
       }
     }
 
-    self._fn(self._attempts);
-  }, timeout);
-
-  if (this._options.unref) {
-      timer.unref();
+    return true
   }
 
-  return true;
-};
-
-RetryOperation.prototype.attempt = function(fn, timeoutOps) {
-  this._fn = fn;
+  let higher, lower
+  let hasDomLT, hasDomGT
+  // if the subset has a prerelease, we need a comparator in the superset
+  // with the same tuple and a prerelease, or it's not a subset
+  let needDomLTPre = lt &&
+    !options.includePrerelease &&
+    lt.semver.prerelease.length ? lt.semver : false
+  let needDomGTPre = gt &&
+    !options.includePrerelease &&
+    gt.semver.prerelease.length ? gt.semver : false
+  // exception: <1.2.3-0 is the same as <1.2.3
+  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
+      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
+    needDomLTPre = false
+  }
 
-  if (timeoutOps) {
-    if (timeoutOps.timeout) {
-      this._operationTimeout = timeoutOps.timeout;
+  for (const c of dom) {
+    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
+    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
+    if (gt) {
+      if (needDomGTPre) {
+        if (c.semver.prerelease && c.semver.prerelease.length &&
+            c.semver.major === needDomGTPre.major &&
+            c.semver.minor === needDomGTPre.minor &&
+            c.semver.patch === needDomGTPre.patch) {
+          needDomGTPre = false
+        }
+      }
+      if (c.operator === '>' || c.operator === '>=') {
+        higher = higherGT(gt, c, options)
+        if (higher === c && higher !== gt) {
+          return false
+        }
+      } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
+        return false
+      }
     }
-    if (timeoutOps.cb) {
-      this._operationTimeoutCb = timeoutOps.cb;
+    if (lt) {
+      if (needDomLTPre) {
+        if (c.semver.prerelease && c.semver.prerelease.length &&
+            c.semver.major === needDomLTPre.major &&
+            c.semver.minor === needDomLTPre.minor &&
+            c.semver.patch === needDomLTPre.patch) {
+          needDomLTPre = false
+        }
+      }
+      if (c.operator === '<' || c.operator === '<=') {
+        lower = lowerLT(lt, c, options)
+        if (lower === c && lower !== lt) {
+          return false
+        }
+      } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
+        return false
+      }
+    }
+    if (!c.operator && (lt || gt) && gtltComp !== 0) {
+      return false
     }
   }
 
-  var self = this;
-  if (this._operationTimeoutCb) {
-    this._timeout = setTimeout(function() {
-      self._operationTimeoutCb();
-    }, self._operationTimeout);
+  // if there was a < or >, and nothing in the dom, then must be false
+  // UNLESS it was limited by another range in the other direction.
+  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
+  if (gt && hasDomLT && !lt && gtltComp !== 0) {
+    return false
   }
 
-  this._operationStart = new Date().getTime();
-
-  this._fn(this._attempts);
-};
-
-RetryOperation.prototype.try = function(fn) {
-  console.log('Using RetryOperation.try() is deprecated');
-  this.attempt(fn);
-};
-
-RetryOperation.prototype.start = function(fn) {
-  console.log('Using RetryOperation.start() is deprecated');
-  this.attempt(fn);
-};
-
-RetryOperation.prototype.start = RetryOperation.prototype.try;
-
-RetryOperation.prototype.errors = function() {
-  return this._errors;
-};
-
-RetryOperation.prototype.attempts = function() {
-  return this._attempts;
-};
-
-RetryOperation.prototype.mainError = function() {
-  if (this._errors.length === 0) {
-    return null;
+  if (lt && hasDomGT && !gt && gtltComp !== 0) {
+    return false
   }
 
-  var counts = {};
-  var mainError = null;
-  var mainErrorCount = 0;
+  // we needed a prerelease range in a specific tuple, but didn't get one
+  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,
+  // because it includes prereleases in the 1.2.3 tuple
+  if (needDomGTPre || needDomLTPre) {
+    return false
+  }
 
-  for (var i = 0; i < this._errors.length; i++) {
-    var error = this._errors[i];
-    var message = error.message;
-    var count = (counts[message] || 0) + 1;
+  return true
+}
 
-    counts[message] = count;
+// >=1.2.3 is lower than >1.2.3
+const higherGT = (a, b, options) => {
+  if (!a) {
+    return b
+  }
+  const comp = compare(a.semver, b.semver, options)
+  return comp > 0 ? a
+    : comp < 0 ? b
+    : b.operator === '>' && a.operator === '>=' ? b
+    : a
+}
 
-    if (count >= mainErrorCount) {
-      mainError = error;
-      mainErrorCount = count;
-    }
+// <=1.2.3 is higher than <1.2.3
+const lowerLT = (a, b, options) => {
+  if (!a) {
+    return b
   }
+  const comp = compare(a.semver, b.semver, options)
+  return comp < 0 ? a
+    : comp > 0 ? b
+    : b.operator === '<' && a.operator === '<=' ? b
+    : a
+}
 
-  return mainError;
-};
+module.exports = subset
 
 
 /***/ }),
 
-/***/ 12803:
+/***/ 54750:
 /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-"use strict";
-/* eslint-disable node/no-deprecated-api */
-
-
-
-var buffer = __nccwpck_require__(20181)
-var Buffer = buffer.Buffer
-
-var safer = {}
-
-var key
+const Range = __nccwpck_require__(96782)
 
-for (key in buffer) {
-  if (!buffer.hasOwnProperty(key)) continue
-  if (key === 'SlowBuffer' || key === 'Buffer') continue
-  safer[key] = buffer[key]
-}
+// Mostly just for testing and legacy API reasons
+const toComparators = (range, options) =>
+  new Range(range, options).set
+    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
 
-var Safer = safer.Buffer = {}
-for (key in Buffer) {
-  if (!Buffer.hasOwnProperty(key)) continue
-  if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
-  Safer[key] = Buffer[key]
-}
+module.exports = toComparators
 
-safer.Buffer.prototype = Buffer.prototype
 
-if (!Safer.from || Safer.from === Uint8Array.from) {
-  Safer.from = function (value, encodingOrOffset, length) {
-    if (typeof value === 'number') {
-      throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
-    }
-    if (value && typeof value.length === 'undefined') {
-      throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
-    }
-    return Buffer(value, encodingOrOffset, length)
-  }
-}
+/***/ }),
 
-if (!Safer.alloc) {
-  Safer.alloc = function (size, fill, encoding) {
-    if (typeof size !== 'number') {
-      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
-    }
-    if (size < 0 || size >= 2 * (1 << 30)) {
-      throw new RangeError('The value "' + size + '" is invalid for option "size"')
-    }
-    var buf = Buffer(size)
-    if (!fill || fill.length === 0) {
-      buf.fill(0)
-    } else if (typeof encoding === 'string') {
-      buf.fill(fill, encoding)
-    } else {
-      buf.fill(fill)
-    }
-    return buf
-  }
-}
+/***/ 64737:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
-if (!safer.kStringMaxLength) {
+const Range = __nccwpck_require__(96782)
+const validRange = (range, options) => {
   try {
-    safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
-  } catch (e) {
-    // we can't determine kStringMaxLength in environments where process.binding
-    // is unsupported, so let's not set it
-  }
-}
-
-if (!safer.constants) {
-  safer.constants = {
-    MAX_LENGTH: safer.kMaxLength
-  }
-  if (safer.kStringMaxLength) {
-    safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
+    // Return '*' instead of '' so that truthiness works.
+    // This will throw if it's invalid anyway
+    return new Range(range, options).range || '*'
+  } catch (er) {
+    return null
   }
 }
-
-module.exports = safer
+module.exports = validRange
 
 
 /***/ }),
@@ -47229,244 +47467,6 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
 __exportStar(__nccwpck_require__(57142), exports);
 //# sourceMappingURL=index.js.map
 
-/***/ }),
-
-/***/ 19973:
-/***/ ((__unused_webpack_module, exports) => {
-
-/* global window, exports, define */
-
-!function() {
-    'use strict'
-
-    var re = {
-        not_string: /[^s]/,
-        not_bool: /[^t]/,
-        not_type: /[^T]/,
-        not_primitive: /[^v]/,
-        number: /[diefg]/,
-        numeric_arg: /[bcdiefguxX]/,
-        json: /[j]/,
-        not_json: /[^j]/,
-        text: /^[^\x25]+/,
-        modulo: /^\x25{2}/,
-        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
-        key: /^([a-z_][a-z_\d]*)/i,
-        key_access: /^\.([a-z_][a-z_\d]*)/i,
-        index_access: /^\[(\d+)\]/,
-        sign: /^[+-]/
-    }
-
-    function sprintf(key) {
-        // `arguments` is not an array, but should be fine for this call
-        return sprintf_format(sprintf_parse(key), arguments)
-    }
-
-    function vsprintf(fmt, argv) {
-        return sprintf.apply(null, [fmt].concat(argv || []))
-    }
-
-    function sprintf_format(parse_tree, argv) {
-        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
-        for (i = 0; i < tree_length; i++) {
-            if (typeof parse_tree[i] === 'string') {
-                output += parse_tree[i]
-            }
-            else if (typeof parse_tree[i] === 'object') {
-                ph = parse_tree[i] // convenience purposes only
-                if (ph.keys) { // keyword argument
-                    arg = argv[cursor]
-                    for (k = 0; k < ph.keys.length; k++) {
-                        if (arg == undefined) {
-                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
-                        }
-                        arg = arg[ph.keys[k]]
-                    }
-                }
-                else if (ph.param_no) { // positional argument (explicit)
-                    arg = argv[ph.param_no]
-                }
-                else { // positional argument (implicit)
-                    arg = argv[cursor++]
-                }
-
-                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
-                    arg = arg()
-                }
-
-                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
-                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
-                }
-
-                if (re.number.test(ph.type)) {
-                    is_positive = arg >= 0
-                }
-
-                switch (ph.type) {
-                    case 'b':
-                        arg = parseInt(arg, 10).toString(2)
-                        break
-                    case 'c':
-                        arg = String.fromCharCode(parseInt(arg, 10))
-                        break
-                    case 'd':
-                    case 'i':
-                        arg = parseInt(arg, 10)
-                        break
-                    case 'j':
-                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
-                        break
-                    case 'e':
-                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
-                        break
-                    case 'f':
-                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
-                        break
-                    case 'g':
-                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
-                        break
-                    case 'o':
-                        arg = (parseInt(arg, 10) >>> 0).toString(8)
-                        break
-                    case 's':
-                        arg = String(arg)
-                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
-                        break
-                    case 't':
-                        arg = String(!!arg)
-                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
-                        break
-                    case 'T':
-                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
-                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
-                        break
-                    case 'u':
-                        arg = parseInt(arg, 10) >>> 0
-                        break
-                    case 'v':
-                        arg = arg.valueOf()
-                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
-                        break
-                    case 'x':
-                        arg = (parseInt(arg, 10) >>> 0).toString(16)
-                        break
-                    case 'X':
-                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
-                        break
-                }
-                if (re.json.test(ph.type)) {
-                    output += arg
-                }
-                else {
-                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
-                        sign = is_positive ? '+' : '-'
-                        arg = arg.toString().replace(re.sign, '')
-                    }
-                    else {
-                        sign = ''
-                    }
-                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
-                    pad_length = ph.width - (sign + arg).length
-                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
-                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
-                }
-            }
-        }
-        return output
-    }
-
-    var sprintf_cache = Object.create(null)
-
-    function sprintf_parse(fmt) {
-        if (sprintf_cache[fmt]) {
-            return sprintf_cache[fmt]
-        }
-
-        var _fmt = fmt, match, parse_tree = [], arg_names = 0
-        while (_fmt) {
-            if ((match = re.text.exec(_fmt)) !== null) {
-                parse_tree.push(match[0])
-            }
-            else if ((match = re.modulo.exec(_fmt)) !== null) {
-                parse_tree.push('%')
-            }
-            else if ((match = re.placeholder.exec(_fmt)) !== null) {
-                if (match[2]) {
-                    arg_names |= 1
-                    var field_list = [], replacement_field = match[2], field_match = []
-                    if ((field_match = re.key.exec(replacement_field)) !== null) {
-                        field_list.push(field_match[1])
-                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
-                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
-                                field_list.push(field_match[1])
-                            }
-                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
-                                field_list.push(field_match[1])
-                            }
-                            else {
-                                throw new SyntaxError('[sprintf] failed to parse named argument key')
-                            }
-                        }
-                    }
-                    else {
-                        throw new SyntaxError('[sprintf] failed to parse named argument key')
-                    }
-                    match[2] = field_list
-                }
-                else {
-                    arg_names |= 2
-                }
-                if (arg_names === 3) {
-                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
-                }
-
-                parse_tree.push(
-                    {
-                        placeholder: match[0],
-                        param_no:    match[1],
-                        keys:        match[2],
-                        sign:        match[3],
-                        pad_char:    match[4],
-                        align:       match[5],
-                        width:       match[6],
-                        precision:   match[7],
-                        type:        match[8]
-                    }
-                )
-            }
-            else {
-                throw new SyntaxError('[sprintf] unexpected placeholder')
-            }
-            _fmt = _fmt.substring(match[0].length)
-        }
-        return sprintf_cache[fmt] = parse_tree
-    }
-
-    /**
-     * export to either browser or node.js
-     */
-    /* eslint-disable quote-props */
-    if (true) {
-        exports.sprintf = sprintf
-        exports.vsprintf = vsprintf
-    }
-    if (typeof window !== 'undefined') {
-        window['sprintf'] = sprintf
-        window['vsprintf'] = vsprintf
-
-        if (typeof define === 'function' && define['amd']) {
-            define(function() {
-                return {
-                    'sprintf': sprintf,
-                    'vsprintf': vsprintf
-                }
-            })
-        }
-    }
-    /* eslint-enable quote-props */
-}(); // eslint-disable-line
-
-
 /***/ }),
 
 /***/ 68951:
@@ -70768,10 +70768,7 @@ const createAttestation = async (subjects, predicate, opts) => {
         sigstore: opts.sigstoreInstance,
         token: opts.githubToken
     });
-    const result = {
-        ...attestation,
-        attestationSubjects: subjects
-    };
+    const result = attestation;
     if (subjects.length === 1 && opts.pushToRegistry) {
         const subject = subjects[0];
         const credentials = (0, oci_1.getRegistryCredentials)(subject.name);
@@ -70864,7 +70861,6 @@ const inputs = {
     pushToRegistry: core.getBooleanInput('push-to-registry'),
     showSummary: core.getBooleanInput('show-summary'),
     githubToken: core.getInput('github-token'),
-    singleSubjectAttestations: core.getBooleanInput('single-subject-attestations'),
     // undocumented -- not part of public interface
     privateSigning: ['true', 'True', 'TRUE', '1'].includes(core.getInput('private-signing'))
 };
@@ -70959,28 +70955,23 @@ async function run(inputs) {
         const predicate = (0, predicate_1.predicateFromInputs)(inputs);
         const outputPath = path_1.default.join(tempDir(), ATTESTATION_FILE_NAME);
         core.setOutput('bundle-path', outputPath);
-        const opts = {
+        const att = await (0, attest_1.createAttestation)(subjects, predicate, {
             sigstoreInstance,
             pushToRegistry: inputs.pushToRegistry,
             githubToken: inputs.githubToken
-        };
-        let atts;
-        if (inputs.singleSubjectAttestations) {
-            atts = await createSingleSubjectAttestations(subjects, predicate, opts);
-        }
-        else {
-            atts = await createMultiSubjectAttestation(subjects, predicate, opts);
-        }
-        for (const att of atts) {
-            logAttestation(att, sigstoreInstance);
-            // Write attestation bundle to output file
-            fs_1.default.writeFileSync(outputPath, JSON.stringify(att.bundle) + os_1.default.EOL, {
-                encoding: 'utf-8',
-                flag: 'a'
-            });
+        });
+        logAttestation(subjects, att, sigstoreInstance);
+        // Write attestation bundle to output file
+        fs_1.default.writeFileSync(outputPath, JSON.stringify(att.bundle) + os_1.default.EOL, {
+            encoding: 'utf-8',
+            flag: 'a'
+        });
+        if (att.attestationID) {
+            core.setOutput('attestation-id', att.attestationID);
+            core.setOutput('attestation-url', attestationURL(att.attestationID));
         }
         if (inputs.showSummary) {
-            await logSummary(atts);
+            await logSummary(att);
         }
     }
     catch (err) {
@@ -70997,26 +70988,8 @@ async function run(inputs) {
         process.removeListener('log', logHandler);
     }
 }
-const createSingleSubjectAttestations = async (subjects, predicate, opts) => {
-    const atts = [];
-    // Generate one attestation for each subject
-    for (const subject of subjects) {
-        const att = await (0, attest_1.createAttestation)([subject], predicate, opts);
-        atts.push(att);
-    }
-    return atts;
-};
-const createMultiSubjectAttestation = async (subjects, predicate, opts) => {
-    const att = await (0, attest_1.createAttestation)(subjects, predicate, opts);
-    if (att.attestationID) {
-        core.setOutput('attestation-id', att.attestationID);
-        core.setOutput('attestation-url', attestationURL(att.attestationID));
-    }
-    return [att];
-};
 // Log details about the attestation to the GitHub Actions run
-const logAttestation = (attestation, sigstoreInstance) => {
-    const subjects = attestation.attestationSubjects;
+const logAttestation = (subjects, attestation, sigstoreInstance) => {
     if (subjects.length === 1) {
         core.info(`Attestation created for ${subjects[0].name}@${(0, subject_1.formatSubjectDigest)(subjects[0])}`);
     }
@@ -71041,24 +71014,12 @@ const logAttestation = (attestation, sigstoreInstance) => {
     }
 };
 // Attach summary information to the GitHub Actions run
-const logSummary = async (attestations) => {
-    if (attestations.length > 0) {
-        core.summary.addHeading(
-        /* istanbul ignore next */
-        attestations.length !== 1
-            ? 'Attestations Created'
-            : 'Attestation Created', 3);
-        const listItems = [];
-        for (const attestation of attestations) {
-            if (attestation.attestationID) {
-                const url = attestationURL(attestation.attestationID);
-                for (const subject of attestation.attestationSubjects) {
-                    const digest = (0, subject_1.formatSubjectDigest)(subject);
-                    listItems.push(`${subject.name}@${digest}`);
-                }
-            }
-        }
-        core.summary.addList(listItems);
+const logSummary = async (attestation) => {
+    const { attestationID } = attestation;
+    if (attestationID) {
+        const url = attestationURL(attestationID);
+        core.summary.addHeading('Attestation Created', 3);
+        core.summary.addList([`${url}`]);
         await core.summary.write();
     }
 };
@@ -73095,3523 +73056,3213 @@ const decoders = {
   }
 }
 
-function decodeText (text, sourceEncoding, destEncoding) {
-  if (text) {
-    return getDecoder(destEncoding)(text, sourceEncoding)
-  }
-  return text
-}
-
-module.exports = decodeText
-
-
-/***/ }),
-
-/***/ 22393:
-/***/ ((module) => {
-
-"use strict";
-
-
-module.exports = function getLimit (limits, name, defaultLimit) {
-  if (
-    !limits ||
-    limits[name] === undefined ||
-    limits[name] === null
-  ) { return defaultLimit }
-
-  if (
-    typeof limits[name] !== 'number' ||
-    isNaN(limits[name])
-  ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
-
-  return limits[name]
-}
-
-
-/***/ }),
-
-/***/ 8929:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-"use strict";
-/* eslint-disable object-property-newline */
-
-
-const decodeText = __nccwpck_require__(72747)
-
-const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
-
-const EncodedLookup = {
-  '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
-  '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
-  '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
-  '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
-  '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
-  '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
-  '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
-  '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
-  '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
-  '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
-  '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
-  '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
-  '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
-  '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
-  '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
-  '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
-  '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
-  '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
-  '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
-  '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
-  '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
-  '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
-  '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
-  '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
-  '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
-  '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
-  '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
-  '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
-  '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
-  '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
-  '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
-  '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
-  '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
-  '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
-  '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
-  '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
-  '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
-  '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
-  '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
-  '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
-  '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
-  '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
-  '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
-  '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
-  '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
-  '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
-  '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
-  '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
-  '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
-  '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
-  '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
-  '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
-  '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
-  '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
-  '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
-  '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
-  '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
-  '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
-  '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
-  '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
-  '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
-  '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
-  '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
-  '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
-  '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
-  '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
-  '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
-  '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
-  '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
-  '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
-  '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
-  '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
-  '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
-  '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
-  '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
-  '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
-  '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
-  '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
-  '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
-  '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
-  '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
-  '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
-  '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
-  '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
-  '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
-  '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
-  '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
-  '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
-  '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
-  '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
-  '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
-  '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
-  '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
-  '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
-  '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
-  '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
-  '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
-}
-
-function encodedReplacer (match) {
-  return EncodedLookup[match]
-}
-
-const STATE_KEY = 0
-const STATE_VALUE = 1
-const STATE_CHARSET = 2
-const STATE_LANG = 3
-
-function parseParams (str) {
-  const res = []
-  let state = STATE_KEY
-  let charset = ''
-  let inquote = false
-  let escaping = false
-  let p = 0
-  let tmp = ''
-  const len = str.length
-
-  for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
-    const char = str[i]
-    if (char === '\\' && inquote) {
-      if (escaping) { escaping = false } else {
-        escaping = true
-        continue
-      }
-    } else if (char === '"') {
-      if (!escaping) {
-        if (inquote) {
-          inquote = false
-          state = STATE_KEY
-        } else { inquote = true }
-        continue
-      } else { escaping = false }
-    } else {
-      if (escaping && inquote) { tmp += '\\' }
-      escaping = false
-      if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
-        if (state === STATE_CHARSET) {
-          state = STATE_LANG
-          charset = tmp.substring(1)
-        } else { state = STATE_VALUE }
-        tmp = ''
-        continue
-      } else if (state === STATE_KEY &&
-        (char === '*' || char === '=') &&
-        res.length) {
-        state = char === '*'
-          ? STATE_CHARSET
-          : STATE_VALUE
-        res[p] = [tmp, undefined]
-        tmp = ''
-        continue
-      } else if (!inquote && char === ';') {
-        state = STATE_KEY
-        if (charset) {
-          if (tmp.length) {
-            tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
-              'binary',
-              charset)
-          }
-          charset = ''
-        } else if (tmp.length) {
-          tmp = decodeText(tmp, 'binary', 'utf8')
-        }
-        if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
-        tmp = ''
-        ++p
-        continue
-      } else if (!inquote && (char === ' ' || char === '\t')) { continue }
-    }
-    tmp += char
-  }
-  if (charset && tmp.length) {
-    tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
-      'binary',
-      charset)
-  } else if (tmp) {
-    tmp = decodeText(tmp, 'binary', 'utf8')
-  }
-
-  if (res[p] === undefined) {
-    if (tmp) { res[p] = tmp }
-  } else { res[p][1] = tmp }
-
-  return res
-}
-
-module.exports = parseParams
-
-
-/***/ }),
-
-/***/ 81017:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Glob = void 0;
-const minimatch_1 = __nccwpck_require__(45613);
-const node_url_1 = __nccwpck_require__(73136);
-const path_scurry_1 = __nccwpck_require__(16577);
-const pattern_js_1 = __nccwpck_require__(4041);
-const walker_js_1 = __nccwpck_require__(95049);
-// if no process global, just call it linux.
-// so we default to case-sensitive, / separators
-const defaultPlatform = (typeof process === 'object' &&
-    process &&
-    typeof process.platform === 'string') ?
-    process.platform
-    : 'linux';
-/**
- * An object that can perform glob pattern traversals.
- */
-class Glob {
-    absolute;
-    cwd;
-    root;
-    dot;
-    dotRelative;
-    follow;
-    ignore;
-    magicalBraces;
-    mark;
-    matchBase;
-    maxDepth;
-    nobrace;
-    nocase;
-    nodir;
-    noext;
-    noglobstar;
-    pattern;
-    platform;
-    realpath;
-    scurry;
-    stat;
-    signal;
-    windowsPathsNoEscape;
-    withFileTypes;
-    includeChildMatches;
-    /**
-     * The options provided to the constructor.
-     */
-    opts;
-    /**
-     * An array of parsed immutable {@link Pattern} objects.
-     */
-    patterns;
-    /**
-     * All options are stored as properties on the `Glob` object.
-     *
-     * See {@link GlobOptions} for full options descriptions.
-     *
-     * Note that a previous `Glob` object can be passed as the
-     * `GlobOptions` to another `Glob` instantiation to re-use settings
-     * and caches with a new pattern.
-     *
-     * Traversal functions can be called multiple times to run the walk
-     * again.
-     */
-    constructor(pattern, opts) {
-        /* c8 ignore start */
-        if (!opts)
-            throw new TypeError('glob options required');
-        /* c8 ignore stop */
-        this.withFileTypes = !!opts.withFileTypes;
-        this.signal = opts.signal;
-        this.follow = !!opts.follow;
-        this.dot = !!opts.dot;
-        this.dotRelative = !!opts.dotRelative;
-        this.nodir = !!opts.nodir;
-        this.mark = !!opts.mark;
-        if (!opts.cwd) {
-            this.cwd = '';
-        }
-        else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
-            opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd);
-        }
-        this.cwd = opts.cwd || '';
-        this.root = opts.root;
-        this.magicalBraces = !!opts.magicalBraces;
-        this.nobrace = !!opts.nobrace;
-        this.noext = !!opts.noext;
-        this.realpath = !!opts.realpath;
-        this.absolute = opts.absolute;
-        this.includeChildMatches = opts.includeChildMatches !== false;
-        this.noglobstar = !!opts.noglobstar;
-        this.matchBase = !!opts.matchBase;
-        this.maxDepth =
-            typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity;
-        this.stat = !!opts.stat;
-        this.ignore = opts.ignore;
-        if (this.withFileTypes && this.absolute !== undefined) {
-            throw new Error('cannot set absolute and withFileTypes:true');
-        }
-        if (typeof pattern === 'string') {
-            pattern = [pattern];
-        }
-        this.windowsPathsNoEscape =
-            !!opts.windowsPathsNoEscape ||
-                opts.allowWindowsEscape ===
-                    false;
-        if (this.windowsPathsNoEscape) {
-            pattern = pattern.map(p => p.replace(/\\/g, '/'));
-        }
-        if (this.matchBase) {
-            if (opts.noglobstar) {
-                throw new TypeError('base matching requires globstar');
-            }
-            pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
-        }
-        this.pattern = pattern;
-        this.platform = opts.platform || defaultPlatform;
-        this.opts = { ...opts, platform: this.platform };
-        if (opts.scurry) {
-            this.scurry = opts.scurry;
-            if (opts.nocase !== undefined &&
-                opts.nocase !== opts.scurry.nocase) {
-                throw new Error('nocase option contradicts provided scurry option');
-            }
-        }
-        else {
-            const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32
-                : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin
-                    : opts.platform ? path_scurry_1.PathScurryPosix
-                        : path_scurry_1.PathScurry;
-            this.scurry = new Scurry(this.cwd, {
-                nocase: opts.nocase,
-                fs: opts.fs,
-            });
-        }
-        this.nocase = this.scurry.nocase;
-        // If you do nocase:true on a case-sensitive file system, then
-        // we need to use regexps instead of strings for non-magic
-        // path portions, because statting `aBc` won't return results
-        // for the file `AbC` for example.
-        const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32';
-        const mmo = {
-            // default nocase based on platform
-            ...opts,
-            dot: this.dot,
-            matchBase: this.matchBase,
-            nobrace: this.nobrace,
-            nocase: this.nocase,
-            nocaseMagicOnly,
-            nocomment: true,
-            noext: this.noext,
-            nonegate: true,
-            optimizationLevel: 2,
-            platform: this.platform,
-            windowsPathsNoEscape: this.windowsPathsNoEscape,
-            debug: !!this.opts.debug,
-        };
-        const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo));
-        const [matchSet, globParts] = mms.reduce((set, m) => {
-            set[0].push(...m.set);
-            set[1].push(...m.globParts);
-            return set;
-        }, [[], []]);
-        this.patterns = matchSet.map((set, i) => {
-            const g = globParts[i];
-            /* c8 ignore start */
-            if (!g)
-                throw new Error('invalid pattern object');
-            /* c8 ignore stop */
-            return new pattern_js_1.Pattern(set, g, 0, this.platform);
-        });
-    }
-    async walk() {
-        // Walkers always return array of Path objects, so we just have to
-        // coerce them into the right shape.  It will have already called
-        // realpath() if the option was set to do so, so we know that's cached.
-        // start out knowing the cwd, at least
-        return [
-            ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
-                ...this.opts,
-                maxDepth: this.maxDepth !== Infinity ?
-                    this.maxDepth + this.scurry.cwd.depth()
-                    : Infinity,
-                platform: this.platform,
-                nocase: this.nocase,
-                includeChildMatches: this.includeChildMatches,
-            }).walk()),
-        ];
-    }
-    walkSync() {
-        return [
-            ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
-                ...this.opts,
-                maxDepth: this.maxDepth !== Infinity ?
-                    this.maxDepth + this.scurry.cwd.depth()
-                    : Infinity,
-                platform: this.platform,
-                nocase: this.nocase,
-                includeChildMatches: this.includeChildMatches,
-            }).walkSync(),
-        ];
-    }
-    stream() {
-        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
-            ...this.opts,
-            maxDepth: this.maxDepth !== Infinity ?
-                this.maxDepth + this.scurry.cwd.depth()
-                : Infinity,
-            platform: this.platform,
-            nocase: this.nocase,
-            includeChildMatches: this.includeChildMatches,
-        }).stream();
-    }
-    streamSync() {
-        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
-            ...this.opts,
-            maxDepth: this.maxDepth !== Infinity ?
-                this.maxDepth + this.scurry.cwd.depth()
-                : Infinity,
-            platform: this.platform,
-            nocase: this.nocase,
-            includeChildMatches: this.includeChildMatches,
-        }).streamSync();
-    }
-    /**
-     * Default sync iteration function. Returns a Generator that
-     * iterates over the results.
-     */
-    iterateSync() {
-        return this.streamSync()[Symbol.iterator]();
-    }
-    [Symbol.iterator]() {
-        return this.iterateSync();
-    }
-    /**
-     * Default async iteration function. Returns an AsyncGenerator that
-     * iterates over the results.
-     */
-    iterate() {
-        return this.stream()[Symbol.asyncIterator]();
-    }
-    [Symbol.asyncIterator]() {
-        return this.iterate();
-    }
+function decodeText (text, sourceEncoding, destEncoding) {
+  if (text) {
+    return getDecoder(destEncoding)(text, sourceEncoding)
+  }
+  return text
 }
-exports.Glob = Glob;
-//# sourceMappingURL=glob.js.map
+
+module.exports = decodeText
+
 
 /***/ }),
 
-/***/ 66889:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 22393:
+/***/ ((module) => {
 
 "use strict";
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.hasMagic = void 0;
-const minimatch_1 = __nccwpck_require__(45613);
-/**
- * Return true if the patterns provided contain any magic glob characters,
- * given the options provided.
- *
- * Brace expansion is not considered "magic" unless the `magicalBraces` option
- * is set, as brace expansion just turns one string into an array of strings.
- * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
- * `'xby'` both do not contain any magic glob characters, and it's treated the
- * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
- * is in the options, brace expansion _is_ treated as a pattern having magic.
- */
-const hasMagic = (pattern, options = {}) => {
-    if (!Array.isArray(pattern)) {
-        pattern = [pattern];
-    }
-    for (const p of pattern) {
-        if (new minimatch_1.Minimatch(p, options).hasMagic())
-            return true;
-    }
-    return false;
-};
-exports.hasMagic = hasMagic;
-//# sourceMappingURL=has-magic.js.map
-
-/***/ }),
 
-/***/ 4833:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+module.exports = function getLimit (limits, name, defaultLimit) {
+  if (
+    !limits ||
+    limits[name] === undefined ||
+    limits[name] === null
+  ) { return defaultLimit }
 
-"use strict";
+  if (
+    typeof limits[name] !== 'number' ||
+    isNaN(limits[name])
+  ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
 
-// give it a pattern, and it'll be able to tell you if
-// a given path should be ignored.
-// Ignoring a path ignores its children if the pattern ends in /**
-// Ignores are always parsed in dot:true mode
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Ignore = void 0;
-const minimatch_1 = __nccwpck_require__(45613);
-const pattern_js_1 = __nccwpck_require__(4041);
-const defaultPlatform = (typeof process === 'object' &&
-    process &&
-    typeof process.platform === 'string') ?
-    process.platform
-    : 'linux';
-/**
- * Class used to process ignored patterns
- */
-class Ignore {
-    relative;
-    relativeChildren;
-    absolute;
-    absoluteChildren;
-    platform;
-    mmopts;
-    constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) {
-        this.relative = [];
-        this.absolute = [];
-        this.relativeChildren = [];
-        this.absoluteChildren = [];
-        this.platform = platform;
-        this.mmopts = {
-            dot: true,
-            nobrace,
-            nocase,
-            noext,
-            noglobstar,
-            optimizationLevel: 2,
-            platform,
-            nocomment: true,
-            nonegate: true,
-        };
-        for (const ign of ignored)
-            this.add(ign);
-    }
-    add(ign) {
-        // this is a little weird, but it gives us a clean set of optimized
-        // minimatch matchers, without getting tripped up if one of them
-        // ends in /** inside a brace section, and it's only inefficient at
-        // the start of the walk, not along it.
-        // It'd be nice if the Pattern class just had a .test() method, but
-        // handling globstars is a bit of a pita, and that code already lives
-        // in minimatch anyway.
-        // Another way would be if maybe Minimatch could take its set/globParts
-        // as an option, and then we could at least just use Pattern to test
-        // for absolute-ness.
-        // Yet another way, Minimatch could take an array of glob strings, and
-        // a cwd option, and do the right thing.
-        const mm = new minimatch_1.Minimatch(ign, this.mmopts);
-        for (let i = 0; i < mm.set.length; i++) {
-            const parsed = mm.set[i];
-            const globParts = mm.globParts[i];
-            /* c8 ignore start */
-            if (!parsed || !globParts) {
-                throw new Error('invalid pattern object');
-            }
-            // strip off leading ./ portions
-            // https://github.com/isaacs/node-glob/issues/570
-            while (parsed[0] === '.' && globParts[0] === '.') {
-                parsed.shift();
-                globParts.shift();
-            }
-            /* c8 ignore stop */
-            const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform);
-            const m = new minimatch_1.Minimatch(p.globString(), this.mmopts);
-            const children = globParts[globParts.length - 1] === '**';
-            const absolute = p.isAbsolute();
-            if (absolute)
-                this.absolute.push(m);
-            else
-                this.relative.push(m);
-            if (children) {
-                if (absolute)
-                    this.absoluteChildren.push(m);
-                else
-                    this.relativeChildren.push(m);
-            }
-        }
-    }
-    ignored(p) {
-        const fullpath = p.fullpath();
-        const fullpaths = `${fullpath}/`;
-        const relative = p.relative() || '.';
-        const relatives = `${relative}/`;
-        for (const m of this.relative) {
-            if (m.match(relative) || m.match(relatives))
-                return true;
-        }
-        for (const m of this.absolute) {
-            if (m.match(fullpath) || m.match(fullpaths))
-                return true;
-        }
-        return false;
-    }
-    childrenIgnored(p) {
-        const fullpath = p.fullpath() + '/';
-        const relative = (p.relative() || '.') + '/';
-        for (const m of this.relativeChildren) {
-            if (m.match(relative))
-                return true;
-        }
-        for (const m of this.absoluteChildren) {
-            if (m.match(fullpath))
-                return true;
-        }
-        return false;
-    }
+  return limits[name]
 }
-exports.Ignore = Ignore;
-//# sourceMappingURL=ignore.js.map
+
 
 /***/ }),
 
-/***/ 67471:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 8929:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
 
 "use strict";
+/* eslint-disable object-property-newline */
 
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0;
-exports.globStreamSync = globStreamSync;
-exports.globStream = globStream;
-exports.globSync = globSync;
-exports.globIterateSync = globIterateSync;
-exports.globIterate = globIterate;
-const minimatch_1 = __nccwpck_require__(45613);
-const glob_js_1 = __nccwpck_require__(81017);
-const has_magic_js_1 = __nccwpck_require__(66889);
-var minimatch_2 = __nccwpck_require__(45613);
-Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return minimatch_2.escape; } }));
-Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return minimatch_2.unescape; } }));
-var glob_js_2 = __nccwpck_require__(81017);
-Object.defineProperty(exports, "Glob", ({ enumerable: true, get: function () { return glob_js_2.Glob; } }));
-var has_magic_js_2 = __nccwpck_require__(66889);
-Object.defineProperty(exports, "hasMagic", ({ enumerable: true, get: function () { return has_magic_js_2.hasMagic; } }));
-var ignore_js_1 = __nccwpck_require__(4833);
-Object.defineProperty(exports, "Ignore", ({ enumerable: true, get: function () { return ignore_js_1.Ignore; } }));
-function globStreamSync(pattern, options = {}) {
-    return new glob_js_1.Glob(pattern, options).streamSync();
-}
-function globStream(pattern, options = {}) {
-    return new glob_js_1.Glob(pattern, options).stream();
-}
-function globSync(pattern, options = {}) {
-    return new glob_js_1.Glob(pattern, options).walkSync();
-}
-async function glob_(pattern, options = {}) {
-    return new glob_js_1.Glob(pattern, options).walk();
+
+const decodeText = __nccwpck_require__(72747)
+
+const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
+
+const EncodedLookup = {
+  '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
+  '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
+  '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
+  '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
+  '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
+  '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
+  '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
+  '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
+  '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
+  '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
+  '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
+  '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
+  '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
+  '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
+  '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
+  '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
+  '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
+  '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
+  '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
+  '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
+  '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
+  '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
+  '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
+  '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
+  '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
+  '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
+  '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
+  '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
+  '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
+  '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
+  '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
+  '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
+  '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
+  '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
+  '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
+  '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
+  '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
+  '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
+  '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
+  '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
+  '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
+  '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
+  '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
+  '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
+  '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
+  '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
+  '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
+  '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
+  '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
+  '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
+  '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
+  '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
+  '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
+  '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
+  '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
+  '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
+  '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
+  '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
+  '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
+  '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
+  '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
+  '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
+  '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
+  '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
+  '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
+  '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
+  '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
+  '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
+  '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
+  '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
+  '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
+  '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
+  '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
+  '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
+  '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
+  '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
+  '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
+  '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
+  '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
+  '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
+  '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
+  '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
+  '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
+  '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
+  '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
+  '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
+  '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
+  '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
+  '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
+  '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
+  '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
+  '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
+  '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
+  '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
+  '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
+  '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
+  '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
 }
-function globIterateSync(pattern, options = {}) {
-    return new glob_js_1.Glob(pattern, options).iterateSync();
+
+function encodedReplacer (match) {
+  return EncodedLookup[match]
 }
-function globIterate(pattern, options = {}) {
-    return new glob_js_1.Glob(pattern, options).iterate();
+
+const STATE_KEY = 0
+const STATE_VALUE = 1
+const STATE_CHARSET = 2
+const STATE_LANG = 3
+
+function parseParams (str) {
+  const res = []
+  let state = STATE_KEY
+  let charset = ''
+  let inquote = false
+  let escaping = false
+  let p = 0
+  let tmp = ''
+  const len = str.length
+
+  for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+    const char = str[i]
+    if (char === '\\' && inquote) {
+      if (escaping) { escaping = false } else {
+        escaping = true
+        continue
+      }
+    } else if (char === '"') {
+      if (!escaping) {
+        if (inquote) {
+          inquote = false
+          state = STATE_KEY
+        } else { inquote = true }
+        continue
+      } else { escaping = false }
+    } else {
+      if (escaping && inquote) { tmp += '\\' }
+      escaping = false
+      if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
+        if (state === STATE_CHARSET) {
+          state = STATE_LANG
+          charset = tmp.substring(1)
+        } else { state = STATE_VALUE }
+        tmp = ''
+        continue
+      } else if (state === STATE_KEY &&
+        (char === '*' || char === '=') &&
+        res.length) {
+        state = char === '*'
+          ? STATE_CHARSET
+          : STATE_VALUE
+        res[p] = [tmp, undefined]
+        tmp = ''
+        continue
+      } else if (!inquote && char === ';') {
+        state = STATE_KEY
+        if (charset) {
+          if (tmp.length) {
+            tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+              'binary',
+              charset)
+          }
+          charset = ''
+        } else if (tmp.length) {
+          tmp = decodeText(tmp, 'binary', 'utf8')
+        }
+        if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
+        tmp = ''
+        ++p
+        continue
+      } else if (!inquote && (char === ' ' || char === '\t')) { continue }
+    }
+    tmp += char
+  }
+  if (charset && tmp.length) {
+    tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+      'binary',
+      charset)
+  } else if (tmp) {
+    tmp = decodeText(tmp, 'binary', 'utf8')
+  }
+
+  if (res[p] === undefined) {
+    if (tmp) { res[p] = tmp }
+  } else { res[p][1] = tmp }
+
+  return res
 }
-// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
-exports.streamSync = globStreamSync;
-exports.stream = Object.assign(globStream, { sync: globStreamSync });
-exports.iterateSync = globIterateSync;
-exports.iterate = Object.assign(globIterate, {
-    sync: globIterateSync,
-});
-exports.sync = Object.assign(globSync, {
-    stream: globStreamSync,
-    iterate: globIterateSync,
-});
-exports.glob = Object.assign(glob_, {
-    glob: glob_,
-    globSync,
-    sync: exports.sync,
-    globStream,
-    stream: exports.stream,
-    globStreamSync,
-    streamSync: exports.streamSync,
-    globIterate,
-    iterate: exports.iterate,
-    globIterateSync,
-    iterateSync: exports.iterateSync,
-    Glob: glob_js_1.Glob,
-    hasMagic: has_magic_js_1.hasMagic,
-    escape: minimatch_1.escape,
-    unescape: minimatch_1.unescape,
-});
-exports.glob.glob = exports.glob;
-//# sourceMappingURL=index.js.map
+
+module.exports = parseParams
+
 
 /***/ }),
 
-/***/ 4041:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 32638:
+/***/ ((__unused_webpack_module, exports) => {
 
 "use strict";
-
-// this is just a very light wrapper around 2 arrays with an offset index
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Pattern = void 0;
-const minimatch_1 = __nccwpck_require__(45613);
-const isPatternList = (pl) => pl.length >= 1;
-const isGlobList = (gl) => gl.length >= 1;
-/**
- * An immutable-ish view on an array of glob parts and their parsed
- * results
- */
-class Pattern {
-    #patternList;
-    #globList;
-    #index;
-    length;
-    #platform;
-    #rest;
-    #globString;
-    #isDrive;
-    #isUNC;
-    #isAbsolute;
-    #followGlobstar = true;
-    constructor(patternList, globList, index, platform) {
-        if (!isPatternList(patternList)) {
-            throw new TypeError('empty pattern list');
-        }
-        if (!isGlobList(globList)) {
-            throw new TypeError('empty glob list');
-        }
-        if (globList.length !== patternList.length) {
-            throw new TypeError('mismatched pattern list and glob list lengths');
-        }
-        this.length = patternList.length;
-        if (index < 0 || index >= this.length) {
-            throw new TypeError('index out of range');
-        }
-        this.#patternList = patternList;
-        this.#globList = globList;
-        this.#index = index;
-        this.#platform = platform;
-        // normalize root entries of absolute patterns on initial creation.
-        if (this.#index === 0) {
-            // c: => ['c:/']
-            // C:/ => ['C:/']
-            // C:/x => ['C:/', 'x']
-            // //host/share => ['//host/share/']
-            // //host/share/ => ['//host/share/']
-            // //host/share/x => ['//host/share/', 'x']
-            // /etc => ['/', 'etc']
-            // / => ['/']
-            if (this.isUNC()) {
-                // '' / '' / 'host' / 'share'
-                const [p0, p1, p2, p3, ...prest] = this.#patternList;
-                const [g0, g1, g2, g3, ...grest] = this.#globList;
-                if (prest[0] === '') {
-                    // ends in /
-                    prest.shift();
-                    grest.shift();
-                }
-                const p = [p0, p1, p2, p3, ''].join('/');
-                const g = [g0, g1, g2, g3, ''].join('/');
-                this.#patternList = [p, ...prest];
-                this.#globList = [g, ...grest];
-                this.length = this.#patternList.length;
-            }
-            else if (this.isDrive() || this.isAbsolute()) {
-                const [p1, ...prest] = this.#patternList;
-                const [g1, ...grest] = this.#globList;
-                if (prest[0] === '') {
-                    // ends in /
-                    prest.shift();
-                    grest.shift();
-                }
-                const p = p1 + '/';
-                const g = g1 + '/';
-                this.#patternList = [p, ...prest];
-                this.#globList = [g, ...grest];
-                this.length = this.#patternList.length;
+
+/**
+ * @module LRUCache
+ */
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LRUCache = void 0;
+const perf = typeof performance === 'object' &&
+    performance &&
+    typeof performance.now === 'function'
+    ? performance
+    : Date;
+const warned = new Set();
+/* c8 ignore start */
+const PROCESS = (typeof process === 'object' && !!process ? process : {});
+/* c8 ignore start */
+const emitWarning = (msg, type, code, fn) => {
+    typeof PROCESS.emitWarning === 'function'
+        ? PROCESS.emitWarning(msg, type, code, fn)
+        : console.error(`[${code}] ${type}: ${msg}`);
+};
+let AC = globalThis.AbortController;
+let AS = globalThis.AbortSignal;
+/* c8 ignore start */
+if (typeof AC === 'undefined') {
+    //@ts-ignore
+    AS = class AbortSignal {
+        onabort;
+        _onabort = [];
+        reason;
+        aborted = false;
+        addEventListener(_, fn) {
+            this._onabort.push(fn);
+        }
+    };
+    //@ts-ignore
+    AC = class AbortController {
+        constructor() {
+            warnACPolyfill();
+        }
+        signal = new AS();
+        abort(reason) {
+            if (this.signal.aborted)
+                return;
+            //@ts-ignore
+            this.signal.reason = reason;
+            //@ts-ignore
+            this.signal.aborted = true;
+            //@ts-ignore
+            for (const fn of this.signal._onabort) {
+                fn(reason);
             }
+            this.signal.onabort?.(reason);
+        }
+    };
+    let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
+    const warnACPolyfill = () => {
+        if (!printACPolyfillWarning)
+            return;
+        printACPolyfillWarning = false;
+        emitWarning('AbortController is not defined. If using lru-cache in ' +
+            'node 14, load an AbortController polyfill from the ' +
+            '`node-abort-controller` package. A minimal polyfill is ' +
+            'provided for use by LRUCache.fetch(), but it should not be ' +
+            'relied upon in other contexts (eg, passing it to other APIs that ' +
+            'use AbortController/AbortSignal might have undesirable effects). ' +
+            'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
+    };
+}
+/* c8 ignore stop */
+const shouldWarn = (code) => !warned.has(code);
+const TYPE = Symbol('type');
+const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
+/* c8 ignore start */
+// This is a little bit ridiculous, tbh.
+// The maximum array length is 2^32-1 or thereabouts on most JS impls.
+// And well before that point, you're caching the entire world, I mean,
+// that's ~32GB of just integers for the next/prev links, plus whatever
+// else to hold that many keys and values.  Just filling the memory with
+// zeroes at init time is brutal when you get that big.
+// But why not be complete?
+// Maybe in the future, these limits will have expanded.
+const getUintArray = (max) => !isPosInt(max)
+    ? null
+    : 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;
+/* c8 ignore stop */
+class ZeroArray extends Array {
+    constructor(size) {
+        super(size);
+        this.fill(0);
+    }
+}
+class Stack {
+    heap;
+    length;
+    // private constructor
+    static #constructing = false;
+    static create(max) {
+        const HeapCls = getUintArray(max);
+        if (!HeapCls)
+            return [];
+        Stack.#constructing = true;
+        const s = new Stack(max, HeapCls);
+        Stack.#constructing = false;
+        return s;
+    }
+    constructor(max, HeapCls) {
+        /* c8 ignore start */
+        if (!Stack.#constructing) {
+            throw new TypeError('instantiate Stack using Stack.create(n)');
         }
+        /* c8 ignore stop */
+        this.heap = new HeapCls(max);
+        this.length = 0;
+    }
+    push(n) {
+        this.heap[this.length++] = n;
+    }
+    pop() {
+        return this.heap[--this.length];
     }
+}
+/**
+ * Default export, the thing you're using this module to get.
+ *
+ * The `K` and `V` types define the key and value types, respectively. The
+ * optional `FC` type defines the type of the `context` object passed to
+ * `cache.fetch()` and `cache.memo()`.
+ *
+ * Keys and values **must not** be `null` or `undefined`.
+ *
+ * All properties from the options object (with the exception of `max`,
+ * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
+ * added as normal public members. (The listed options are read-only getters.)
+ *
+ * Changing any of these will alter the defaults for subsequent method calls.
+ */
+class LRUCache {
+    // options that cannot be changed without disaster
+    #max;
+    #maxSize;
+    #dispose;
+    #disposeAfter;
+    #fetchMethod;
+    #memoMethod;
     /**
-     * The first entry in the parsed list of patterns
+     * {@link LRUCache.OptionsBase.ttl}
      */
-    pattern() {
-        return this.#patternList[this.#index];
-    }
+    ttl;
     /**
-     * true of if pattern() returns a string
+     * {@link LRUCache.OptionsBase.ttlResolution}
      */
-    isString() {
-        return typeof this.#patternList[this.#index] === 'string';
-    }
+    ttlResolution;
     /**
-     * true of if pattern() returns GLOBSTAR
+     * {@link LRUCache.OptionsBase.ttlAutopurge}
      */
-    isGlobstar() {
-        return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
-    }
+    ttlAutopurge;
     /**
-     * true if pattern() returns a regexp
+     * {@link LRUCache.OptionsBase.updateAgeOnGet}
      */
-    isRegExp() {
-        return this.#patternList[this.#index] instanceof RegExp;
-    }
+    updateAgeOnGet;
     /**
-     * The /-joined set of glob parts that make up this pattern
+     * {@link LRUCache.OptionsBase.updateAgeOnHas}
      */
-    globString() {
-        return (this.#globString =
-            this.#globString ||
-                (this.#index === 0 ?
-                    this.isAbsolute() ?
-                        this.#globList[0] + this.#globList.slice(1).join('/')
-                        : this.#globList.join('/')
-                    : this.#globList.slice(this.#index).join('/')));
-    }
+    updateAgeOnHas;
     /**
-     * true if there are more pattern parts after this one
+     * {@link LRUCache.OptionsBase.allowStale}
      */
-    hasMore() {
-        return this.length > this.#index + 1;
-    }
+    allowStale;
     /**
-     * The rest of the pattern after this part, or null if this is the end
+     * {@link LRUCache.OptionsBase.noDisposeOnSet}
      */
-    rest() {
-        if (this.#rest !== undefined)
-            return this.#rest;
-        if (!this.hasMore())
-            return (this.#rest = null);
-        this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
-        this.#rest.#isAbsolute = this.#isAbsolute;
-        this.#rest.#isUNC = this.#isUNC;
-        this.#rest.#isDrive = this.#isDrive;
-        return this.#rest;
-    }
+    noDisposeOnSet;
     /**
-     * true if the pattern represents a //unc/path/ on windows
+     * {@link LRUCache.OptionsBase.noUpdateTTL}
      */
-    isUNC() {
-        const pl = this.#patternList;
-        return this.#isUNC !== undefined ?
-            this.#isUNC
-            : (this.#isUNC =
-                this.#platform === 'win32' &&
-                    this.#index === 0 &&
-                    pl[0] === '' &&
-                    pl[1] === '' &&
-                    typeof pl[2] === 'string' &&
-                    !!pl[2] &&
-                    typeof pl[3] === 'string' &&
-                    !!pl[3]);
-    }
-    // pattern like C:/...
-    // split = ['C:', ...]
-    // XXX: would be nice to handle patterns like `c:*` to test the cwd
-    // in c: for *, but I don't know of a way to even figure out what that
-    // cwd is without actually chdir'ing into it?
+    noUpdateTTL;
     /**
-     * True if the pattern starts with a drive letter on Windows
+     * {@link LRUCache.OptionsBase.maxEntrySize}
      */
-    isDrive() {
-        const pl = this.#patternList;
-        return this.#isDrive !== undefined ?
-            this.#isDrive
-            : (this.#isDrive =
-                this.#platform === 'win32' &&
-                    this.#index === 0 &&
-                    this.length > 1 &&
-                    typeof pl[0] === 'string' &&
-                    /^[a-z]:$/i.test(pl[0]));
-    }
-    // pattern = '/' or '/...' or '/x/...'
-    // split = ['', ''] or ['', ...] or ['', 'x', ...]
-    // Drive and UNC both considered absolute on windows
+    maxEntrySize;
     /**
-     * True if the pattern is rooted on an absolute path
+     * {@link LRUCache.OptionsBase.sizeCalculation}
      */
-    isAbsolute() {
-        const pl = this.#patternList;
-        return this.#isAbsolute !== undefined ?
-            this.#isAbsolute
-            : (this.#isAbsolute =
-                (pl[0] === '' && pl.length > 1) ||
-                    this.isDrive() ||
-                    this.isUNC());
-    }
+    sizeCalculation;
     /**
-     * consume the root of the pattern, and return it
+     * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
      */
-    root() {
-        const p = this.#patternList[0];
-        return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
-            p
-            : '';
-    }
+    noDeleteOnFetchRejection;
     /**
-     * Check to see if the current globstar pattern is allowed to follow
-     * a symbolic link.
+     * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
      */
-    checkFollowGlobstar() {
-        return !(this.#index === 0 ||
-            !this.isGlobstar() ||
-            !this.#followGlobstar);
-    }
+    noDeleteOnStaleGet;
     /**
-     * Mark that the current globstar pattern is following a symbolic link
+     * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
      */
-    markFollowGlobstar() {
-        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
-            return false;
-        this.#followGlobstar = false;
-        return true;
-    }
-}
-exports.Pattern = Pattern;
-//# sourceMappingURL=pattern.js.map
-
-/***/ }),
-
-/***/ 48095:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// synchronous utility for filtering entries and calculating subwalks
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0;
-const minimatch_1 = __nccwpck_require__(45613);
-/**
- * A cache of which patterns have been processed for a given Path
- */
-class HasWalkedCache {
-    store;
-    constructor(store = new Map()) {
-        this.store = store;
-    }
-    copy() {
-        return new HasWalkedCache(new Map(this.store));
-    }
-    hasWalked(target, pattern) {
-        return this.store.get(target.fullpath())?.has(pattern.globString());
-    }
-    storeWalked(target, pattern) {
-        const fullpath = target.fullpath();
-        const cached = this.store.get(fullpath);
-        if (cached)
-            cached.add(pattern.globString());
-        else
-            this.store.set(fullpath, new Set([pattern.globString()]));
-    }
-}
-exports.HasWalkedCache = HasWalkedCache;
-/**
- * A record of which paths have been matched in a given walk step,
- * and whether they only are considered a match if they are a directory,
- * and whether their absolute or relative path should be returned.
- */
-class MatchRecord {
-    store = new Map();
-    add(target, absolute, ifDir) {
-        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
-        const current = this.store.get(target);
-        this.store.set(target, current === undefined ? n : n & current);
-    }
-    // match, absolute, ifdir
-    entries() {
-        return [...this.store.entries()].map(([path, n]) => [
-            path,
-            !!(n & 2),
-            !!(n & 1),
-        ]);
-    }
-}
-exports.MatchRecord = MatchRecord;
-/**
- * A collection of patterns that must be processed in a subsequent step
- * for a given path.
- */
-class SubWalks {
-    store = new Map();
-    add(target, pattern) {
-        if (!target.canReaddir()) {
-            return;
-        }
-        const subs = this.store.get(target);
-        if (subs) {
-            if (!subs.find(p => p.globString() === pattern.globString())) {
-                subs.push(pattern);
-            }
-        }
-        else
-            this.store.set(target, [pattern]);
-    }
-    get(target) {
-        const subs = this.store.get(target);
-        /* c8 ignore start */
-        if (!subs) {
-            throw new Error('attempting to walk unknown path');
-        }
-        /* c8 ignore stop */
-        return subs;
-    }
-    entries() {
-        return this.keys().map(k => [k, this.store.get(k)]);
-    }
-    keys() {
-        return [...this.store.keys()].filter(t => t.canReaddir());
-    }
-}
-exports.SubWalks = SubWalks;
-/**
- * The class that processes patterns for a given path.
- *
- * Handles child entry filtering, and determining whether a path's
- * directory contents must be read.
- */
-class Processor {
-    hasWalkedCache;
-    matches = new MatchRecord();
-    subwalks = new SubWalks();
-    patterns;
-    follow;
-    dot;
-    opts;
-    constructor(opts, hasWalkedCache) {
-        this.opts = opts;
-        this.follow = !!opts.follow;
-        this.dot = !!opts.dot;
-        this.hasWalkedCache =
-            hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
-    }
-    processPatterns(target, patterns) {
-        this.patterns = patterns;
-        const processingSet = patterns.map(p => [target, p]);
-        // map of paths to the magic-starting subwalks they need to walk
-        // first item in patterns is the filter
-        for (let [t, pattern] of processingSet) {
-            this.hasWalkedCache.storeWalked(t, pattern);
-            const root = pattern.root();
-            const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
-            // start absolute patterns at root
-            if (root) {
-                t = t.resolve(root === '/' && this.opts.root !== undefined ?
-                    this.opts.root
-                    : root);
-                const rest = pattern.rest();
-                if (!rest) {
-                    this.matches.add(t, true, false);
-                    continue;
-                }
-                else {
-                    pattern = rest;
-                }
-            }
-            if (t.isENOENT())
-                continue;
-            let p;
-            let rest;
-            let changed = false;
-            while (typeof (p = pattern.pattern()) === 'string' &&
-                (rest = pattern.rest())) {
-                const c = t.resolve(p);
-                t = c;
-                pattern = rest;
-                changed = true;
-            }
-            p = pattern.pattern();
-            rest = pattern.rest();
-            if (changed) {
-                if (this.hasWalkedCache.hasWalked(t, pattern))
-                    continue;
-                this.hasWalkedCache.storeWalked(t, pattern);
-            }
-            // now we have either a final string for a known entry,
-            // more strings for an unknown entry,
-            // or a pattern starting with magic, mounted on t.
-            if (typeof p === 'string') {
-                // must not be final entry, otherwise we would have
-                // concatenated it earlier.
-                const ifDir = p === '..' || p === '' || p === '.';
-                this.matches.add(t.resolve(p), absolute, ifDir);
-                continue;
-            }
-            else if (p === minimatch_1.GLOBSTAR) {
-                // if no rest, match and subwalk pattern
-                // if rest, process rest and subwalk pattern
-                // if it's a symlink, but we didn't get here by way of a
-                // globstar match (meaning it's the first time THIS globstar
-                // has traversed a symlink), then we follow it. Otherwise, stop.
-                if (!t.isSymbolicLink() ||
-                    this.follow ||
-                    pattern.checkFollowGlobstar()) {
-                    this.subwalks.add(t, pattern);
-                }
-                const rp = rest?.pattern();
-                const rrest = rest?.rest();
-                if (!rest || ((rp === '' || rp === '.') && !rrest)) {
-                    // only HAS to be a dir if it ends in **/ or **/.
-                    // but ending in ** will match files as well.
-                    this.matches.add(t, absolute, rp === '' || rp === '.');
-                }
-                else {
-                    if (rp === '..') {
-                        // this would mean you're matching **/.. at the fs root,
-                        // and no thanks, I'm not gonna test that specific case.
-                        /* c8 ignore start */
-                        const tp = t.parent || t;
-                        /* c8 ignore stop */
-                        if (!rrest)
-                            this.matches.add(tp, absolute, true);
-                        else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
-                            this.subwalks.add(tp, rrest);
-                        }
-                    }
-                }
-            }
-            else if (p instanceof RegExp) {
-                this.subwalks.add(t, pattern);
-            }
-        }
-        return this;
+    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),
+        };
     }
-    subwalkTargets() {
-        return this.subwalks.keys();
+    // Protected read-only members
+    /**
+     * {@link LRUCache.OptionsBase.max} (read-only)
+     */
+    get max() {
+        return this.#max;
     }
-    child() {
-        return new Processor(this.opts, this.hasWalkedCache);
+    /**
+     * {@link LRUCache.OptionsBase.maxSize} (read-only)
+     */
+    get maxSize() {
+        return this.#maxSize;
     }
-    // return a new Processor containing the subwalks for each
-    // child entry, and a set of matches, and
-    // a hasWalkedCache that's a copy of this one
-    // then we're going to call
-    filterEntries(parent, entries) {
-        const patterns = this.subwalks.get(parent);
-        // put matches and entry walks into the results processor
-        const results = this.child();
-        for (const e of entries) {
-            for (const pattern of patterns) {
-                const absolute = pattern.isAbsolute();
-                const p = pattern.pattern();
-                const rest = pattern.rest();
-                if (p === minimatch_1.GLOBSTAR) {
-                    results.testGlobstar(e, pattern, rest, absolute);
-                }
-                else if (p instanceof RegExp) {
-                    results.testRegExp(e, p, rest, absolute);
-                }
-                else {
-                    results.testString(e, p, rest, absolute);
-                }
-            }
-        }
-        return results;
+    /**
+     * The total computed size of items in the cache (read-only)
+     */
+    get calculatedSize() {
+        return this.#calculatedSize;
     }
-    testGlobstar(e, pattern, rest, absolute) {
-        if (this.dot || !e.name.startsWith('.')) {
-            if (!pattern.hasMore()) {
-                this.matches.add(e, absolute, false);
-            }
-            if (e.canReaddir()) {
-                // if we're in follow mode or it's not a symlink, just keep
-                // testing the same pattern. If there's more after the globstar,
-                // then this symlink consumes the globstar. If not, then we can
-                // follow at most ONE symlink along the way, so we mark it, which
-                // also checks to ensure that it wasn't already marked.
-                if (this.follow || !e.isSymbolicLink()) {
-                    this.subwalks.add(e, pattern);
-                }
-                else if (e.isSymbolicLink()) {
-                    if (rest && pattern.checkFollowGlobstar()) {
-                        this.subwalks.add(e, rest);
-                    }
-                    else if (pattern.markFollowGlobstar()) {
-                        this.subwalks.add(e, pattern);
-                    }
-                }
-            }
+    /**
+     * 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;
+    }
+    get memoMethod() {
+        return this.#memoMethod;
+    }
+    /**
+     * {@link LRUCache.OptionsBase.dispose} (read-only)
+     */
+    get dispose() {
+        return this.#dispose;
+    }
+    /**
+     * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
+     */
+    get disposeAfter() {
+        return this.#disposeAfter;
+    }
+    constructor(options) {
+        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
+        if (max !== 0 && !isPosInt(max)) {
+            throw new TypeError('max option must be a nonnegative integer');
         }
-        // if the NEXT thing matches this entry, then also add
-        // the rest.
-        if (rest) {
-            const rp = rest.pattern();
-            if (typeof rp === 'string' &&
-                // dots and empty were handled already
-                rp !== '..' &&
-                rp !== '' &&
-                rp !== '.') {
-                this.testString(e, rp, rest.rest(), absolute);
-            }
-            else if (rp === '..') {
-                /* c8 ignore start */
-                const ep = e.parent || e;
-                /* c8 ignore stop */
-                this.subwalks.add(ep, rest);
+        const UintArray = max ? getUintArray(max) : Array;
+        if (!UintArray) {
+            throw new Error('invalid max value: ' + max);
+        }
+        this.#max = max;
+        this.#maxSize = maxSize;
+        this.maxEntrySize = maxEntrySize || this.#maxSize;
+        this.sizeCalculation = sizeCalculation;
+        if (this.sizeCalculation) {
+            if (!this.#maxSize && !this.maxEntrySize) {
+                throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
             }
-            else if (rp instanceof RegExp) {
-                this.testRegExp(e, rp, rest.rest(), absolute);
+            if (typeof this.sizeCalculation !== 'function') {
+                throw new TypeError('sizeCalculation set to non-function');
             }
         }
-    }
-    testRegExp(e, p, rest, absolute) {
-        if (!p.test(e.name))
-            return;
-        if (!rest) {
-            this.matches.add(e, absolute, false);
+        if (memoMethod !== undefined &&
+            typeof memoMethod !== 'function') {
+            throw new TypeError('memoMethod must be a function if defined');
         }
-        else {
-            this.subwalks.add(e, rest);
+        this.#memoMethod = memoMethod;
+        if (fetchMethod !== undefined &&
+            typeof fetchMethod !== 'function') {
+            throw new TypeError('fetchMethod must be a function if specified');
         }
-    }
-    testString(e, p, rest, absolute) {
-        // should never happen?
-        if (!e.isNamed(p))
-            return;
-        if (!rest) {
-            this.matches.add(e, absolute, false);
+        this.#fetchMethod = fetchMethod;
+        this.#hasFetchMethod = !!fetchMethod;
+        this.#keyMap = new Map();
+        this.#keyList = new Array(max).fill(undefined);
+        this.#valList = new Array(max).fill(undefined);
+        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;
+        if (typeof dispose === 'function') {
+            this.#dispose = dispose;
+        }
+        if (typeof disposeAfter === 'function') {
+            this.#disposeAfter = disposeAfter;
+            this.#disposed = [];
         }
         else {
-            this.subwalks.add(e, rest);
+            this.#disposeAfter = undefined;
+            this.#disposed = undefined;
         }
-    }
-}
-exports.Processor = Processor;
-//# sourceMappingURL=processor.js.map
-
-/***/ }),
-
-/***/ 95049:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0;
-/**
- * Single-use utility classes to provide functionality to the {@link Glob}
- * methods.
- *
- * @module
- */
-const minipass_1 = __nccwpck_require__(78275);
-const ignore_js_1 = __nccwpck_require__(4833);
-const processor_js_1 = __nccwpck_require__(48095);
-const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts)
-    : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts)
-        : ignore;
-/**
- * basic walking utilities that all the glob walker types use
- */
-class GlobUtil {
-    path;
-    patterns;
-    opts;
-    seen = new Set();
-    paused = false;
-    aborted = false;
-    #onResume = [];
-    #ignore;
-    #sep;
-    signal;
-    maxDepth;
-    includeChildMatches;
-    constructor(patterns, path, opts) {
-        this.patterns = patterns;
-        this.path = path;
-        this.opts = opts;
-        this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
-        this.includeChildMatches = opts.includeChildMatches !== false;
-        if (opts.ignore || !this.includeChildMatches) {
-            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
-            if (!this.includeChildMatches &&
-                typeof this.#ignore.add !== 'function') {
-                const m = 'cannot ignore child matches, ignore lacks add() method.';
-                throw new Error(m);
+        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;
+        // NB: maxEntrySize is set to maxSize if it's set
+        if (this.maxEntrySize !== 0) {
+            if (this.#maxSize !== 0) {
+                if (!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();
         }
-        // ignore, always set with maxDepth, but it's optional on the
-        // GlobOptions type
-        /* c8 ignore start */
-        this.maxDepth = opts.maxDepth || Infinity;
-        /* c8 ignore stop */
-        if (opts.signal) {
-            this.signal = opts.signal;
-            this.signal.addEventListener('abort', () => {
-                this.#onResume.length = 0;
-            });
-        }
-    }
-    #ignored(path) {
-        return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
-    }
-    #childrenIgnored(path) {
-        return !!this.#ignore?.childrenIgnored?.(path);
-    }
-    // backpressure mechanism
-    pause() {
-        this.paused = true;
-    }
-    resume() {
-        /* c8 ignore start */
-        if (this.signal?.aborted)
-            return;
-        /* c8 ignore stop */
-        this.paused = false;
-        let fn = undefined;
-        while (!this.paused && (fn = this.#onResume.shift())) {
-            fn();
+        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;
+        if (this.ttl) {
+            if (!isPosInt(this.ttl)) {
+                throw new TypeError('ttl must be a positive integer if specified');
+            }
+            this.#initializeTTLTracking();
         }
-    }
-    onResume(fn) {
-        if (this.signal?.aborted)
-            return;
-        /* c8 ignore start */
-        if (!this.paused) {
-            fn();
+        // do not allow completely unbounded caches
+        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
+            throw new TypeError('At least one of max, maxSize, or ttl is required');
         }
-        else {
-            /* c8 ignore stop */
-            this.#onResume.push(fn);
+        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
+            const code = 'LRU_CACHE_UNBOUNDED';
+            if (shouldWarn(code)) {
+                warned.add(code);
+                const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
+                    'result in unbounded memory consumption.';
+                emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
+            }
         }
     }
-    // do the requisite realpath/stat checking, and return the path
-    // to add or undefined to filter it out.
-    async matchCheck(e, ifDir) {
-        if (ifDir && this.opts.nodir)
-            return undefined;
-        let rpc;
-        if (this.opts.realpath) {
-            rpc = e.realpathCached() || (await e.realpath());
-            if (!rpc)
-                return undefined;
-            e = rpc;
-        }
-        const needStat = e.isUnknown() || this.opts.stat;
-        const s = needStat ? await e.lstat() : e;
-        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
-            const target = await s.realpath();
-            /* c8 ignore start */
-            if (target && (target.isUnknown() || this.opts.stat)) {
-                await target.lstat();
+    /**
+     * Return the number of ms left in the item's TTL. If item is not in cache,
+     * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
+     */
+    getRemainingTTL(key) {
+        return this.#keyMap.has(key) ? Infinity : 0;
+    }
+    #initializeTTLTracking() {
+        const ttls = new ZeroArray(this.#max);
+        const starts = new ZeroArray(this.#max);
+        this.#ttls = ttls;
+        this.#starts = starts;
+        this.#setItemTTL = (index, ttl, start = perf.now()) => {
+            starts[index] = ttl !== 0 ? start : 0;
+            ttls[index] = ttl;
+            if (ttl !== 0 && this.ttlAutopurge) {
+                const t = setTimeout(() => {
+                    if (this.#isStale(index)) {
+                        this.#delete(this.#keyList[index], 'expire');
+                    }
+                }, ttl + 1);
+                // unref() not supported on all platforms
+                /* c8 ignore start */
+                if (t.unref) {
+                    t.unref();
+                }
+                /* c8 ignore stop */
             }
-            /* c8 ignore stop */
-        }
-        return this.matchCheckTest(s, ifDir);
+        };
+        this.#updateItemAge = index => {
+            starts[index] = ttls[index] !== 0 ? perf.now() : 0;
+        };
+        this.#statusTTL = (status, index) => {
+            if (ttls[index]) {
+                const ttl = ttls[index];
+                const start = starts[index];
+                /* c8 ignore next */
+                if (!ttl || !start)
+                    return;
+                status.ttl = ttl;
+                status.start = start;
+                status.now = cachedNow || getNow();
+                const age = status.now - start;
+                status.remainingTTL = ttl - age;
+            }
+        };
+        // debounce calls to perf.now() to 1s so we're not hitting
+        // that costly call repeatedly.
+        let cachedNow = 0;
+        const getNow = () => {
+            const n = perf.now();
+            if (this.ttlResolution > 0) {
+                cachedNow = n;
+                const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
+                // not available on all platforms
+                /* c8 ignore start */
+                if (t.unref) {
+                    t.unref();
+                }
+                /* c8 ignore stop */
+            }
+            return n;
+        };
+        this.getRemainingTTL = key => {
+            const index = this.#keyMap.get(key);
+            if (index === undefined) {
+                return 0;
+            }
+            const ttl = ttls[index];
+            const start = starts[index];
+            if (!ttl || !start) {
+                return Infinity;
+            }
+            const age = (cachedNow || getNow()) - start;
+            return ttl - age;
+        };
+        this.#isStale = index => {
+            const s = starts[index];
+            const t = ttls[index];
+            return !!t && !!s && (cachedNow || getNow()) - s > t;
+        };
     }
-    matchCheckTest(e, ifDir) {
-        return (e &&
-            (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
-            (!ifDir || e.canReaddir()) &&
-            (!this.opts.nodir || !e.isDirectory()) &&
-            (!this.opts.nodir ||
-                !this.opts.follow ||
-                !e.isSymbolicLink() ||
-                !e.realpathCached()?.isDirectory()) &&
-            !this.#ignored(e)) ?
-            e
-            : undefined;
+    // conditionally set private methods related to TTL
+    #updateItemAge = () => { };
+    #statusTTL = () => { };
+    #setItemTTL = () => { };
+    /* c8 ignore stop */
+    #isStale = () => false;
+    #initializeSizeTracking() {
+        const 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) => {
+            // provisionally accept background fetches.
+            // actual value size will be checked when they return.
+            if (this.#isBackgroundFetch(v)) {
+                return 0;
+            }
+            if (!isPosInt(size)) {
+                if (sizeCalculation) {
+                    if (typeof sizeCalculation !== 'function') {
+                        throw new TypeError('sizeCalculation must be a function');
+                    }
+                    size = sizeCalculation(v, k);
+                    if (!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) => {
+            sizes[index] = size;
+            if (this.#maxSize) {
+                const maxSize = this.#maxSize - sizes[index];
+                while (this.#calculatedSize > maxSize) {
+                    this.#evict(true);
+                }
+            }
+            this.#calculatedSize += sizes[index];
+            if (status) {
+                status.entrySize = size;
+                status.totalCalculatedSize = this.#calculatedSize;
+            }
+        };
     }
-    matchCheckSync(e, ifDir) {
-        if (ifDir && this.opts.nodir)
-            return undefined;
-        let rpc;
-        if (this.opts.realpath) {
-            rpc = e.realpathCached() || e.realpathSync();
-            if (!rpc)
-                return undefined;
-            e = rpc;
+    #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');
         }
-        const needStat = e.isUnknown() || this.opts.stat;
-        const s = needStat ? e.lstatSync() : e;
-        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
-            const target = s.realpathSync();
-            if (target && (target?.isUnknown() || this.opts.stat)) {
-                target.lstatSync();
+        return 0;
+    };
+    *#indexes({ allowStale = this.allowStale } = {}) {
+        if (this.#size) {
+            for (let i = this.#tail; true;) {
+                if (!this.#isValidIndex(i)) {
+                    break;
+                }
+                if (allowStale || !this.#isStale(i)) {
+                    yield i;
+                }
+                if (i === this.#head) {
+                    break;
+                }
+                else {
+                    i = this.#prev[i];
+                }
             }
         }
-        return this.matchCheckTest(s, ifDir);
     }
-    matchFinish(e, absolute) {
-        if (this.#ignored(e))
-            return;
-        // we know we have an ignore if this is false, but TS doesn't
-        if (!this.includeChildMatches && this.#ignore?.add) {
-            const ign = `${e.relativePosix()}/**`;
-            this.#ignore.add(ign);
-        }
-        const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
-        this.seen.add(e);
-        const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
-        // ok, we have what we need!
-        if (this.opts.withFileTypes) {
-            this.matchEmit(e);
-        }
-        else if (abs) {
-            const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
-            this.matchEmit(abs + mark);
-        }
-        else {
-            const rel = this.opts.posix ? e.relativePosix() : e.relative();
-            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
-                '.' + this.#sep
-                : '';
-            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
+    *#rindexes({ allowStale = this.allowStale } = {}) {
+        if (this.#size) {
+            for (let i = this.#head; true;) {
+                if (!this.#isValidIndex(i)) {
+                    break;
+                }
+                if (allowStale || !this.#isStale(i)) {
+                    yield i;
+                }
+                if (i === this.#tail) {
+                    break;
+                }
+                else {
+                    i = this.#next[i];
+                }
+            }
         }
     }
-    async match(e, absolute, ifDir) {
-        const p = await this.matchCheck(e, ifDir);
-        if (p)
-            this.matchFinish(p, absolute);
-    }
-    matchSync(e, absolute, ifDir) {
-        const p = this.matchCheckSync(e, ifDir);
-        if (p)
-            this.matchFinish(p, absolute);
-    }
-    walkCB(target, patterns, cb) {
-        /* c8 ignore start */
-        if (this.signal?.aborted)
-            cb();
-        /* c8 ignore stop */
-        this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
+    #isValidIndex(index) {
+        return (index !== undefined &&
+            this.#keyMap.get(this.#keyList[index]) === index);
     }
-    walkCB2(target, patterns, processor, cb) {
-        if (this.#childrenIgnored(target))
-            return cb();
-        if (this.signal?.aborted)
-            cb();
-        if (this.paused) {
-            this.onResume(() => this.walkCB2(target, patterns, processor, cb));
-            return;
-        }
-        processor.processPatterns(target, patterns);
-        // done processing.  all of the above is sync, can be abstracted out.
-        // subwalks is a map of paths to the entry filters they need
-        // matches is a map of paths to [absolute, ifDir] tuples.
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
-        }
-        for (const t of processor.subwalkTargets()) {
-            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
-                continue;
-            }
-            tasks++;
-            const childrenCached = t.readdirCached();
-            if (t.calledReaddir())
-                this.walkCB3(t, childrenCached, processor, next);
-            else {
-                t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
+    /**
+     * Return a generator yielding `[key, value]` pairs,
+     * in order from most recently used to least recently used.
+     */
+    *entries() {
+        for (const i of this.#indexes()) {
+            if (this.#valList[i] !== undefined &&
+                this.#keyList[i] !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield [this.#keyList[i], this.#valList[i]];
             }
         }
-        next();
     }
-    walkCB3(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            tasks++;
-            this.match(m, absolute, ifDir).then(() => next());
-        }
-        for (const [target, patterns] of processor.subwalks.entries()) {
-            tasks++;
-            this.walkCB2(target, patterns, processor.child(), next);
+    /**
+     * 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 (const i of this.#rindexes()) {
+            if (this.#valList[i] !== undefined &&
+                this.#keyList[i] !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield [this.#keyList[i], this.#valList[i]];
+            }
         }
-        next();
-    }
-    walkCBSync(target, patterns, cb) {
-        /* c8 ignore start */
-        if (this.signal?.aborted)
-            cb();
-        /* c8 ignore stop */
-        this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
     }
-    walkCB2Sync(target, patterns, processor, cb) {
-        if (this.#childrenIgnored(target))
-            return cb();
-        if (this.signal?.aborted)
-            cb();
-        if (this.paused) {
-            this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
-            return;
-        }
-        processor.processPatterns(target, patterns);
-        // done processing.  all of the above is sync, can be abstracted out.
-        // subwalks is a map of paths to the entry filters they need
-        // matches is a map of paths to [absolute, ifDir] tuples.
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            this.matchSync(m, absolute, ifDir);
-        }
-        for (const t of processor.subwalkTargets()) {
-            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
-                continue;
+    /**
+     * Return a generator yielding the keys in the cache,
+     * in order from most recently used to least recently used.
+     */
+    *keys() {
+        for (const i of this.#indexes()) {
+            const k = this.#keyList[i];
+            if (k !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield k;
             }
-            tasks++;
-            const children = t.readdirSync();
-            this.walkCB3Sync(t, children, processor, next);
         }
-        next();
     }
-    walkCB3Sync(target, entries, processor, cb) {
-        processor = processor.filterEntries(target, entries);
-        let tasks = 1;
-        const next = () => {
-            if (--tasks === 0)
-                cb();
-        };
-        for (const [m, absolute, ifDir] of processor.matches.entries()) {
-            if (this.#ignored(m))
-                continue;
-            this.matchSync(m, absolute, ifDir);
-        }
-        for (const [target, patterns] of processor.subwalks.entries()) {
-            tasks++;
-            this.walkCB2Sync(target, patterns, processor.child(), next);
+    /**
+     * 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 (const i of this.#rindexes()) {
+            const k = this.#keyList[i];
+            if (k !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield k;
+            }
         }
-        next();
-    }
-}
-exports.GlobUtil = GlobUtil;
-class GlobWalker extends GlobUtil {
-    matches = new Set();
-    constructor(patterns, path, opts) {
-        super(patterns, path, opts);
-    }
-    matchEmit(e) {
-        this.matches.add(e);
     }
-    async walk() {
-        if (this.signal?.aborted)
-            throw this.signal.reason;
-        if (this.path.isUnknown()) {
-            await this.path.lstat();
+    /**
+     * Return a generator yielding the values in the cache,
+     * in order from most recently used to least recently used.
+     */
+    *values() {
+        for (const i of this.#indexes()) {
+            const v = this.#valList[i];
+            if (v !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield this.#valList[i];
+            }
         }
-        await new Promise((res, rej) => {
-            this.walkCB(this.path, this.patterns, () => {
-                if (this.signal?.aborted) {
-                    rej(this.signal.reason);
-                }
-                else {
-                    res(this.matches);
-                }
-            });
-        });
-        return this.matches;
     }
-    walkSync() {
-        if (this.signal?.aborted)
-            throw this.signal.reason;
-        if (this.path.isUnknown()) {
-            this.path.lstatSync();
+    /**
+     * 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 (const i of this.#rindexes()) {
+            const v = this.#valList[i];
+            if (v !== undefined &&
+                !this.#isBackgroundFetch(this.#valList[i])) {
+                yield this.#valList[i];
+            }
         }
-        // nothing for the callback to do, because this never pauses
-        this.walkCBSync(this.path, this.patterns, () => {
-            if (this.signal?.aborted)
-                throw this.signal.reason;
-        });
-        return this.matches;
-    }
-}
-exports.GlobWalker = GlobWalker;
-class GlobStream extends GlobUtil {
-    results;
-    constructor(patterns, path, opts) {
-        super(patterns, path, opts);
-        this.results = new minipass_1.Minipass({
-            signal: this.signal,
-            objectMode: true,
-        });
-        this.results.on('drain', () => this.resume());
-        this.results.on('resume', () => this.resume());
     }
-    matchEmit(e) {
-        this.results.write(e);
-        if (!this.results.flowing)
-            this.pause();
+    /**
+     * Iterating over the cache itself yields the same results as
+     * {@link LRUCache.entries}
+     */
+    [Symbol.iterator]() {
+        return this.entries();
     }
-    stream() {
-        const target = this.path;
-        if (target.isUnknown()) {
-            target.lstat().then(() => {
-                this.walkCB(target, this.patterns, () => this.results.end());
-            });
-        }
-        else {
-            this.walkCB(target, this.patterns, () => this.results.end());
+    /**
+     * A String value that is used in the creation of the default string
+     * description of an object. Called by the built-in method
+     * `Object.prototype.toString`.
+     */
+    [Symbol.toStringTag] = 'LRUCache';
+    /**
+     * 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 (const i of this.#indexes()) {
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined)
+                continue;
+            if (fn(value, this.#keyList[i], this)) {
+                return this.get(this.#keyList[i], getOptions);
+            }
         }
-        return this.results;
     }
-    streamSync() {
-        if (this.path.isUnknown()) {
-            this.path.lstatSync();
+    /**
+     * 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)`.
+     *
+     * If `thisp` is provided, function will be called in the `this`-context of
+     * the provided object, or the cache if no `thisp` object is provided.
+     *
+     * Does not update age or recenty of use, or iterate over stale values.
+     */
+    forEach(fn, thisp = this) {
+        for (const i of this.#indexes()) {
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined)
+                continue;
+            fn.call(thisp, value, this.#keyList[i], this);
         }
-        this.walkCBSync(this.path, this.patterns, () => this.results.end());
-        return this.results;
     }
-}
-exports.GlobStream = GlobStream;
-//# sourceMappingURL=walker.js.map
-
-/***/ }),
-
-/***/ 33555:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.assertValidPattern = void 0;
-const MAX_PATTERN_LENGTH = 1024 * 64;
-const assertValidPattern = (pattern) => {
-    if (typeof pattern !== 'string') {
-        throw new TypeError('invalid pattern');
+    /**
+     * 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 (const i of this.#rindexes()) {
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined)
+                continue;
+            fn.call(thisp, value, this.#keyList[i], this);
+        }
     }
-    if (pattern.length > MAX_PATTERN_LENGTH) {
-        throw new TypeError('pattern is too long');
+    /**
+     * Delete any stale entries. Returns true if anything was removed,
+     * false otherwise.
+     */
+    purgeStale() {
+        let deleted = false;
+        for (const i of this.#rindexes({ allowStale: true })) {
+            if (this.#isStale(i)) {
+                this.#delete(this.#keyList[i], 'expire');
+                deleted = true;
+            }
+        }
+        return deleted;
     }
-};
-exports.assertValidPattern = assertValidPattern;
-//# sourceMappingURL=assert-valid-pattern.js.map
-
-/***/ }),
-
-/***/ 10421:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-"use strict";
-
-// parse a single path portion
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AST = void 0;
-const brace_expressions_js_1 = __nccwpck_require__(34796);
-const unescape_js_1 = __nccwpck_require__(11633);
-const types = new Set(['!', '?', '+', '*', '@']);
-const isExtglobType = (c) => types.has(c);
-// Patterns that get prepended to bind to the start of either the
-// entire string, or just a single path portion, to prevent dots
-// and/or traversal patterns, when needed.
-// Exts don't need the ^ or / bit, because the root binds that already.
-const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
-const startNoDot = '(?!\\.)';
-// characters that indicate a start of pattern needs the "no dots" bit,
-// because a dot *might* be matched. ( is not in the list, because in
-// the case of a child extglob, it will handle the prevention itself.
-const addPatternStart = new Set(['[', '.']);
-// cases where traversal is A-OK, no dot prevention needed
-const justDots = new Set(['..', '.']);
-const reSpecials = new Set('().*{}+?[]^$\\!');
-const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-// any single thing other than /
-const qmark = '[^/]';
-// * => any number of characters
-const star = qmark + '*?';
-// use + when we need to ensure that *something* matches, because the * is
-// the only thing in the path portion.
-const starNoEmpty = qmark + '+?';
-// remove the \ chars that we added if we end up doing a nonmagic compare
-// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
-class AST {
-    type;
-    #root;
-    #hasMagic;
-    #uflag = false;
-    #parts = [];
-    #parent;
-    #parentIndex;
-    #negs;
-    #filledNegs = false;
-    #options;
-    #toString;
-    // set to true if it's an extglob with no children
-    // (which really means one child of '')
-    #emptyExt = false;
-    constructor(type, parent, options = {}) {
-        this.type = type;
-        // extglobs are inherently magical
-        if (type)
-            this.#hasMagic = true;
-        this.#parent = parent;
-        this.#root = this.#parent ? this.#parent.#root : this;
-        this.#options = this.#root === this ? options : this.#root.#options;
-        this.#negs = this.#root === this ? [] : this.#root.#negs;
-        if (type === '!' && !this.#root.#filledNegs)
-            this.#negs.push(this);
-        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
+    /**
+     * Get the extended info about a given entry, to get its value, size, and
+     * TTL info simultaneously. Returns `undefined` if the key is not present.
+     *
+     * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
+     * serialization, the `start` value is always the current timestamp, and the
+     * `ttl` is a calculated remaining time to live (negative if expired).
+     *
+     * Always returns stale values, if their info is found in the cache, so be
+     * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
+     * if relevant.
+     */
+    info(key) {
+        const i = this.#keyMap.get(key);
+        if (i === undefined)
+            return undefined;
+        const v = this.#valList[i];
+        const value = this.#isBackgroundFetch(v)
+            ? v.__staleWhileFetching
+            : v;
+        if (value === undefined)
+            return undefined;
+        const entry = { value };
+        if (this.#ttls && this.#starts) {
+            const ttl = this.#ttls[i];
+            const start = this.#starts[i];
+            if (ttl && start) {
+                const remain = ttl - (perf.now() - start);
+                entry.ttl = remain;
+                entry.start = Date.now();
+            }
+        }
+        if (this.#sizes) {
+            entry.size = this.#sizes[i];
+        }
+        return entry;
     }
-    get hasMagic() {
-        /* c8 ignore start */
-        if (this.#hasMagic !== undefined)
-            return this.#hasMagic;
-        /* c8 ignore stop */
-        for (const p of this.#parts) {
-            if (typeof p === 'string')
+    /**
+     * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
+     * passed to {@link LRLUCache#load}.
+     *
+     * The `start` fields are calculated relative to a portable `Date.now()`
+     * timestamp, even if `performance.now()` is available.
+     *
+     * Stale entries are always included in the `dump`, even if
+     * {@link LRUCache.OptionsBase.allowStale} is false.
+     *
+     * Note: this returns an actual array, not a generator, so it can be more
+     * easily passed around.
+     */
+    dump() {
+        const arr = [];
+        for (const i of this.#indexes({ allowStale: true })) {
+            const key = this.#keyList[i];
+            const v = this.#valList[i];
+            const value = this.#isBackgroundFetch(v)
+                ? v.__staleWhileFetching
+                : v;
+            if (value === undefined || key === undefined)
                 continue;
-            if (p.type || p.hasMagic)
-                return (this.#hasMagic = true);
+            const entry = { value };
+            if (this.#ttls && this.#starts) {
+                entry.ttl = this.#ttls[i];
+                // always dump the start relative to a portable timestamp
+                // it's ok for this to be a bit slow, it's a rare operation.
+                const age = perf.now() - this.#starts[i];
+                entry.start = Math.floor(Date.now() - age);
+            }
+            if (this.#sizes) {
+                entry.size = this.#sizes[i];
+            }
+            arr.unshift([key, entry]);
         }
-        // note: will be undefined until we generate the regexp src and find out
-        return this.#hasMagic;
+        return arr;
     }
-    // reconstructs the pattern
-    toString() {
-        if (this.#toString !== undefined)
-            return this.#toString;
-        if (!this.type) {
-            return (this.#toString = this.#parts.map(p => String(p)).join(''));
-        }
-        else {
-            return (this.#toString =
-                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
+    /**
+     * Reset the cache and load in the items in entries in the order listed.
+     *
+     * The shape of the resulting cache may be different if the same options are
+     * not used in both caches.
+     *
+     * The `start` fields are assumed to be calculated relative to a portable
+     * `Date.now()` timestamp, even if `performance.now()` is available.
+     */
+    load(arr) {
+        this.clear();
+        for (const [key, entry] of arr) {
+            if (entry.start) {
+                // entry.start is a portable timestamp, but we may be using
+                // node's performance.now(), so calculate the offset, so that
+                // we get the intended remaining TTL, no matter how long it's
+                // been on ice.
+                //
+                // it's ok for this to be a bit slow, it's a rare operation.
+                const age = Date.now() - entry.start;
+                entry.start = perf.now() - age;
+            }
+            this.set(key, entry.value, entry);
         }
     }
-    #fillNegs() {
-        /* c8 ignore start */
-        if (this !== this.#root)
-            throw new Error('should only call on root');
-        if (this.#filledNegs)
+    /**
+     * Add a value to the cache.
+     *
+     * Note: if `undefined` is specified as a value, this is an alias for
+     * {@link LRUCache#delete}
+     *
+     * Fields on the {@link LRUCache.SetOptions} options param will override
+     * their corresponding values in the constructor options for the scope
+     * of this single `set()` operation.
+     *
+     * If `start` is provided, then that will set the effective start
+     * time for the TTL calculation. Note that this must be a previous
+     * value of `performance.now()` if supported, or a previous value of
+     * `Date.now()` if not.
+     *
+     * Options object may also include `size`, which will prevent
+     * calling the `sizeCalculation` function and just use the specified
+     * number if it is a positive integer, and `noDisposeOnSet` which
+     * will prevent calling a `dispose` function in the case of
+     * overwrites.
+     *
+     * If the `size` (or return value of `sizeCalculation`) for a given
+     * entry is greater than `maxEntrySize`, then the item will not be
+     * added to the cache.
+     *
+     * Will update the recency of the entry.
+     *
+     * If the value is `undefined`, then this is an alias for
+     * `cache.delete(key)`. `undefined` is never stored in the cache.
+     */
+    set(k, v, setOptions = {}) {
+        if (v === undefined) {
+            this.delete(k);
             return this;
-        /* c8 ignore stop */
-        // call toString() once to fill this out
-        this.toString();
-        this.#filledNegs = true;
-        let n;
-        while ((n = this.#negs.pop())) {
-            if (n.type !== '!')
-                continue;
-            // walk up the tree, appending everthing that comes AFTER parentIndex
-            let p = n;
-            let pp = p.#parent;
-            while (pp) {
-                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
-                    for (const part of n.#parts) {
-                        /* c8 ignore start */
-                        if (typeof part === 'string') {
-                            throw new Error('string part in extglob AST??');
+        }
+        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
+        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
+        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
+        // if the item doesn't fit, don't do anything
+        // NB: maxEntrySize set to maxSize by default
+        if (this.maxEntrySize && size > this.maxEntrySize) {
+            if (status) {
+                status.set = 'miss';
+                status.maxEntrySizeExceeded = true;
+            }
+            // have to delete, in case something is there already.
+            this.#delete(k, 'set');
+            return this;
+        }
+        let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
+        if (index === undefined) {
+            // addition
+            index = (this.#size === 0
+                ? this.#tail
+                : this.#free.length !== 0
+                    ? this.#free.pop()
+                    : this.#size === this.#max
+                        ? this.#evict(false)
+                        : 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);
+            if (status)
+                status.set = 'add';
+            noUpdateTTL = false;
+        }
+        else {
+            // update
+            this.#moveToTail(index);
+            const oldVal = this.#valList[index];
+            if (v !== oldVal) {
+                if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
+                    oldVal.__abortController.abort(new Error('replaced'));
+                    const { __staleWhileFetching: s } = oldVal;
+                    if (s !== undefined && !noDisposeOnSet) {
+                        if (this.#hasDispose) {
+                            this.#dispose?.(s, k, 'set');
+                        }
+                        if (this.#hasDisposeAfter) {
+                            this.#disposed?.push([s, k, 'set']);
                         }
-                        /* c8 ignore stop */
-                        part.copyIn(pp.#parts[i]);
                     }
                 }
-                p = pp;
-                pp = p.#parent;
+                else if (!noDisposeOnSet) {
+                    if (this.#hasDispose) {
+                        this.#dispose?.(oldVal, k, 'set');
+                    }
+                    if (this.#hasDisposeAfter) {
+                        this.#disposed?.push([oldVal, k, 'set']);
+                    }
+                }
+                this.#removeItemSize(index);
+                this.#addItemSize(index, size, status);
+                this.#valList[index] = v;
+                if (status) {
+                    status.set = 'replace';
+                    const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
+                        ? oldVal.__staleWhileFetching
+                        : oldVal;
+                    if (oldValue !== undefined)
+                        status.oldValue = oldValue;
+                }
+            }
+            else if (status) {
+                status.set = 'update';
+            }
+        }
+        if (ttl !== 0 && !this.#ttls) {
+            this.#initializeTTLTracking();
+        }
+        if (this.#ttls) {
+            if (!noUpdateTTL) {
+                this.#setItemTTL(index, ttl, start);
+            }
+            if (status)
+                this.#statusTTL(status, index);
+        }
+        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
         }
         return this;
     }
-    push(...parts) {
-        for (const p of parts) {
-            if (p === '')
-                continue;
-            /* c8 ignore start */
-            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
-                throw new Error('invalid part: ' + p);
+    /**
+     * Evict the least recently used item, returning its value or
+     * `undefined` if cache is empty.
+     */
+    pop() {
+        try {
+            while (this.#size) {
+                const val = this.#valList[this.#head];
+                this.#evict(true);
+                if (this.#isBackgroundFetch(val)) {
+                    if (val.__staleWhileFetching) {
+                        return val.__staleWhileFetching;
+                    }
+                }
+                else if (val !== undefined) {
+                    return val;
+                }
+            }
+        }
+        finally {
+            if (this.#hasDisposeAfter && this.#disposed) {
+                const dt = this.#disposed;
+                let task;
+                while ((task = dt?.shift())) {
+                    this.#disposeAfter?.(...task);
+                }
             }
-            /* c8 ignore stop */
-            this.#parts.push(p);
         }
     }
-    toJSON() {
-        const ret = this.type === null
-            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
-            : [this.type, ...this.#parts.map(p => p.toJSON())];
-        if (this.isStart() && !this.type)
-            ret.unshift([]);
-        if (this.isEnd() &&
-            (this === this.#root ||
-                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
-            ret.push({});
+    #evict(free) {
+        const head = this.#head;
+        const k = this.#keyList[head];
+        const v = this.#valList[head];
+        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
+            v.__abortController.abort(new Error('evicted'));
         }
-        return ret;
+        else if (this.#hasDispose || this.#hasDisposeAfter) {
+            if (this.#hasDispose) {
+                this.#dispose?.(v, k, 'evict');
+            }
+            if (this.#hasDisposeAfter) {
+                this.#disposed?.push([v, k, 'evict']);
+            }
+        }
+        this.#removeItemSize(head);
+        // if we aren't about to use the index, then null these out
+        if (free) {
+            this.#keyList[head] = undefined;
+            this.#valList[head] = undefined;
+            this.#free.push(head);
+        }
+        if (this.#size === 1) {
+            this.#head = this.#tail = 0;
+            this.#free.length = 0;
+        }
+        else {
+            this.#head = this.#next[head];
+        }
+        this.#keyMap.delete(k);
+        this.#size--;
+        return head;
     }
-    isStart() {
-        if (this.#root === this)
-            return true;
-        // if (this.type) return !!this.#parent?.isStart()
-        if (!this.#parent?.isStart())
-            return false;
-        if (this.#parentIndex === 0)
-            return true;
-        // if everything AHEAD of this is a negation, then it's still the "start"
-        const p = this.#parent;
-        for (let i = 0; i < this.#parentIndex; i++) {
-            const pp = p.#parts[i];
-            if (!(pp instanceof AST && pp.type === '!')) {
+    /**
+     * 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.
+     *
+     * Check if a key is in the cache, without updating the recency of
+     * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
+     * to `true` in either the options or the constructor.
+     *
+     * Will return `false` if the item is stale, even though it is technically in
+     * the cache. The difference can be determined (if it matters) by using a
+     * `status` argument, and inspecting the `has` field.
+     *
+     * Will not update item age unless
+     * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
+     */
+    has(k, hasOptions = {}) {
+        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== undefined) {
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v) &&
+                v.__staleWhileFetching === undefined) {
                 return false;
             }
+            if (!this.#isStale(index)) {
+                if (updateAgeOnHas) {
+                    this.#updateItemAge(index);
+                }
+                if (status) {
+                    status.has = 'hit';
+                    this.#statusTTL(status, index);
+                }
+                return true;
+            }
+            else if (status) {
+                status.has = 'stale';
+                this.#statusTTL(status, index);
+            }
         }
-        return true;
-    }
-    isEnd() {
-        if (this.#root === this)
-            return true;
-        if (this.#parent?.type === '!')
-            return true;
-        if (!this.#parent?.isEnd())
-            return false;
-        if (!this.type)
-            return this.#parent?.isEnd();
-        // if not root, it'll always have a parent
-        /* c8 ignore start */
-        const pl = this.#parent ? this.#parent.#parts.length : 0;
-        /* c8 ignore stop */
-        return this.#parentIndex === pl - 1;
-    }
-    copyIn(part) {
-        if (typeof part === 'string')
-            this.push(part);
-        else
-            this.push(part.clone(this));
+        else if (status) {
+            status.has = 'miss';
+        }
+        return false;
     }
-    clone(parent) {
-        const c = new AST(this.type, parent);
-        for (const p of this.#parts) {
-            c.copyIn(p);
+    /**
+     * 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 = {}) {
+        const { allowStale = this.allowStale } = peekOptions;
+        const index = this.#keyMap.get(k);
+        if (index === undefined ||
+            (!allowStale && this.#isStale(index))) {
+            return;
         }
-        return c;
+        const v = this.#valList[index];
+        // either stale and allowed, or forcing a refresh of non-stale value
+        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
     }
-    static #parseAST(str, ast, pos, opt) {
-        let escaping = false;
-        let inBrace = false;
-        let braceStart = -1;
-        let braceNeg = false;
-        if (ast.type === null) {
-            // outside of a extglob, append until we find a start
-            let i = pos;
-            let acc = '';
-            while (i < str.length) {
-                const c = str.charAt(i++);
-                // still accumulate escapes at this point, but we do ignore
-                // starts that are escaped
-                if (escaping || c === '\\') {
-                    escaping = !escaping;
-                    acc += c;
-                    continue;
-                }
-                if (inBrace) {
-                    if (i === braceStart + 1) {
-                        if (c === '^' || c === '!') {
-                            braceNeg = true;
-                        }
-                    }
-                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
-                        inBrace = false;
-                    }
-                    acc += c;
-                    continue;
+    #backgroundFetch(k, index, options, context) {
+        const v = index === undefined ? undefined : this.#valList[index];
+        if (this.#isBackgroundFetch(v)) {
+            return v;
+        }
+        const ac = new AC();
+        const { signal } = options;
+        // when/if our AC signals, then stop listening to theirs.
+        signal?.addEventListener('abort', () => ac.abort(signal.reason), {
+            signal: ac.signal,
+        });
+        const fetchOpts = {
+            signal: ac.signal,
+            options,
+            context,
+        };
+        const cb = (v, updateCache = false) => {
+            const { aborted } = ac.signal;
+            const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
+            if (options.status) {
+                if (aborted && !updateCache) {
+                    options.status.fetchAborted = true;
+                    options.status.fetchError = ac.signal.reason;
+                    if (ignoreAbort)
+                        options.status.fetchAbortIgnored = true;
                 }
-                else if (c === '[') {
-                    inBrace = true;
-                    braceStart = i;
-                    braceNeg = false;
-                    acc += c;
-                    continue;
+                else {
+                    options.status.fetchResolved = true;
                 }
-                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
-                    ast.push(acc);
-                    acc = '';
-                    const ext = new AST(c, ast);
-                    i = AST.#parseAST(str, ext, i, opt);
-                    ast.push(ext);
-                    continue;
+            }
+            if (aborted && !ignoreAbort && !updateCache) {
+                return fetchFail(ac.signal.reason);
+            }
+            // either we didn't abort, and are still here, or we did, and ignored
+            const bf = p;
+            if (this.#valList[index] === p) {
+                if (v === undefined) {
+                    if (bf.__staleWhileFetching) {
+                        this.#valList[index] = bf.__staleWhileFetching;
+                    }
+                    else {
+                        this.#delete(k, 'fetch');
+                    }
+                }
+                else {
+                    if (options.status)
+                        options.status.fetchUpdated = true;
+                    this.set(k, v, fetchOpts.options);
                 }
-                acc += c;
             }
-            ast.push(acc);
-            return i;
-        }
-        // some kind of extglob, pos is at the (
-        // find the next | or )
-        let i = pos + 1;
-        let part = new AST(null, ast);
-        const parts = [];
-        let acc = '';
-        while (i < str.length) {
-            const c = str.charAt(i++);
-            // still accumulate escapes at this point, but we do ignore
-            // starts that are escaped
-            if (escaping || c === '\\') {
-                escaping = !escaping;
-                acc += c;
-                continue;
+            return v;
+        };
+        const eb = (er) => {
+            if (options.status) {
+                options.status.fetchRejected = true;
+                options.status.fetchError = er;
             }
-            if (inBrace) {
-                if (i === braceStart + 1) {
-                    if (c === '^' || c === '!') {
-                        braceNeg = true;
-                    }
+            return fetchFail(er);
+        };
+        const fetchFail = (er) => {
+            const { aborted } = ac.signal;
+            const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
+            const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
+            const noDelete = allowStale || options.noDeleteOnFetchRejection;
+            const bf = p;
+            if (this.#valList[index] === p) {
+                // if we allow stale on fetch rejections, then we need to ensure that
+                // the stale value is not removed from the cache when the fetch fails.
+                const del = !noDelete || bf.__staleWhileFetching === undefined;
+                if (del) {
+                    this.#delete(k, 'fetch');
                 }
-                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
-                    inBrace = false;
+                else if (!allowStaleAborted) {
+                    // still replace the *promise* with the stale value,
+                    // since we are done with the promise at this point.
+                    // leave it untouched if we're still waiting for an
+                    // aborted background fetch that hasn't yet returned.
+                    this.#valList[index] = bf.__staleWhileFetching;
                 }
-                acc += c;
-                continue;
             }
-            else if (c === '[') {
-                inBrace = true;
-                braceStart = i;
-                braceNeg = false;
-                acc += c;
-                continue;
+            if (allowStale) {
+                if (options.status && bf.__staleWhileFetching !== undefined) {
+                    options.status.returnedStale = true;
+                }
+                return bf.__staleWhileFetching;
             }
-            if (isExtglobType(c) && str.charAt(i) === '(') {
-                part.push(acc);
-                acc = '';
-                const ext = new AST(c, part);
-                part.push(ext);
-                i = AST.#parseAST(str, ext, i, opt);
-                continue;
+            else if (bf.__returned === bf) {
+                throw er;
             }
-            if (c === '|') {
-                part.push(acc);
-                acc = '';
-                parts.push(part);
-                part = new AST(null, ast);
-                continue;
+        };
+        const pcall = (res, rej) => {
+            const fmp = this.#fetchMethod?.(k, v, fetchOpts);
+            if (fmp && fmp instanceof Promise) {
+                fmp.then(v => res(v === undefined ? undefined : v), rej);
             }
-            if (c === ')') {
-                if (acc === '' && ast.#parts.length === 0) {
-                    ast.#emptyExt = true;
+            // ignored, we go until we finish, regardless.
+            // defer check until we are actually aborting,
+            // so fetchMethod can override.
+            ac.signal.addEventListener('abort', () => {
+                if (!options.ignoreFetchAbort ||
+                    options.allowStaleOnFetchAbort) {
+                    res(undefined);
+                    // when it eventually resolves, update the cache.
+                    if (options.allowStaleOnFetchAbort) {
+                        res = v => cb(v, true);
+                    }
                 }
-                part.push(acc);
-                acc = '';
-                ast.push(...parts, part);
-                return i;
+            });
+        };
+        if (options.status)
+            options.status.fetchDispatched = true;
+        const p = new Promise(pcall).then(cb, eb);
+        const bf = Object.assign(p, {
+            __abortController: ac,
+            __staleWhileFetching: v,
+            __returned: undefined,
+        });
+        if (index === undefined) {
+            // internal, don't expose status.
+            this.set(k, bf, { ...fetchOpts.options, status: undefined });
+            index = this.#keyMap.get(k);
+        }
+        else {
+            this.#valList[index] = bf;
+        }
+        return bf;
+    }
+    #isBackgroundFetch(p) {
+        if (!this.#hasFetchMethod)
+            return false;
+        const b = p;
+        return (!!b &&
+            b instanceof Promise &&
+            b.hasOwnProperty('__staleWhileFetching') &&
+            b.__abortController instanceof AC);
+    }
+    async fetch(k, fetchOptions = {}) {
+        const { 
+        // 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 = false, status, signal, } = fetchOptions;
+        if (!this.#hasFetchMethod) {
+            if (status)
+                status.fetch = 'get';
+            return this.get(k, {
+                allowStale,
+                updateAgeOnGet,
+                noDeleteOnStaleGet,
+                status,
+            });
+        }
+        const options = {
+            allowStale,
+            updateAgeOnGet,
+            noDeleteOnStaleGet,
+            ttl,
+            noDisposeOnSet,
+            size,
+            sizeCalculation,
+            noUpdateTTL,
+            noDeleteOnFetchRejection,
+            allowStaleOnFetchRejection,
+            allowStaleOnFetchAbort,
+            ignoreFetchAbort,
+            status,
+            signal,
+        };
+        let index = this.#keyMap.get(k);
+        if (index === undefined) {
+            if (status)
+                status.fetch = 'miss';
+            const p = this.#backgroundFetch(k, index, options, context);
+            return (p.__returned = p);
+        }
+        else {
+            // in cache, maybe already fetching
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                const stale = allowStale && v.__staleWhileFetching !== undefined;
+                if (status) {
+                    status.fetch = 'inflight';
+                    if (stale)
+                        status.returnedStale = true;
+                }
+                return stale ? v.__staleWhileFetching : (v.__returned = v);
             }
-            acc += c;
+            // if we force a refresh, that means do NOT serve the cached value,
+            // unless we are already in the process of refreshing the cache.
+            const isStale = this.#isStale(index);
+            if (!forceRefresh && !isStale) {
+                if (status)
+                    status.fetch = 'hit';
+                this.#moveToTail(index);
+                if (updateAgeOnGet) {
+                    this.#updateItemAge(index);
+                }
+                if (status)
+                    this.#statusTTL(status, index);
+                return v;
+            }
+            // ok, it is stale or a forced refresh, and not already fetching.
+            // refresh the cache.
+            const p = this.#backgroundFetch(k, index, options, context);
+            const hasStale = p.__staleWhileFetching !== undefined;
+            const staleVal = hasStale && allowStale;
+            if (status) {
+                status.fetch = isStale ? 'stale' : 'refresh';
+                if (staleVal && isStale)
+                    status.returnedStale = true;
+            }
+            return staleVal ? p.__staleWhileFetching : (p.__returned = p);
         }
-        // unfinished extglob
-        // if we got here, it was a malformed extglob! not an extglob, but
-        // maybe something else in there.
-        ast.type = null;
-        ast.#hasMagic = undefined;
-        ast.#parts = [str.substring(pos - 1)];
-        return i;
     }
-    static fromGlob(pattern, options = {}) {
-        const ast = new AST(null, undefined, options);
-        AST.#parseAST(pattern, ast, 0, options);
-        return ast;
+    async forceFetch(k, fetchOptions = {}) {
+        const v = await this.fetch(k, fetchOptions);
+        if (v === undefined)
+            throw new Error('fetch() returned undefined');
+        return v;
     }
-    // returns the regular expression if there's magic, or the unescaped
-    // string if not.
-    toMMPattern() {
-        // should only be called on root
-        /* c8 ignore start */
-        if (this !== this.#root)
-            return this.#root.toMMPattern();
-        /* c8 ignore stop */
-        const glob = this.toString();
-        const [re, body, hasMagic, uflag] = this.toRegExpSource();
-        // if we're in nocase mode, and not nocaseMagicOnly, then we do
-        // still need a regular expression if we have to case-insensitively
-        // match capital/lowercase characters.
-        const anyMagic = hasMagic ||
-            this.#hasMagic ||
-            (this.#options.nocase &&
-                !this.#options.nocaseMagicOnly &&
-                glob.toUpperCase() !== glob.toLowerCase());
-        if (!anyMagic) {
-            return body;
+    memo(k, memoOptions = {}) {
+        const memoMethod = this.#memoMethod;
+        if (!memoMethod) {
+            throw new Error('no memoMethod provided to constructor');
         }
-        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
-        return Object.assign(new RegExp(`^${re}$`, flags), {
-            _src: re,
-            _glob: glob,
+        const { context, forceRefresh, ...options } = memoOptions;
+        const v = this.get(k, options);
+        if (!forceRefresh && v !== undefined)
+            return v;
+        const vv = memoMethod(k, v, {
+            options,
+            context,
         });
+        this.set(k, vv, options);
+        return vv;
     }
-    get options() {
-        return this.#options;
-    }
-    // returns the string match, the regexp source, whether there's magic
-    // in the regexp (so a regular expression is required) and whether or
-    // not the uflag is needed for the regular expression (for posix classes)
-    // TODO: instead of injecting the start/end at this point, just return
-    // the BODY of the regexp, along with the start/end portions suitable
-    // for binding the start/end in either a joined full-path makeRe context
-    // (where we bind to (^|/), or a standalone matchPart context (where
-    // we bind to ^, and not /).  Otherwise slashes get duped!
-    //
-    // In part-matching mode, the start is:
-    // - if not isStart: nothing
-    // - if traversal possible, but not allowed: ^(?!\.\.?$)
-    // - if dots allowed or not possible: ^
-    // - if dots possible and not allowed: ^(?!\.)
-    // end is:
-    // - if not isEnd(): nothing
-    // - else: $
-    //
-    // In full-path matching mode, we put the slash at the START of the
-    // pattern, so start is:
-    // - if first pattern: same as part-matching mode
-    // - if not isStart(): nothing
-    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
-    // - if dots allowed or not possible: /
-    // - if dots possible and not allowed: /(?!\.)
-    // end is:
-    // - if last pattern, same as part-matching mode
-    // - else nothing
-    //
-    // Always put the (?:$|/) on negated tails, though, because that has to be
-    // there to bind the end of the negated pattern portion, and it's easier to
-    // just stick it in now rather than try to inject it later in the middle of
-    // the pattern.
-    //
-    // We can just always return the same end, and leave it up to the caller
-    // to know whether it's going to be used joined or in parts.
-    // And, if the start is adjusted slightly, can do the same there:
-    // - if not isStart: nothing
-    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
-    // - if dots allowed or not possible: (?:/|^)
-    // - if dots possible and not allowed: (?:/|^)(?!\.)
-    //
-    // But it's better to have a simpler binding without a conditional, for
-    // performance, so probably better to return both start options.
-    //
-    // Then the caller just ignores the end if it's not the first pattern,
-    // and the start always gets applied.
-    //
-    // But that's always going to be $ if it's the ending pattern, or nothing,
-    // so the caller can just attach $ at the end of the pattern when building.
-    //
-    // So the todo is:
-    // - better detect what kind of start is needed
-    // - return both flavors of starting pattern
-    // - attach $ at the end of the pattern when creating the actual RegExp
-    //
-    // Ah, but wait, no, that all only applies to the root when the first pattern
-    // is not an extglob. If the first pattern IS an extglob, then we need all
-    // that dot prevention biz to live in the extglob portions, because eg
-    // +(*|.x*) can match .xy but not .yx.
-    //
-    // So, return the two flavors if it's #root and the first child is not an
-    // AST, otherwise leave it to the child AST to handle it, and there,
-    // use the (?:^|/) style of start binding.
-    //
-    // Even simplified further:
-    // - Since the start for a join is eg /(?!\.) and the start for a part
-    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
-    // or start or whatever) and prepend ^ or / at the Regexp construction.
-    toRegExpSource(allowDot) {
-        const dot = allowDot ?? !!this.#options.dot;
-        if (this.#root === this)
-            this.#fillNegs();
-        if (!this.type) {
-            const noEmpty = this.isStart() && this.isEnd();
-            const src = this.#parts
-                .map(p => {
-                const [re, _, hasMagic, uflag] = typeof p === 'string'
-                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
-                    : p.toRegExpSource(allowDot);
-                this.#hasMagic = this.#hasMagic || hasMagic;
-                this.#uflag = this.#uflag || uflag;
-                return re;
-            })
-                .join('');
-            let start = '';
-            if (this.isStart()) {
-                if (typeof this.#parts[0] === 'string') {
-                    // this is the string that will match the start of the pattern,
-                    // so we need to protect against dots and such.
-                    // '.' and '..' cannot match unless the pattern is that exactly,
-                    // even if it starts with . or dot:true is set.
-                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
-                    if (!dotTravAllowed) {
-                        const aps = addPatternStart;
-                        // check if we have a possibility of matching . or ..,
-                        // and prevent that.
-                        const needNoTrav = 
-                        // dots are allowed, and the pattern starts with [ or .
-                        (dot && aps.has(src.charAt(0))) ||
-                            // the pattern starts with \., and then [ or .
-                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
-                            // the pattern starts with \.\., and then [ or .
-                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
-                        // no need to prevent dots if it can't match a dot, or if a
-                        // sub-pattern will be preventing it anyway.
-                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
-                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
+    /**
+     * 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 = {}) {
+        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== undefined) {
+            const value = this.#valList[index];
+            const fetching = this.#isBackgroundFetch(value);
+            if (status)
+                this.#statusTTL(status, index);
+            if (this.#isStale(index)) {
+                if (status)
+                    status.get = 'stale';
+                // delete only if not an in-flight background fetch
+                if (!fetching) {
+                    if (!noDeleteOnStaleGet) {
+                        this.#delete(k, 'expire');
                     }
+                    if (status && allowStale)
+                        status.returnedStale = true;
+                    return allowStale ? value : undefined;
+                }
+                else {
+                    if (status &&
+                        allowStale &&
+                        value.__staleWhileFetching !== undefined) {
+                        status.returnedStale = true;
+                    }
+                    return allowStale ? value.__staleWhileFetching : undefined;
                 }
             }
-            // append the "end of path portion" pattern to negation tails
-            let end = '';
-            if (this.isEnd() &&
-                this.#root.#filledNegs &&
-                this.#parent?.type === '!') {
-                end = '(?:$|\\/)';
+            else {
+                if (status)
+                    status.get = 'hit';
+                // if we're currently fetching it, we don't actually have it yet
+                // it's not stale, which means this isn't a staleWhileRefetching.
+                // If it's not stale, and fetching, AND has a __staleWhileFetching
+                // value, then that means the user fetched with {forceRefresh:true},
+                // so it's safe to return that value.
+                if (fetching) {
+                    return value.__staleWhileFetching;
+                }
+                this.#moveToTail(index);
+                if (updateAgeOnGet) {
+                    this.#updateItemAge(index);
+                }
+                return value;
             }
-            const final = start + src + end;
-            return [
-                final,
-                (0, unescape_js_1.unescape)(src),
-                (this.#hasMagic = !!this.#hasMagic),
-                this.#uflag,
-            ];
-        }
-        // We need to calculate the body *twice* if it's a repeat pattern
-        // at the start, once in nodot mode, then again in dot mode, so a
-        // pattern like *(?) can match 'x.y'
-        const repeated = this.type === '*' || this.type === '+';
-        // some kind of extglob
-        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
-        let body = this.#partsToRegExp(dot);
-        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
-            // invalid extglob, has to at least be *something* present, if it's
-            // the entire path portion.
-            const s = this.toString();
-            this.#parts = [s];
-            this.type = null;
-            this.#hasMagic = undefined;
-            return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
-        }
-        // XXX abstract out this map method
-        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
-            ? ''
-            : this.#partsToRegExp(true);
-        if (bodyDotAllowed === body) {
-            bodyDotAllowed = '';
-        }
-        if (bodyDotAllowed) {
-            body = `(?:${body})(?:${bodyDotAllowed})*?`;
         }
-        // an empty !() is exactly equivalent to a starNoEmpty
-        let final = '';
-        if (this.type === '!' && this.#emptyExt) {
-            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
+        else if (status) {
+            status.get = 'miss';
         }
-        else {
-            const close = this.type === '!'
-                ? // !() must match something,but !(x) can match ''
-                    '))' +
-                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
-                        star +
-                        ')'
-                : this.type === '@'
-                    ? ')'
-                    : this.type === '?'
-                        ? ')?'
-                        : this.type === '+' && bodyDotAllowed
-                            ? ')'
-                            : this.type === '*' && bodyDotAllowed
-                                ? `)?`
-                                : `)${this.type}`;
-            final = start + body + close;
+    }
+    #connect(p, n) {
+        this.#prev[n] = p;
+        this.#next[p] = n;
+    }
+    #moveToTail(index) {
+        // if tail already, nothing to do
+        // if head, move head to next[index]
+        // else
+        //   move next[prev[index]] to next[index] (head has no prev)
+        //   move prev[next[index]] to prev[index]
+        // prev[index] = tail
+        // next[tail] = index
+        // tail = index
+        if (index !== this.#tail) {
+            if (index === this.#head) {
+                this.#head = this.#next[index];
+            }
+            else {
+                this.#connect(this.#prev[index], this.#next[index]);
+            }
+            this.#connect(this.#tail, index);
+            this.#tail = index;
         }
-        return [
-            final,
-            (0, unescape_js_1.unescape)(body),
-            (this.#hasMagic = !!this.#hasMagic),
-            this.#uflag,
-        ];
     }
-    #partsToRegExp(dot) {
-        return this.#parts
-            .map(p => {
-            // extglob ASTs should only contain parent ASTs
-            /* c8 ignore start */
-            if (typeof p === 'string') {
-                throw new Error('string type in extglob ast??');
-            }
-            /* c8 ignore stop */
-            // can ignore hasMagic, because extglobs are already always magic
-            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
-            this.#uflag = this.#uflag || uflag;
-            return re;
-        })
-            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
-            .join('|');
+    /**
+     * Deletes a key out of the cache.
+     *
+     * Returns true if the key was deleted, false otherwise.
+     */
+    delete(k) {
+        return this.#delete(k, 'delete');
     }
-    static #parseGlob(glob, hasMagic, noEmpty = false) {
-        let escaping = false;
-        let re = '';
-        let uflag = false;
-        for (let i = 0; i < glob.length; i++) {
-            const c = glob.charAt(i);
-            if (escaping) {
-                escaping = false;
-                re += (reSpecials.has(c) ? '\\' : '') + c;
-                continue;
-            }
-            if (c === '\\') {
-                if (i === glob.length - 1) {
-                    re += '\\\\';
+    #delete(k, reason) {
+        let deleted = false;
+        if (this.#size !== 0) {
+            const index = this.#keyMap.get(k);
+            if (index !== undefined) {
+                deleted = true;
+                if (this.#size === 1) {
+                    this.#clear(reason);
                 }
                 else {
-                    escaping = true;
+                    this.#removeItemSize(index);
+                    const v = this.#valList[index];
+                    if (this.#isBackgroundFetch(v)) {
+                        v.__abortController.abort(new Error('deleted'));
+                    }
+                    else if (this.#hasDispose || this.#hasDisposeAfter) {
+                        if (this.#hasDispose) {
+                            this.#dispose?.(v, k, reason);
+                        }
+                        if (this.#hasDisposeAfter) {
+                            this.#disposed?.push([v, k, reason]);
+                        }
+                    }
+                    this.#keyMap.delete(k);
+                    this.#keyList[index] = undefined;
+                    this.#valList[index] = undefined;
+                    if (index === this.#tail) {
+                        this.#tail = this.#prev[index];
+                    }
+                    else if (index === this.#head) {
+                        this.#head = this.#next[index];
+                    }
+                    else {
+                        const pi = this.#prev[index];
+                        this.#next[pi] = this.#next[index];
+                        const ni = this.#next[index];
+                        this.#prev[ni] = this.#prev[index];
+                    }
+                    this.#size--;
+                    this.#free.push(index);
                 }
-                continue;
             }
-            if (c === '[') {
-                const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
-                if (consumed) {
-                    re += src;
-                    uflag = uflag || needUflag;
-                    i += consumed - 1;
-                    hasMagic = hasMagic || magic;
-                    continue;
-                }
+        }
+        if (this.#hasDisposeAfter && this.#disposed?.length) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
-            if (c === '*') {
-                if (noEmpty && glob === '*')
-                    re += starNoEmpty;
-                else
-                    re += star;
-                hasMagic = true;
-                continue;
+        }
+        return deleted;
+    }
+    /**
+     * Clear the cache entirely, throwing away all values.
+     */
+    clear() {
+        return this.#clear('delete');
+    }
+    #clear(reason) {
+        for (const index of this.#rindexes({ allowStale: true })) {
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                v.__abortController.abort(new Error('deleted'));
             }
-            if (c === '?') {
-                re += qmark;
-                hasMagic = true;
-                continue;
+            else {
+                const k = this.#keyList[index];
+                if (this.#hasDispose) {
+                    this.#dispose?.(v, k, reason);
+                }
+                if (this.#hasDisposeAfter) {
+                    this.#disposed?.push([v, k, reason]);
+                }
+            }
+        }
+        this.#keyMap.clear();
+        this.#valList.fill(undefined);
+        this.#keyList.fill(undefined);
+        if (this.#ttls && this.#starts) {
+            this.#ttls.fill(0);
+            this.#starts.fill(0);
+        }
+        if (this.#sizes) {
+            this.#sizes.fill(0);
+        }
+        this.#head = 0;
+        this.#tail = 0;
+        this.#free.length = 0;
+        this.#calculatedSize = 0;
+        this.#size = 0;
+        if (this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
             }
-            re += regExpEscape(c);
         }
-        return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
     }
 }
-exports.AST = AST;
-//# sourceMappingURL=ast.js.map
+exports.LRUCache = LRUCache;
+//# sourceMappingURL=index.js.map
 
 /***/ }),
 
-/***/ 34796:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 81017:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-// translate the various posix character classes into unicode properties
-// this works across all unicode locales
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseClass = void 0;
-// { : [, /u flag required, negated]
-const posixClasses = {
-    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
-    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
-    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
-    '[:blank:]': ['\\p{Zs}\\t', true],
-    '[:cntrl:]': ['\\p{Cc}', true],
-    '[:digit:]': ['\\p{Nd}', true],
-    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
-    '[:lower:]': ['\\p{Ll}', true],
-    '[:print:]': ['\\p{C}', true],
-    '[:punct:]': ['\\p{P}', true],
-    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
-    '[:upper:]': ['\\p{Lu}', true],
-    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
-    '[:xdigit:]': ['A-Fa-f0-9', false],
-};
-// only need to escape a few things inside of brace expressions
-// escapes: [ \ ] -
-const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
-// escape all regexp magic characters
-const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-// everything has already been escaped, we just have to join
-const rangesToString = (ranges) => ranges.join('');
-// takes a glob string at a posix brace expression, and returns
-// an equivalent regular expression source, and boolean indicating
-// whether the /u flag needs to be applied, and the number of chars
-// consumed to parse the character class.
-// This also removes out of order ranges, and returns ($.) if the
-// entire class just no good.
-const parseClass = (glob, position) => {
-    const pos = position;
-    /* c8 ignore start */
-    if (glob.charAt(pos) !== '[') {
-        throw new Error('not in a brace expression');
-    }
-    /* c8 ignore stop */
-    const ranges = [];
-    const negs = [];
-    let i = pos + 1;
-    let sawStart = false;
-    let uflag = false;
-    let escaping = false;
-    let negate = false;
-    let endPos = pos;
-    let rangeStart = '';
-    WHILE: while (i < glob.length) {
-        const c = glob.charAt(i);
-        if ((c === '!' || c === '^') && i === pos + 1) {
-            negate = true;
-            i++;
-            continue;
+exports.Glob = void 0;
+const minimatch_1 = __nccwpck_require__(85207);
+const node_url_1 = __nccwpck_require__(73136);
+const path_scurry_1 = __nccwpck_require__(16577);
+const pattern_js_1 = __nccwpck_require__(4041);
+const walker_js_1 = __nccwpck_require__(95049);
+// if no process global, just call it linux.
+// so we default to case-sensitive, / separators
+const defaultPlatform = (typeof process === 'object' &&
+    process &&
+    typeof process.platform === 'string') ?
+    process.platform
+    : 'linux';
+/**
+ * An object that can perform glob pattern traversals.
+ */
+class Glob {
+    absolute;
+    cwd;
+    root;
+    dot;
+    dotRelative;
+    follow;
+    ignore;
+    magicalBraces;
+    mark;
+    matchBase;
+    maxDepth;
+    nobrace;
+    nocase;
+    nodir;
+    noext;
+    noglobstar;
+    pattern;
+    platform;
+    realpath;
+    scurry;
+    stat;
+    signal;
+    windowsPathsNoEscape;
+    withFileTypes;
+    includeChildMatches;
+    /**
+     * The options provided to the constructor.
+     */
+    opts;
+    /**
+     * An array of parsed immutable {@link Pattern} objects.
+     */
+    patterns;
+    /**
+     * All options are stored as properties on the `Glob` object.
+     *
+     * See {@link GlobOptions} for full options descriptions.
+     *
+     * Note that a previous `Glob` object can be passed as the
+     * `GlobOptions` to another `Glob` instantiation to re-use settings
+     * and caches with a new pattern.
+     *
+     * Traversal functions can be called multiple times to run the walk
+     * again.
+     */
+    constructor(pattern, opts) {
+        /* c8 ignore start */
+        if (!opts)
+            throw new TypeError('glob options required');
+        /* c8 ignore stop */
+        this.withFileTypes = !!opts.withFileTypes;
+        this.signal = opts.signal;
+        this.follow = !!opts.follow;
+        this.dot = !!opts.dot;
+        this.dotRelative = !!opts.dotRelative;
+        this.nodir = !!opts.nodir;
+        this.mark = !!opts.mark;
+        if (!opts.cwd) {
+            this.cwd = '';
         }
-        if (c === ']' && sawStart && !escaping) {
-            endPos = i + 1;
-            break;
+        else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {
+            opts.cwd = (0, node_url_1.fileURLToPath)(opts.cwd);
         }
-        sawStart = true;
-        if (c === '\\') {
-            if (!escaping) {
-                escaping = true;
-                i++;
-                continue;
-            }
-            // escaped \ char, fall through and treat like normal char
+        this.cwd = opts.cwd || '';
+        this.root = opts.root;
+        this.magicalBraces = !!opts.magicalBraces;
+        this.nobrace = !!opts.nobrace;
+        this.noext = !!opts.noext;
+        this.realpath = !!opts.realpath;
+        this.absolute = opts.absolute;
+        this.includeChildMatches = opts.includeChildMatches !== false;
+        this.noglobstar = !!opts.noglobstar;
+        this.matchBase = !!opts.matchBase;
+        this.maxDepth =
+            typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity;
+        this.stat = !!opts.stat;
+        this.ignore = opts.ignore;
+        if (this.withFileTypes && this.absolute !== undefined) {
+            throw new Error('cannot set absolute and withFileTypes:true');
         }
-        if (c === '[' && !escaping) {
-            // either a posix class, a collation equivalent, or just a [
-            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
-                if (glob.startsWith(cls, i)) {
-                    // invalid, [a-[] is fine, but not [a-[:alpha]]
-                    if (rangeStart) {
-                        return ['$.', false, glob.length - pos, true];
-                    }
-                    i += cls.length;
-                    if (neg)
-                        negs.push(unip);
-                    else
-                        ranges.push(unip);
-                    uflag = uflag || u;
-                    continue WHILE;
-                }
-            }
+        if (typeof pattern === 'string') {
+            pattern = [pattern];
         }
-        // now it's just a normal character, effectively
-        escaping = false;
-        if (rangeStart) {
-            // throw this range away if it's not valid, but others
-            // can still match.
-            if (c > rangeStart) {
-                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
-            }
-            else if (c === rangeStart) {
-                ranges.push(braceEscape(c));
+        this.windowsPathsNoEscape =
+            !!opts.windowsPathsNoEscape ||
+                opts.allowWindowsEscape ===
+                    false;
+        if (this.windowsPathsNoEscape) {
+            pattern = pattern.map(p => p.replace(/\\/g, '/'));
+        }
+        if (this.matchBase) {
+            if (opts.noglobstar) {
+                throw new TypeError('base matching requires globstar');
             }
-            rangeStart = '';
-            i++;
-            continue;
+            pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`));
         }
-        // now might be the start of a range.
-        // can be either c-d or c-] or c] or c] at this point
-        if (glob.startsWith('-]', i + 1)) {
-            ranges.push(braceEscape(c + '-'));
-            i += 2;
-            continue;
+        this.pattern = pattern;
+        this.platform = opts.platform || defaultPlatform;
+        this.opts = { ...opts, platform: this.platform };
+        if (opts.scurry) {
+            this.scurry = opts.scurry;
+            if (opts.nocase !== undefined &&
+                opts.nocase !== opts.scurry.nocase) {
+                throw new Error('nocase option contradicts provided scurry option');
+            }
         }
-        if (glob.startsWith('-', i + 1)) {
-            rangeStart = c;
-            i += 2;
-            continue;
+        else {
+            const Scurry = opts.platform === 'win32' ? path_scurry_1.PathScurryWin32
+                : opts.platform === 'darwin' ? path_scurry_1.PathScurryDarwin
+                    : opts.platform ? path_scurry_1.PathScurryPosix
+                        : path_scurry_1.PathScurry;
+            this.scurry = new Scurry(this.cwd, {
+                nocase: opts.nocase,
+                fs: opts.fs,
+            });
         }
-        // not the start of a range, just a single character
-        ranges.push(braceEscape(c));
-        i++;
+        this.nocase = this.scurry.nocase;
+        // If you do nocase:true on a case-sensitive file system, then
+        // we need to use regexps instead of strings for non-magic
+        // path portions, because statting `aBc` won't return results
+        // for the file `AbC` for example.
+        const nocaseMagicOnly = this.platform === 'darwin' || this.platform === 'win32';
+        const mmo = {
+            // default nocase based on platform
+            ...opts,
+            dot: this.dot,
+            matchBase: this.matchBase,
+            nobrace: this.nobrace,
+            nocase: this.nocase,
+            nocaseMagicOnly,
+            nocomment: true,
+            noext: this.noext,
+            nonegate: true,
+            optimizationLevel: 2,
+            platform: this.platform,
+            windowsPathsNoEscape: this.windowsPathsNoEscape,
+            debug: !!this.opts.debug,
+        };
+        const mms = this.pattern.map(p => new minimatch_1.Minimatch(p, mmo));
+        const [matchSet, globParts] = mms.reduce((set, m) => {
+            set[0].push(...m.set);
+            set[1].push(...m.globParts);
+            return set;
+        }, [[], []]);
+        this.patterns = matchSet.map((set, i) => {
+            const g = globParts[i];
+            /* c8 ignore start */
+            if (!g)
+                throw new Error('invalid pattern object');
+            /* c8 ignore stop */
+            return new pattern_js_1.Pattern(set, g, 0, this.platform);
+        });
     }
-    if (endPos < i) {
-        // didn't see the end of the class, not a valid class,
-        // but might still be valid as a literal match.
-        return ['', false, 0, false];
+    async walk() {
+        // Walkers always return array of Path objects, so we just have to
+        // coerce them into the right shape.  It will have already called
+        // realpath() if the option was set to do so, so we know that's cached.
+        // start out knowing the cwd, at least
+        return [
+            ...(await new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
+                ...this.opts,
+                maxDepth: this.maxDepth !== Infinity ?
+                    this.maxDepth + this.scurry.cwd.depth()
+                    : Infinity,
+                platform: this.platform,
+                nocase: this.nocase,
+                includeChildMatches: this.includeChildMatches,
+            }).walk()),
+        ];
     }
-    // if we got no ranges and no negates, then we have a range that
-    // cannot possibly match anything, and that poisons the whole glob
-    if (!ranges.length && !negs.length) {
-        return ['$.', false, glob.length - pos, true];
+    walkSync() {
+        return [
+            ...new walker_js_1.GlobWalker(this.patterns, this.scurry.cwd, {
+                ...this.opts,
+                maxDepth: this.maxDepth !== Infinity ?
+                    this.maxDepth + this.scurry.cwd.depth()
+                    : Infinity,
+                platform: this.platform,
+                nocase: this.nocase,
+                includeChildMatches: this.includeChildMatches,
+            }).walkSync(),
+        ];
     }
-    // if we got one positive range, and it's a single character, then that's
-    // not actually a magic pattern, it's just that one literal character.
-    // we should not treat that as "magic", we should just return the literal
-    // character. [_] is a perfectly valid way to escape glob magic chars.
-    if (negs.length === 0 &&
-        ranges.length === 1 &&
-        /^\\?.$/.test(ranges[0]) &&
-        !negate) {
-        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
-        return [regexpEscape(r), false, endPos - pos, false];
+    stream() {
+        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
+            ...this.opts,
+            maxDepth: this.maxDepth !== Infinity ?
+                this.maxDepth + this.scurry.cwd.depth()
+                : Infinity,
+            platform: this.platform,
+            nocase: this.nocase,
+            includeChildMatches: this.includeChildMatches,
+        }).stream();
+    }
+    streamSync() {
+        return new walker_js_1.GlobStream(this.patterns, this.scurry.cwd, {
+            ...this.opts,
+            maxDepth: this.maxDepth !== Infinity ?
+                this.maxDepth + this.scurry.cwd.depth()
+                : Infinity,
+            platform: this.platform,
+            nocase: this.nocase,
+            includeChildMatches: this.includeChildMatches,
+        }).streamSync();
+    }
+    /**
+     * Default sync iteration function. Returns a Generator that
+     * iterates over the results.
+     */
+    iterateSync() {
+        return this.streamSync()[Symbol.iterator]();
+    }
+    [Symbol.iterator]() {
+        return this.iterateSync();
+    }
+    /**
+     * Default async iteration function. Returns an AsyncGenerator that
+     * iterates over the results.
+     */
+    iterate() {
+        return this.stream()[Symbol.asyncIterator]();
     }
-    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
-    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
-    const comb = ranges.length && negs.length
-        ? '(' + sranges + '|' + snegs + ')'
-        : ranges.length
-            ? sranges
-            : snegs;
-    return [comb, uflag, endPos - pos, true];
-};
-exports.parseClass = parseClass;
-//# sourceMappingURL=brace-expressions.js.map
+    [Symbol.asyncIterator]() {
+        return this.iterate();
+    }
+}
+exports.Glob = Glob;
+//# sourceMappingURL=glob.js.map
 
 /***/ }),
 
-/***/ 4578:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 66889:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.escape = void 0;
+exports.hasMagic = void 0;
+const minimatch_1 = __nccwpck_require__(85207);
 /**
- * Escape all magic characters in a glob pattern.
+ * Return true if the patterns provided contain any magic glob characters,
+ * given the options provided.
  *
- * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
- * option is used, then characters are escaped by wrapping in `[]`, because
- * a magic character wrapped in a character class can only be satisfied by
- * that exact character.  In this mode, `\` is _not_ escaped, because it is
- * not interpreted as a magic character, but instead as a path separator.
+ * Brace expansion is not considered "magic" unless the `magicalBraces` option
+ * is set, as brace expansion just turns one string into an array of strings.
+ * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and
+ * `'xby'` both do not contain any magic glob characters, and it's treated the
+ * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`
+ * is in the options, brace expansion _is_ treated as a pattern having magic.
  */
-const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
-    // don't need to escape +@! because we escape the parens
-    // that make those magic, and escaping ! as [!] isn't valid,
-    // because [!]] is a valid glob class meaning not ']'.
-    return windowsPathsNoEscape
-        ? s.replace(/[?*()[\]]/g, '[$&]')
-        : s.replace(/[?*()[\]\\]/g, '\\$&');
+const hasMagic = (pattern, options = {}) => {
+    if (!Array.isArray(pattern)) {
+        pattern = [pattern];
+    }
+    for (const p of pattern) {
+        if (new minimatch_1.Minimatch(p, options).hasMagic())
+            return true;
+    }
+    return false;
 };
-exports.escape = escape;
-//# sourceMappingURL=escape.js.map
+exports.hasMagic = hasMagic;
+//# sourceMappingURL=has-magic.js.map
 
 /***/ }),
 
-/***/ 45613:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+/***/ 4833:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
 
 "use strict";
 
-var __importDefault = (this && this.__importDefault) || function (mod) {
-    return (mod && mod.__esModule) ? mod : { "default": mod };
-};
+// give it a pattern, and it'll be able to tell you if
+// a given path should be ignored.
+// Ignoring a path ignores its children if the pattern ends in /**
+// Ignores are always parsed in dot:true mode
 Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0;
-const brace_expansion_1 = __importDefault(__nccwpck_require__(66723));
-const assert_valid_pattern_js_1 = __nccwpck_require__(33555);
-const ast_js_1 = __nccwpck_require__(10421);
-const escape_js_1 = __nccwpck_require__(4578);
-const unescape_js_1 = __nccwpck_require__(11633);
-const minimatch = (p, pattern, options = {}) => {
-    (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-    // shortcut: comments match nothing.
-    if (!options.nocomment && pattern.charAt(0) === '#') {
-        return false;
-    }
-    return new Minimatch(pattern, options).match(p);
-};
-exports.minimatch = minimatch;
-// Optimized checking for the most common glob patterns.
-const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
-const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
-const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
-const starDotExtTestNocase = (ext) => {
-    ext = ext.toLowerCase();
-    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
-};
-const starDotExtTestNocaseDot = (ext) => {
-    ext = ext.toLowerCase();
-    return (f) => f.toLowerCase().endsWith(ext);
-};
-const starDotStarRE = /^\*+\.\*+$/;
-const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
-const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
-const dotStarRE = /^\.\*+$/;
-const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
-const starRE = /^\*+$/;
-const starTest = (f) => f.length !== 0 && !f.startsWith('.');
-const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
-const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
-const qmarksTestNocase = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExt([$0]);
-    if (!ext)
-        return noext;
-    ext = ext.toLowerCase();
-    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
-};
-const qmarksTestNocaseDot = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExtDot([$0]);
-    if (!ext)
-        return noext;
-    ext = ext.toLowerCase();
-    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
-};
-const qmarksTestDot = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExtDot([$0]);
-    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
-};
-const qmarksTest = ([$0, ext = '']) => {
-    const noext = qmarksTestNoExt([$0]);
-    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
-};
-const qmarksTestNoExt = ([$0]) => {
-    const len = $0.length;
-    return (f) => f.length === len && !f.startsWith('.');
-};
-const qmarksTestNoExtDot = ([$0]) => {
-    const len = $0.length;
-    return (f) => f.length === len && f !== '.' && f !== '..';
-};
-/* c8 ignore start */
-const defaultPlatform = (typeof process === 'object' && process
-    ? (typeof process.env === 'object' &&
-        process.env &&
-        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
-        process.platform
-    : 'posix');
-const path = {
-    win32: { sep: '\\' },
-    posix: { sep: '/' },
-};
-/* c8 ignore stop */
-exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
-exports.minimatch.sep = exports.sep;
-exports.GLOBSTAR = Symbol('globstar **');
-exports.minimatch.GLOBSTAR = exports.GLOBSTAR;
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-const qmark = '[^/]';
-// * => any number of characters
-const star = qmark + '*?';
-// ** when dots are allowed.  Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
-const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options);
-exports.filter = filter;
-exports.minimatch.filter = exports.filter;
-const ext = (a, b = {}) => Object.assign({}, a, b);
-const defaults = (def) => {
-    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
-        return exports.minimatch;
+exports.Ignore = void 0;
+const minimatch_1 = __nccwpck_require__(85207);
+const pattern_js_1 = __nccwpck_require__(4041);
+const defaultPlatform = (typeof process === 'object' &&
+    process &&
+    typeof process.platform === 'string') ?
+    process.platform
+    : 'linux';
+/**
+ * Class used to process ignored patterns
+ */
+class Ignore {
+    relative;
+    relativeChildren;
+    absolute;
+    absoluteChildren;
+    platform;
+    mmopts;
+    constructor(ignored, { nobrace, nocase, noext, noglobstar, platform = defaultPlatform, }) {
+        this.relative = [];
+        this.absolute = [];
+        this.relativeChildren = [];
+        this.absoluteChildren = [];
+        this.platform = platform;
+        this.mmopts = {
+            dot: true,
+            nobrace,
+            nocase,
+            noext,
+            noglobstar,
+            optimizationLevel: 2,
+            platform,
+            nocomment: true,
+            nonegate: true,
+        };
+        for (const ign of ignored)
+            this.add(ign);
     }
-    const orig = exports.minimatch;
-    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
-    return Object.assign(m, {
-        Minimatch: class Minimatch extends orig.Minimatch {
-            constructor(pattern, options = {}) {
-                super(pattern, ext(def, options));
-            }
-            static defaults(options) {
-                return orig.defaults(ext(def, options)).Minimatch;
-            }
-        },
-        AST: class AST extends orig.AST {
+    add(ign) {
+        // this is a little weird, but it gives us a clean set of optimized
+        // minimatch matchers, without getting tripped up if one of them
+        // ends in /** inside a brace section, and it's only inefficient at
+        // the start of the walk, not along it.
+        // It'd be nice if the Pattern class just had a .test() method, but
+        // handling globstars is a bit of a pita, and that code already lives
+        // in minimatch anyway.
+        // Another way would be if maybe Minimatch could take its set/globParts
+        // as an option, and then we could at least just use Pattern to test
+        // for absolute-ness.
+        // Yet another way, Minimatch could take an array of glob strings, and
+        // a cwd option, and do the right thing.
+        const mm = new minimatch_1.Minimatch(ign, this.mmopts);
+        for (let i = 0; i < mm.set.length; i++) {
+            const parsed = mm.set[i];
+            const globParts = mm.globParts[i];
             /* c8 ignore start */
-            constructor(type, parent, options = {}) {
-                super(type, parent, ext(def, options));
+            if (!parsed || !globParts) {
+                throw new Error('invalid pattern object');
+            }
+            // strip off leading ./ portions
+            // https://github.com/isaacs/node-glob/issues/570
+            while (parsed[0] === '.' && globParts[0] === '.') {
+                parsed.shift();
+                globParts.shift();
             }
             /* c8 ignore stop */
-            static fromGlob(pattern, options = {}) {
-                return orig.AST.fromGlob(pattern, ext(def, options));
+            const p = new pattern_js_1.Pattern(parsed, globParts, 0, this.platform);
+            const m = new minimatch_1.Minimatch(p.globString(), this.mmopts);
+            const children = globParts[globParts.length - 1] === '**';
+            const absolute = p.isAbsolute();
+            if (absolute)
+                this.absolute.push(m);
+            else
+                this.relative.push(m);
+            if (children) {
+                if (absolute)
+                    this.absoluteChildren.push(m);
+                else
+                    this.relativeChildren.push(m);
             }
-        },
-        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
-        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
-        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
-        defaults: (options) => orig.defaults(ext(def, options)),
-        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
-        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
-        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
-        sep: orig.sep,
-        GLOBSTAR: exports.GLOBSTAR,
-    });
-};
-exports.defaults = defaults;
-exports.minimatch.defaults = exports.defaults;
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-const braceExpand = (pattern, options = {}) => {
-    (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-    // Thanks to Yeting Li  for
-    // improving this regexp to avoid a ReDOS vulnerability.
-    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
-        // shortcut. no need to expand.
-        return [pattern];
-    }
-    return (0, brace_expansion_1.default)(pattern);
-};
-exports.braceExpand = braceExpand;
-exports.minimatch.braceExpand = exports.braceExpand;
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion.  Otherwise, any series
-// of * is equivalent to a single *.  Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
-exports.makeRe = makeRe;
-exports.minimatch.makeRe = exports.makeRe;
-const match = (list, pattern, options = {}) => {
-    const mm = new Minimatch(pattern, options);
-    list = list.filter(f => mm.match(f));
-    if (mm.options.nonull && !list.length) {
-        list.push(pattern);
+        }
     }
-    return list;
-};
-exports.match = match;
-exports.minimatch.match = exports.match;
-// replace stuff like \* with *
-const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
-const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
-class Minimatch {
-    options;
-    set;
-    pattern;
-    windowsPathsNoEscape;
-    nonegate;
-    negate;
-    comment;
-    empty;
-    preserveMultipleSlashes;
-    partial;
-    globSet;
-    globParts;
-    nocase;
-    isWindows;
-    platform;
-    windowsNoMagicRoot;
-    regexp;
-    constructor(pattern, options = {}) {
-        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-        options = options || {};
-        this.options = options;
-        this.pattern = pattern;
-        this.platform = options.platform || defaultPlatform;
-        this.isWindows = this.platform === 'win32';
-        this.windowsPathsNoEscape =
-            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
-        if (this.windowsPathsNoEscape) {
-            this.pattern = this.pattern.replace(/\\/g, '/');
+    ignored(p) {
+        const fullpath = p.fullpath();
+        const fullpaths = `${fullpath}/`;
+        const relative = p.relative() || '.';
+        const relatives = `${relative}/`;
+        for (const m of this.relative) {
+            if (m.match(relative) || m.match(relatives))
+                return true;
         }
-        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
-        this.regexp = null;
-        this.negate = false;
-        this.nonegate = !!options.nonegate;
-        this.comment = false;
-        this.empty = false;
-        this.partial = !!options.partial;
-        this.nocase = !!this.options.nocase;
-        this.windowsNoMagicRoot =
-            options.windowsNoMagicRoot !== undefined
-                ? options.windowsNoMagicRoot
-                : !!(this.isWindows && this.nocase);
-        this.globSet = [];
-        this.globParts = [];
-        this.set = [];
-        // make the set of regexps etc.
-        this.make();
+        for (const m of this.absolute) {
+            if (m.match(fullpath) || m.match(fullpaths))
+                return true;
+        }
+        return false;
     }
-    hasMagic() {
-        if (this.options.magicalBraces && this.set.length > 1) {
-            return true;
+    childrenIgnored(p) {
+        const fullpath = p.fullpath() + '/';
+        const relative = (p.relative() || '.') + '/';
+        for (const m of this.relativeChildren) {
+            if (m.match(relative))
+                return true;
         }
-        for (const pattern of this.set) {
-            for (const part of pattern) {
-                if (typeof part !== 'string')
-                    return true;
-            }
+        for (const m of this.absoluteChildren) {
+            if (m.match(fullpath))
+                return true;
         }
         return false;
     }
-    debug(..._) { }
-    make() {
-        const pattern = this.pattern;
-        const options = this.options;
-        // empty patterns and comments match nothing.
-        if (!options.nocomment && pattern.charAt(0) === '#') {
-            this.comment = true;
-            return;
+}
+exports.Ignore = Ignore;
+//# sourceMappingURL=ignore.js.map
+
+/***/ }),
+
+/***/ 67471:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.glob = exports.sync = exports.iterate = exports.iterateSync = exports.stream = exports.streamSync = exports.Ignore = exports.hasMagic = exports.Glob = exports.unescape = exports.escape = void 0;
+exports.globStreamSync = globStreamSync;
+exports.globStream = globStream;
+exports.globSync = globSync;
+exports.globIterateSync = globIterateSync;
+exports.globIterate = globIterate;
+const minimatch_1 = __nccwpck_require__(85207);
+const glob_js_1 = __nccwpck_require__(81017);
+const has_magic_js_1 = __nccwpck_require__(66889);
+var minimatch_2 = __nccwpck_require__(85207);
+Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return minimatch_2.escape; } }));
+Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return minimatch_2.unescape; } }));
+var glob_js_2 = __nccwpck_require__(81017);
+Object.defineProperty(exports, "Glob", ({ enumerable: true, get: function () { return glob_js_2.Glob; } }));
+var has_magic_js_2 = __nccwpck_require__(66889);
+Object.defineProperty(exports, "hasMagic", ({ enumerable: true, get: function () { return has_magic_js_2.hasMagic; } }));
+var ignore_js_1 = __nccwpck_require__(4833);
+Object.defineProperty(exports, "Ignore", ({ enumerable: true, get: function () { return ignore_js_1.Ignore; } }));
+function globStreamSync(pattern, options = {}) {
+    return new glob_js_1.Glob(pattern, options).streamSync();
+}
+function globStream(pattern, options = {}) {
+    return new glob_js_1.Glob(pattern, options).stream();
+}
+function globSync(pattern, options = {}) {
+    return new glob_js_1.Glob(pattern, options).walkSync();
+}
+async function glob_(pattern, options = {}) {
+    return new glob_js_1.Glob(pattern, options).walk();
+}
+function globIterateSync(pattern, options = {}) {
+    return new glob_js_1.Glob(pattern, options).iterateSync();
+}
+function globIterate(pattern, options = {}) {
+    return new glob_js_1.Glob(pattern, options).iterate();
+}
+// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc
+exports.streamSync = globStreamSync;
+exports.stream = Object.assign(globStream, { sync: globStreamSync });
+exports.iterateSync = globIterateSync;
+exports.iterate = Object.assign(globIterate, {
+    sync: globIterateSync,
+});
+exports.sync = Object.assign(globSync, {
+    stream: globStreamSync,
+    iterate: globIterateSync,
+});
+exports.glob = Object.assign(glob_, {
+    glob: glob_,
+    globSync,
+    sync: exports.sync,
+    globStream,
+    stream: exports.stream,
+    globStreamSync,
+    streamSync: exports.streamSync,
+    globIterate,
+    iterate: exports.iterate,
+    globIterateSync,
+    iterateSync: exports.iterateSync,
+    Glob: glob_js_1.Glob,
+    hasMagic: has_magic_js_1.hasMagic,
+    escape: minimatch_1.escape,
+    unescape: minimatch_1.unescape,
+});
+exports.glob.glob = exports.glob;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 4041:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// this is just a very light wrapper around 2 arrays with an offset index
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Pattern = void 0;
+const minimatch_1 = __nccwpck_require__(85207);
+const isPatternList = (pl) => pl.length >= 1;
+const isGlobList = (gl) => gl.length >= 1;
+/**
+ * An immutable-ish view on an array of glob parts and their parsed
+ * results
+ */
+class Pattern {
+    #patternList;
+    #globList;
+    #index;
+    length;
+    #platform;
+    #rest;
+    #globString;
+    #isDrive;
+    #isUNC;
+    #isAbsolute;
+    #followGlobstar = true;
+    constructor(patternList, globList, index, platform) {
+        if (!isPatternList(patternList)) {
+            throw new TypeError('empty pattern list');
+        }
+        if (!isGlobList(globList)) {
+            throw new TypeError('empty glob list');
         }
-        if (!pattern) {
-            this.empty = true;
-            return;
+        if (globList.length !== patternList.length) {
+            throw new TypeError('mismatched pattern list and glob list lengths');
         }
-        // step 1: figure out negation, etc.
-        this.parseNegate();
-        // step 2: expand braces
-        this.globSet = [...new Set(this.braceExpand())];
-        if (options.debug) {
-            this.debug = (...args) => console.error(...args);
+        this.length = patternList.length;
+        if (index < 0 || index >= this.length) {
+            throw new TypeError('index out of range');
         }
-        this.debug(this.pattern, this.globSet);
-        // step 3: now we have a set, so turn each one into a series of
-        // path-portion matching patterns.
-        // These will be regexps, except in the case of "**", which is
-        // set to the GLOBSTAR object for globstar behavior,
-        // and will not contain any / characters
-        //
-        // First, we preprocess to make the glob pattern sets a bit simpler
-        // and deduped.  There are some perf-killing patterns that can cause
-        // problems with a glob walk, but we can simplify them down a bit.
-        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
-        this.globParts = this.preprocess(rawGlobParts);
-        this.debug(this.pattern, this.globParts);
-        // glob --> regexps
-        let set = this.globParts.map((s, _, __) => {
-            if (this.isWindows && this.windowsNoMagicRoot) {
-                // check if it's a drive or unc path.
-                const isUNC = s[0] === '' &&
-                    s[1] === '' &&
-                    (s[2] === '?' || !globMagic.test(s[2])) &&
-                    !globMagic.test(s[3]);
-                const isDrive = /^[a-z]:/i.test(s[0]);
-                if (isUNC) {
-                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
-                }
-                else if (isDrive) {
-                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
+        this.#patternList = patternList;
+        this.#globList = globList;
+        this.#index = index;
+        this.#platform = platform;
+        // normalize root entries of absolute patterns on initial creation.
+        if (this.#index === 0) {
+            // c: => ['c:/']
+            // C:/ => ['C:/']
+            // C:/x => ['C:/', 'x']
+            // //host/share => ['//host/share/']
+            // //host/share/ => ['//host/share/']
+            // //host/share/x => ['//host/share/', 'x']
+            // /etc => ['/', 'etc']
+            // / => ['/']
+            if (this.isUNC()) {
+                // '' / '' / 'host' / 'share'
+                const [p0, p1, p2, p3, ...prest] = this.#patternList;
+                const [g0, g1, g2, g3, ...grest] = this.#globList;
+                if (prest[0] === '') {
+                    // ends in /
+                    prest.shift();
+                    grest.shift();
                 }
+                const p = [p0, p1, p2, p3, ''].join('/');
+                const g = [g0, g1, g2, g3, ''].join('/');
+                this.#patternList = [p, ...prest];
+                this.#globList = [g, ...grest];
+                this.length = this.#patternList.length;
             }
-            return s.map(ss => this.parse(ss));
-        });
-        this.debug(this.pattern, set);
-        // filter out everything that didn't compile properly.
-        this.set = set.filter(s => s.indexOf(false) === -1);
-        // do not treat the ? in UNC paths as magic
-        if (this.isWindows) {
-            for (let i = 0; i < this.set.length; i++) {
-                const p = this.set[i];
-                if (p[0] === '' &&
-                    p[1] === '' &&
-                    this.globParts[i][2] === '?' &&
-                    typeof p[3] === 'string' &&
-                    /^[a-z]:$/i.test(p[3])) {
-                    p[2] = '?';
+            else if (this.isDrive() || this.isAbsolute()) {
+                const [p1, ...prest] = this.#patternList;
+                const [g1, ...grest] = this.#globList;
+                if (prest[0] === '') {
+                    // ends in /
+                    prest.shift();
+                    grest.shift();
                 }
+                const p = p1 + '/';
+                const g = g1 + '/';
+                this.#patternList = [p, ...prest];
+                this.#globList = [g, ...grest];
+                this.length = this.#patternList.length;
             }
         }
-        this.debug(this.pattern, this.set);
     }
-    // various transforms to equivalent pattern sets that are
-    // faster to process in a filesystem walk.  The goal is to
-    // eliminate what we can, and push all ** patterns as far
-    // to the right as possible, even if it increases the number
-    // of patterns that we have to process.
-    preprocess(globParts) {
-        // if we're not in globstar mode, then turn all ** into *
-        if (this.options.noglobstar) {
-            for (let i = 0; i < globParts.length; i++) {
-                for (let j = 0; j < globParts[i].length; j++) {
-                    if (globParts[i][j] === '**') {
-                        globParts[i][j] = '*';
-                    }
-                }
-            }
-        }
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-            // aggressive optimization for the purpose of fs walking
-            globParts = this.firstPhasePreProcess(globParts);
-            globParts = this.secondPhasePreProcess(globParts);
-        }
-        else if (optimizationLevel >= 1) {
-            // just basic optimizations to remove some .. parts
-            globParts = this.levelOneOptimize(globParts);
-        }
-        else {
-            // just collapse multiple ** portions into one
-            globParts = this.adjascentGlobstarOptimize(globParts);
-        }
-        return globParts;
+    /**
+     * The first entry in the parsed list of patterns
+     */
+    pattern() {
+        return this.#patternList[this.#index];
     }
-    // just get rid of adjascent ** portions
-    adjascentGlobstarOptimize(globParts) {
-        return globParts.map(parts => {
-            let gs = -1;
-            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
-                let i = gs;
-                while (parts[i + 1] === '**') {
-                    i++;
-                }
-                if (i !== gs) {
-                    parts.splice(gs, i - gs);
-                }
-            }
-            return parts;
-        });
+    /**
+     * true of if pattern() returns a string
+     */
+    isString() {
+        return typeof this.#patternList[this.#index] === 'string';
     }
-    // get rid of adjascent ** and resolve .. portions
-    levelOneOptimize(globParts) {
-        return globParts.map(parts => {
-            parts = parts.reduce((set, part) => {
-                const prev = set[set.length - 1];
-                if (part === '**' && prev === '**') {
-                    return set;
-                }
-                if (part === '..') {
-                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
-                        set.pop();
-                        return set;
-                    }
-                }
-                set.push(part);
-                return set;
-            }, []);
-            return parts.length === 0 ? [''] : parts;
-        });
+    /**
+     * true of if pattern() returns GLOBSTAR
+     */
+    isGlobstar() {
+        return this.#patternList[this.#index] === minimatch_1.GLOBSTAR;
     }
-    levelTwoFileOptimize(parts) {
-        if (!Array.isArray(parts)) {
-            parts = this.slashSplit(parts);
-        }
-        let didSomething = false;
-        do {
-            didSomething = false;
-            // 
// -> 
/
-            if (!this.preserveMultipleSlashes) {
-                for (let i = 1; i < parts.length - 1; i++) {
-                    const p = parts[i];
-                    // don't squeeze out UNC patterns
-                    if (i === 1 && p === '' && parts[0] === '')
-                        continue;
-                    if (p === '.' || p === '') {
-                        didSomething = true;
-                        parts.splice(i, 1);
-                        i--;
-                    }
-                }
-                if (parts[0] === '.' &&
-                    parts.length === 2 &&
-                    (parts[1] === '.' || parts[1] === '')) {
-                    didSomething = true;
-                    parts.pop();
-                }
-            }
-            // 
/

/../ ->

/
-            let dd = 0;
-            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
-                const p = parts[dd - 1];
-                if (p && p !== '.' && p !== '..' && p !== '**') {
-                    didSomething = true;
-                    parts.splice(dd - 1, 2);
-                    dd -= 2;
-                }
-            }
-        } while (didSomething);
-        return parts.length === 0 ? [''] : parts;
+    /**
+     * true if pattern() returns a regexp
+     */
+    isRegExp() {
+        return this.#patternList[this.#index] instanceof RegExp;
     }
-    // First phase: single-pattern processing
-    // 
 is 1 or more portions
-    //  is 1 or more portions
-    // 

is any portion other than ., .., '', or ** - // is . or '' - // - // **/.. is *brutal* for filesystem walking performance, because - // it effectively resets the recursive walk each time it occurs, - // and ** cannot be reduced out by a .. pattern part like a regexp - // or most strings (other than .., ., and '') can be. - // - //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} - //

// -> 
/
-    // 
/

/../ ->

/
-    // **/**/ -> **/
-    //
-    // **/*/ -> */**/ <== not valid because ** doesn't follow
-    // this WOULD be allowed if ** did follow symlinks, or * didn't
-    firstPhasePreProcess(globParts) {
-        let didSomething = false;
-        do {
-            didSomething = false;
-            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} - for (let parts of globParts) { - let gs = -1; - while (-1 !== (gs = parts.indexOf('**', gs + 1))) { - let gss = gs; - while (parts[gss + 1] === '**') { - //

/**/**/ -> 
/**/
-                        gss++;
-                    }
-                    // eg, if gs is 2 and gss is 4, that means we have 3 **
-                    // parts, and can remove 2 of them.
-                    if (gss > gs) {
-                        parts.splice(gs + 1, gss - gs);
-                    }
-                    let next = parts[gs + 1];
-                    const p = parts[gs + 2];
-                    const p2 = parts[gs + 3];
-                    if (next !== '..')
-                        continue;
-                    if (!p ||
-                        p === '.' ||
-                        p === '..' ||
-                        !p2 ||
-                        p2 === '.' ||
-                        p2 === '..') {
-                        continue;
-                    }
-                    didSomething = true;
-                    // edit parts in place, and push the new one
-                    parts.splice(gs, 1);
-                    const other = parts.slice(0);
-                    other[gs] = '**';
-                    globParts.push(other);
-                    gs--;
-                }
-                // 
// -> 
/
-                if (!this.preserveMultipleSlashes) {
-                    for (let i = 1; i < parts.length - 1; i++) {
-                        const p = parts[i];
-                        // don't squeeze out UNC patterns
-                        if (i === 1 && p === '' && parts[0] === '')
-                            continue;
-                        if (p === '.' || p === '') {
-                            didSomething = true;
-                            parts.splice(i, 1);
-                            i--;
-                        }
-                    }
-                    if (parts[0] === '.' &&
-                        parts.length === 2 &&
-                        (parts[1] === '.' || parts[1] === '')) {
-                        didSomething = true;
-                        parts.pop();
-                    }
-                }
-                // 
/

/../ ->

/
-                let dd = 0;
-                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
-                    const p = parts[dd - 1];
-                    if (p && p !== '.' && p !== '..' && p !== '**') {
-                        didSomething = true;
-                        const needDot = dd === 1 && parts[dd + 1] === '**';
-                        const splin = needDot ? ['.'] : [];
-                        parts.splice(dd - 1, 2, ...splin);
-                        if (parts.length === 0)
-                            parts.push('');
-                        dd -= 2;
-                    }
-                }
-            }
-        } while (didSomething);
-        return globParts;
+    /**
+     * The /-joined set of glob parts that make up this pattern
+     */
+    globString() {
+        return (this.#globString =
+            this.#globString ||
+                (this.#index === 0 ?
+                    this.isAbsolute() ?
+                        this.#globList[0] + this.#globList.slice(1).join('/')
+                        : this.#globList.join('/')
+                    : this.#globList.slice(this.#index).join('/')));
     }
-    // second phase: multi-pattern dedupes
-    // {
/*/,
/

/} ->

/*/
-    // {
/,
/} -> 
/
-    // {
/**/,
/} -> 
/**/
-    //
-    // {
/**/,
/**/

/} ->

/**/
-    // ^-- not valid because ** doens't follow symlinks
-    secondPhasePreProcess(globParts) {
-        for (let i = 0; i < globParts.length - 1; i++) {
-            for (let j = i + 1; j < globParts.length; j++) {
-                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
-                if (matched) {
-                    globParts[i] = [];
-                    globParts[j] = matched;
-                    break;
-                }
+    /**
+     * true if there are more pattern parts after this one
+     */
+    hasMore() {
+        return this.length > this.#index + 1;
+    }
+    /**
+     * The rest of the pattern after this part, or null if this is the end
+     */
+    rest() {
+        if (this.#rest !== undefined)
+            return this.#rest;
+        if (!this.hasMore())
+            return (this.#rest = null);
+        this.#rest = new Pattern(this.#patternList, this.#globList, this.#index + 1, this.#platform);
+        this.#rest.#isAbsolute = this.#isAbsolute;
+        this.#rest.#isUNC = this.#isUNC;
+        this.#rest.#isDrive = this.#isDrive;
+        return this.#rest;
+    }
+    /**
+     * true if the pattern represents a //unc/path/ on windows
+     */
+    isUNC() {
+        const pl = this.#patternList;
+        return this.#isUNC !== undefined ?
+            this.#isUNC
+            : (this.#isUNC =
+                this.#platform === 'win32' &&
+                    this.#index === 0 &&
+                    pl[0] === '' &&
+                    pl[1] === '' &&
+                    typeof pl[2] === 'string' &&
+                    !!pl[2] &&
+                    typeof pl[3] === 'string' &&
+                    !!pl[3]);
+    }
+    // pattern like C:/...
+    // split = ['C:', ...]
+    // XXX: would be nice to handle patterns like `c:*` to test the cwd
+    // in c: for *, but I don't know of a way to even figure out what that
+    // cwd is without actually chdir'ing into it?
+    /**
+     * True if the pattern starts with a drive letter on Windows
+     */
+    isDrive() {
+        const pl = this.#patternList;
+        return this.#isDrive !== undefined ?
+            this.#isDrive
+            : (this.#isDrive =
+                this.#platform === 'win32' &&
+                    this.#index === 0 &&
+                    this.length > 1 &&
+                    typeof pl[0] === 'string' &&
+                    /^[a-z]:$/i.test(pl[0]));
+    }
+    // pattern = '/' or '/...' or '/x/...'
+    // split = ['', ''] or ['', ...] or ['', 'x', ...]
+    // Drive and UNC both considered absolute on windows
+    /**
+     * True if the pattern is rooted on an absolute path
+     */
+    isAbsolute() {
+        const pl = this.#patternList;
+        return this.#isAbsolute !== undefined ?
+            this.#isAbsolute
+            : (this.#isAbsolute =
+                (pl[0] === '' && pl.length > 1) ||
+                    this.isDrive() ||
+                    this.isUNC());
+    }
+    /**
+     * consume the root of the pattern, and return it
+     */
+    root() {
+        const p = this.#patternList[0];
+        return (typeof p === 'string' && this.isAbsolute() && this.#index === 0) ?
+            p
+            : '';
+    }
+    /**
+     * Check to see if the current globstar pattern is allowed to follow
+     * a symbolic link.
+     */
+    checkFollowGlobstar() {
+        return !(this.#index === 0 ||
+            !this.isGlobstar() ||
+            !this.#followGlobstar);
+    }
+    /**
+     * Mark that the current globstar pattern is following a symbolic link
+     */
+    markFollowGlobstar() {
+        if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)
+            return false;
+        this.#followGlobstar = false;
+        return true;
+    }
+}
+exports.Pattern = Pattern;
+//# sourceMappingURL=pattern.js.map
+
+/***/ }),
+
+/***/ 48095:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// synchronous utility for filtering entries and calculating subwalks
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Processor = exports.SubWalks = exports.MatchRecord = exports.HasWalkedCache = void 0;
+const minimatch_1 = __nccwpck_require__(85207);
+/**
+ * A cache of which patterns have been processed for a given Path
+ */
+class HasWalkedCache {
+    store;
+    constructor(store = new Map()) {
+        this.store = store;
+    }
+    copy() {
+        return new HasWalkedCache(new Map(this.store));
+    }
+    hasWalked(target, pattern) {
+        return this.store.get(target.fullpath())?.has(pattern.globString());
+    }
+    storeWalked(target, pattern) {
+        const fullpath = target.fullpath();
+        const cached = this.store.get(fullpath);
+        if (cached)
+            cached.add(pattern.globString());
+        else
+            this.store.set(fullpath, new Set([pattern.globString()]));
+    }
+}
+exports.HasWalkedCache = HasWalkedCache;
+/**
+ * A record of which paths have been matched in a given walk step,
+ * and whether they only are considered a match if they are a directory,
+ * and whether their absolute or relative path should be returned.
+ */
+class MatchRecord {
+    store = new Map();
+    add(target, absolute, ifDir) {
+        const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
+        const current = this.store.get(target);
+        this.store.set(target, current === undefined ? n : n & current);
+    }
+    // match, absolute, ifdir
+    entries() {
+        return [...this.store.entries()].map(([path, n]) => [
+            path,
+            !!(n & 2),
+            !!(n & 1),
+        ]);
+    }
+}
+exports.MatchRecord = MatchRecord;
+/**
+ * A collection of patterns that must be processed in a subsequent step
+ * for a given path.
+ */
+class SubWalks {
+    store = new Map();
+    add(target, pattern) {
+        if (!target.canReaddir()) {
+            return;
+        }
+        const subs = this.store.get(target);
+        if (subs) {
+            if (!subs.find(p => p.globString() === pattern.globString())) {
+                subs.push(pattern);
             }
         }
-        return globParts.filter(gs => gs.length);
+        else
+            this.store.set(target, [pattern]);
     }
-    partsMatch(a, b, emptyGSMatch = false) {
-        let ai = 0;
-        let bi = 0;
-        let result = [];
-        let which = '';
-        while (ai < a.length && bi < b.length) {
-            if (a[ai] === b[bi]) {
-                result.push(which === 'b' ? b[bi] : a[ai]);
-                ai++;
-                bi++;
+    get(target) {
+        const subs = this.store.get(target);
+        /* c8 ignore start */
+        if (!subs) {
+            throw new Error('attempting to walk unknown path');
+        }
+        /* c8 ignore stop */
+        return subs;
+    }
+    entries() {
+        return this.keys().map(k => [k, this.store.get(k)]);
+    }
+    keys() {
+        return [...this.store.keys()].filter(t => t.canReaddir());
+    }
+}
+exports.SubWalks = SubWalks;
+/**
+ * The class that processes patterns for a given path.
+ *
+ * Handles child entry filtering, and determining whether a path's
+ * directory contents must be read.
+ */
+class Processor {
+    hasWalkedCache;
+    matches = new MatchRecord();
+    subwalks = new SubWalks();
+    patterns;
+    follow;
+    dot;
+    opts;
+    constructor(opts, hasWalkedCache) {
+        this.opts = opts;
+        this.follow = !!opts.follow;
+        this.dot = !!opts.dot;
+        this.hasWalkedCache =
+            hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
+    }
+    processPatterns(target, patterns) {
+        this.patterns = patterns;
+        const processingSet = patterns.map(p => [target, p]);
+        // map of paths to the magic-starting subwalks they need to walk
+        // first item in patterns is the filter
+        for (let [t, pattern] of processingSet) {
+            this.hasWalkedCache.storeWalked(t, pattern);
+            const root = pattern.root();
+            const absolute = pattern.isAbsolute() && this.opts.absolute !== false;
+            // start absolute patterns at root
+            if (root) {
+                t = t.resolve(root === '/' && this.opts.root !== undefined ?
+                    this.opts.root
+                    : root);
+                const rest = pattern.rest();
+                if (!rest) {
+                    this.matches.add(t, true, false);
+                    continue;
+                }
+                else {
+                    pattern = rest;
+                }
             }
-            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
-                result.push(a[ai]);
-                ai++;
+            if (t.isENOENT())
+                continue;
+            let p;
+            let rest;
+            let changed = false;
+            while (typeof (p = pattern.pattern()) === 'string' &&
+                (rest = pattern.rest())) {
+                const c = t.resolve(p);
+                t = c;
+                pattern = rest;
+                changed = true;
             }
-            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
-                result.push(b[bi]);
-                bi++;
+            p = pattern.pattern();
+            rest = pattern.rest();
+            if (changed) {
+                if (this.hasWalkedCache.hasWalked(t, pattern))
+                    continue;
+                this.hasWalkedCache.storeWalked(t, pattern);
             }
-            else if (a[ai] === '*' &&
-                b[bi] &&
-                (this.options.dot || !b[bi].startsWith('.')) &&
-                b[bi] !== '**') {
-                if (which === 'b')
-                    return false;
-                which = 'a';
-                result.push(a[ai]);
-                ai++;
-                bi++;
+            // now we have either a final string for a known entry,
+            // more strings for an unknown entry,
+            // or a pattern starting with magic, mounted on t.
+            if (typeof p === 'string') {
+                // must not be final entry, otherwise we would have
+                // concatenated it earlier.
+                const ifDir = p === '..' || p === '' || p === '.';
+                this.matches.add(t.resolve(p), absolute, ifDir);
+                continue;
             }
-            else if (b[bi] === '*' &&
-                a[ai] &&
-                (this.options.dot || !a[ai].startsWith('.')) &&
-                a[ai] !== '**') {
-                if (which === 'a')
-                    return false;
-                which = 'b';
-                result.push(b[bi]);
-                ai++;
-                bi++;
+            else if (p === minimatch_1.GLOBSTAR) {
+                // if no rest, match and subwalk pattern
+                // if rest, process rest and subwalk pattern
+                // if it's a symlink, but we didn't get here by way of a
+                // globstar match (meaning it's the first time THIS globstar
+                // has traversed a symlink), then we follow it. Otherwise, stop.
+                if (!t.isSymbolicLink() ||
+                    this.follow ||
+                    pattern.checkFollowGlobstar()) {
+                    this.subwalks.add(t, pattern);
+                }
+                const rp = rest?.pattern();
+                const rrest = rest?.rest();
+                if (!rest || ((rp === '' || rp === '.') && !rrest)) {
+                    // only HAS to be a dir if it ends in **/ or **/.
+                    // but ending in ** will match files as well.
+                    this.matches.add(t, absolute, rp === '' || rp === '.');
+                }
+                else {
+                    if (rp === '..') {
+                        // this would mean you're matching **/.. at the fs root,
+                        // and no thanks, I'm not gonna test that specific case.
+                        /* c8 ignore start */
+                        const tp = t.parent || t;
+                        /* c8 ignore stop */
+                        if (!rrest)
+                            this.matches.add(tp, absolute, true);
+                        else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
+                            this.subwalks.add(tp, rrest);
+                        }
+                    }
+                }
             }
-            else {
-                return false;
+            else if (p instanceof RegExp) {
+                this.subwalks.add(t, pattern);
             }
         }
-        // if we fall out of the loop, it means they two are identical
-        // as long as their lengths match
-        return a.length === b.length && result;
+        return this;
     }
-    parseNegate() {
-        if (this.nonegate)
-            return;
-        const pattern = this.pattern;
-        let negate = false;
-        let negateOffset = 0;
-        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
-            negate = !negate;
-            negateOffset++;
-        }
-        if (negateOffset)
-            this.pattern = pattern.slice(negateOffset);
-        this.negate = negate;
+    subwalkTargets() {
+        return this.subwalks.keys();
     }
-    // set partial to true to test if, for example,
-    // "/a/b" matches the start of "/*/b/*/d"
-    // Partial means, if you run out of file before you run
-    // out of pattern, then that's fine, as long as all
-    // the parts match.
-    matchOne(file, pattern, partial = false) {
-        const options = this.options;
-        // UNC paths like //?/X:/... can match X:/... and vice versa
-        // Drive letters in absolute drive or unc paths are always compared
-        // case-insensitively.
-        if (this.isWindows) {
-            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
-            const fileUNC = !fileDrive &&
-                file[0] === '' &&
-                file[1] === '' &&
-                file[2] === '?' &&
-                /^[a-z]:$/i.test(file[3]);
-            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
-            const patternUNC = !patternDrive &&
-                pattern[0] === '' &&
-                pattern[1] === '' &&
-                pattern[2] === '?' &&
-                typeof pattern[3] === 'string' &&
-                /^[a-z]:$/i.test(pattern[3]);
-            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
-            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
-            if (typeof fdi === 'number' && typeof pdi === 'number') {
-                const [fd, pd] = [file[fdi], pattern[pdi]];
-                if (fd.toLowerCase() === pd.toLowerCase()) {
-                    pattern[pdi] = fd;
-                    if (pdi > fdi) {
-                        pattern = pattern.slice(pdi);
-                    }
-                    else if (fdi > pdi) {
-                        file = file.slice(fdi);
-                    }
+    child() {
+        return new Processor(this.opts, this.hasWalkedCache);
+    }
+    // return a new Processor containing the subwalks for each
+    // child entry, and a set of matches, and
+    // a hasWalkedCache that's a copy of this one
+    // then we're going to call
+    filterEntries(parent, entries) {
+        const patterns = this.subwalks.get(parent);
+        // put matches and entry walks into the results processor
+        const results = this.child();
+        for (const e of entries) {
+            for (const pattern of patterns) {
+                const absolute = pattern.isAbsolute();
+                const p = pattern.pattern();
+                const rest = pattern.rest();
+                if (p === minimatch_1.GLOBSTAR) {
+                    results.testGlobstar(e, pattern, rest, absolute);
+                }
+                else if (p instanceof RegExp) {
+                    results.testRegExp(e, p, rest, absolute);
+                }
+                else {
+                    results.testString(e, p, rest, absolute);
                 }
             }
         }
-        // resolve and reduce . and .. portions in the file as well.
-        // dont' need to do the second phase, because it's only one string[]
-        const { optimizationLevel = 1 } = this.options;
-        if (optimizationLevel >= 2) {
-            file = this.levelTwoFileOptimize(file);
-        }
-        this.debug('matchOne', this, { file, pattern });
-        this.debug('matchOne', file.length, pattern.length);
-        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
-            this.debug('matchOne loop');
-            var p = pattern[pi];
-            var f = file[fi];
-            this.debug(pattern, p, f);
-            // should be impossible.
-            // some invalid regexp stuff in the set.
-            /* c8 ignore start */
-            if (p === false) {
-                return false;
+        return results;
+    }
+    testGlobstar(e, pattern, rest, absolute) {
+        if (this.dot || !e.name.startsWith('.')) {
+            if (!pattern.hasMore()) {
+                this.matches.add(e, absolute, false);
             }
-            /* c8 ignore stop */
-            if (p === exports.GLOBSTAR) {
-                this.debug('GLOBSTAR', [pattern, p, f]);
-                // "**"
-                // a/**/b/**/c would match the following:
-                // a/b/x/y/z/c
-                // a/x/y/z/b/c
-                // a/b/x/b/x/c
-                // a/b/c
-                // To do this, take the rest of the pattern after
-                // the **, and see if it would match the file remainder.
-                // If so, return success.
-                // If not, the ** "swallows" a segment, and try again.
-                // This is recursively awful.
-                //
-                // a/**/b/**/c matching a/b/x/y/z/c
-                // - a matches a
-                // - doublestar
-                //   - matchOne(b/x/y/z/c, b/**/c)
-                //     - b matches b
-                //     - doublestar
-                //       - matchOne(x/y/z/c, c) -> no
-                //       - matchOne(y/z/c, c) -> no
-                //       - matchOne(z/c, c) -> no
-                //       - matchOne(c, c) yes, hit
-                var fr = fi;
-                var pr = pi + 1;
-                if (pr === pl) {
-                    this.debug('** at the end');
-                    // a ** at the end will just swallow the rest.
-                    // We have found a match.
-                    // however, it will not swallow /.x, unless
-                    // options.dot is set.
-                    // . and .. are *never* matched by **, for explosively
-                    // exponential reasons.
-                    for (; fi < fl; fi++) {
-                        if (file[fi] === '.' ||
-                            file[fi] === '..' ||
-                            (!options.dot && file[fi].charAt(0) === '.'))
-                            return false;
-                    }
-                    return true;
+            if (e.canReaddir()) {
+                // if we're in follow mode or it's not a symlink, just keep
+                // testing the same pattern. If there's more after the globstar,
+                // then this symlink consumes the globstar. If not, then we can
+                // follow at most ONE symlink along the way, so we mark it, which
+                // also checks to ensure that it wasn't already marked.
+                if (this.follow || !e.isSymbolicLink()) {
+                    this.subwalks.add(e, pattern);
                 }
-                // ok, let's see if we can swallow whatever we can.
-                while (fr < fl) {
-                    var swallowee = file[fr];
-                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
-                    // XXX remove this slice.  Just pass the start index.
-                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
-                        this.debug('globstar found match!', fr, fl, swallowee);
-                        // found a match.
-                        return true;
+                else if (e.isSymbolicLink()) {
+                    if (rest && pattern.checkFollowGlobstar()) {
+                        this.subwalks.add(e, rest);
                     }
-                    else {
-                        // can't swallow "." or ".." ever.
-                        // can only swallow ".foo" when explicitly asked.
-                        if (swallowee === '.' ||
-                            swallowee === '..' ||
-                            (!options.dot && swallowee.charAt(0) === '.')) {
-                            this.debug('dot detected!', file, fr, pattern, pr);
-                            break;
-                        }
-                        // ** swallows a segment, and continue.
-                        this.debug('globstar swallow a segment, and continue');
-                        fr++;
+                    else if (pattern.markFollowGlobstar()) {
+                        this.subwalks.add(e, pattern);
                     }
                 }
-                // no match was found.
-                // However, in partial mode, we can't say this is necessarily over.
+            }
+        }
+        // if the NEXT thing matches this entry, then also add
+        // the rest.
+        if (rest) {
+            const rp = rest.pattern();
+            if (typeof rp === 'string' &&
+                // dots and empty were handled already
+                rp !== '..' &&
+                rp !== '' &&
+                rp !== '.') {
+                this.testString(e, rp, rest.rest(), absolute);
+            }
+            else if (rp === '..') {
                 /* c8 ignore start */
-                if (partial) {
-                    // ran out of file
-                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
-                    if (fr === fl) {
-                        return true;
-                    }
-                }
+                const ep = e.parent || e;
                 /* c8 ignore stop */
-                return false;
+                this.subwalks.add(ep, rest);
             }
-            // something other than **
-            // non-magic patterns just have to match exactly
-            // patterns with magic have been turned into regexps.
-            let hit;
-            if (typeof p === 'string') {
-                hit = f === p;
-                this.debug('string match', p, f, hit);
+            else if (rp instanceof RegExp) {
+                this.testRegExp(e, rp, rest.rest(), absolute);
             }
-            else {
-                hit = p.test(f);
-                this.debug('pattern match', p, f, hit);
+        }
+    }
+    testRegExp(e, p, rest, absolute) {
+        if (!p.test(e.name))
+            return;
+        if (!rest) {
+            this.matches.add(e, absolute, false);
+        }
+        else {
+            this.subwalks.add(e, rest);
+        }
+    }
+    testString(e, p, rest, absolute) {
+        // should never happen?
+        if (!e.isNamed(p))
+            return;
+        if (!rest) {
+            this.matches.add(e, absolute, false);
+        }
+        else {
+            this.subwalks.add(e, rest);
+        }
+    }
+}
+exports.Processor = Processor;
+//# sourceMappingURL=processor.js.map
+
+/***/ }),
+
+/***/ 95049:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GlobStream = exports.GlobWalker = exports.GlobUtil = void 0;
+/**
+ * Single-use utility classes to provide functionality to the {@link Glob}
+ * methods.
+ *
+ * @module
+ */
+const minipass_1 = __nccwpck_require__(78275);
+const ignore_js_1 = __nccwpck_require__(4833);
+const processor_js_1 = __nccwpck_require__(48095);
+const makeIgnore = (ignore, opts) => typeof ignore === 'string' ? new ignore_js_1.Ignore([ignore], opts)
+    : Array.isArray(ignore) ? new ignore_js_1.Ignore(ignore, opts)
+        : ignore;
+/**
+ * basic walking utilities that all the glob walker types use
+ */
+class GlobUtil {
+    path;
+    patterns;
+    opts;
+    seen = new Set();
+    paused = false;
+    aborted = false;
+    #onResume = [];
+    #ignore;
+    #sep;
+    signal;
+    maxDepth;
+    includeChildMatches;
+    constructor(patterns, path, opts) {
+        this.patterns = patterns;
+        this.path = path;
+        this.opts = opts;
+        this.#sep = !opts.posix && opts.platform === 'win32' ? '\\' : '/';
+        this.includeChildMatches = opts.includeChildMatches !== false;
+        if (opts.ignore || !this.includeChildMatches) {
+            this.#ignore = makeIgnore(opts.ignore ?? [], opts);
+            if (!this.includeChildMatches &&
+                typeof this.#ignore.add !== 'function') {
+                const m = 'cannot ignore child matches, ignore lacks add() method.';
+                throw new Error(m);
             }
-            if (!hit)
-                return false;
         }
-        // Note: ending in / means that we'll get a final ""
-        // at the end of the pattern.  This can only match a
-        // corresponding "" at the end of the file.
-        // If the file ends in /, then it can only match a
-        // a pattern that ends in /, unless the pattern just
-        // doesn't have any more for it. But, a/b/ should *not*
-        // match "a/b/*", even though "" matches against the
-        // [^/]*? pattern, except in partial mode, where it might
-        // simply not be reached yet.
-        // However, a/b/ should still satisfy a/*
-        // now either we fell off the end of the pattern, or we're done.
-        if (fi === fl && pi === pl) {
-            // ran out of pattern and filename at the same time.
-            // an exact hit!
-            return true;
+        // ignore, always set with maxDepth, but it's optional on the
+        // GlobOptions type
+        /* c8 ignore start */
+        this.maxDepth = opts.maxDepth || Infinity;
+        /* c8 ignore stop */
+        if (opts.signal) {
+            this.signal = opts.signal;
+            this.signal.addEventListener('abort', () => {
+                this.#onResume.length = 0;
+            });
+        }
+    }
+    #ignored(path) {
+        return this.seen.has(path) || !!this.#ignore?.ignored?.(path);
+    }
+    #childrenIgnored(path) {
+        return !!this.#ignore?.childrenIgnored?.(path);
+    }
+    // backpressure mechanism
+    pause() {
+        this.paused = true;
+    }
+    resume() {
+        /* c8 ignore start */
+        if (this.signal?.aborted)
+            return;
+        /* c8 ignore stop */
+        this.paused = false;
+        let fn = undefined;
+        while (!this.paused && (fn = this.#onResume.shift())) {
+            fn();
+        }
+    }
+    onResume(fn) {
+        if (this.signal?.aborted)
+            return;
+        /* c8 ignore start */
+        if (!this.paused) {
+            fn();
         }
-        else if (fi === fl) {
-            // ran out of file, but still had pattern left.
-            // this is ok if we're doing the match as part of
-            // a glob fs traversal.
-            return partial;
+        else {
+            /* c8 ignore stop */
+            this.#onResume.push(fn);
         }
-        else if (pi === pl) {
-            // ran out of pattern, still have file left.
-            // this is only acceptable if we're on the very last
-            // empty segment of a file with a trailing slash.
-            // a/* should match a/b/
-            return fi === fl - 1 && file[fi] === '';
-            /* c8 ignore start */
+    }
+    // do the requisite realpath/stat checking, and return the path
+    // to add or undefined to filter it out.
+    async matchCheck(e, ifDir) {
+        if (ifDir && this.opts.nodir)
+            return undefined;
+        let rpc;
+        if (this.opts.realpath) {
+            rpc = e.realpathCached() || (await e.realpath());
+            if (!rpc)
+                return undefined;
+            e = rpc;
         }
-        else {
-            // should be unreachable.
-            throw new Error('wtf?');
+        const needStat = e.isUnknown() || this.opts.stat;
+        const s = needStat ? await e.lstat() : e;
+        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
+            const target = await s.realpath();
+            /* c8 ignore start */
+            if (target && (target.isUnknown() || this.opts.stat)) {
+                await target.lstat();
+            }
+            /* c8 ignore stop */
         }
-        /* c8 ignore stop */
+        return this.matchCheckTest(s, ifDir);
     }
-    braceExpand() {
-        return (0, exports.braceExpand)(this.pattern, this.options);
+    matchCheckTest(e, ifDir) {
+        return (e &&
+            (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&
+            (!ifDir || e.canReaddir()) &&
+            (!this.opts.nodir || !e.isDirectory()) &&
+            (!this.opts.nodir ||
+                !this.opts.follow ||
+                !e.isSymbolicLink() ||
+                !e.realpathCached()?.isDirectory()) &&
+            !this.#ignored(e)) ?
+            e
+            : undefined;
     }
-    parse(pattern) {
-        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
-        const options = this.options;
-        // shortcuts
-        if (pattern === '**')
-            return exports.GLOBSTAR;
-        if (pattern === '')
-            return '';
-        // far and away, the most common glob pattern parts are
-        // *, *.*, and *.  Add a fast check method for those.
-        let m;
-        let fastTest = null;
-        if ((m = pattern.match(starRE))) {
-            fastTest = options.dot ? starTestDot : starTest;
+    matchCheckSync(e, ifDir) {
+        if (ifDir && this.opts.nodir)
+            return undefined;
+        let rpc;
+        if (this.opts.realpath) {
+            rpc = e.realpathCached() || e.realpathSync();
+            if (!rpc)
+                return undefined;
+            e = rpc;
         }
-        else if ((m = pattern.match(starDotExtRE))) {
-            fastTest = (options.nocase
-                ? options.dot
-                    ? starDotExtTestNocaseDot
-                    : starDotExtTestNocase
-                : options.dot
-                    ? starDotExtTestDot
-                    : starDotExtTest)(m[1]);
+        const needStat = e.isUnknown() || this.opts.stat;
+        const s = needStat ? e.lstatSync() : e;
+        if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {
+            const target = s.realpathSync();
+            if (target && (target?.isUnknown() || this.opts.stat)) {
+                target.lstatSync();
+            }
         }
-        else if ((m = pattern.match(qmarksRE))) {
-            fastTest = (options.nocase
-                ? options.dot
-                    ? qmarksTestNocaseDot
-                    : qmarksTestNocase
-                : options.dot
-                    ? qmarksTestDot
-                    : qmarksTest)(m);
+        return this.matchCheckTest(s, ifDir);
+    }
+    matchFinish(e, absolute) {
+        if (this.#ignored(e))
+            return;
+        // we know we have an ignore if this is false, but TS doesn't
+        if (!this.includeChildMatches && this.#ignore?.add) {
+            const ign = `${e.relativePosix()}/**`;
+            this.#ignore.add(ign);
         }
-        else if ((m = pattern.match(starDotStarRE))) {
-            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        const abs = this.opts.absolute === undefined ? absolute : this.opts.absolute;
+        this.seen.add(e);
+        const mark = this.opts.mark && e.isDirectory() ? this.#sep : '';
+        // ok, we have what we need!
+        if (this.opts.withFileTypes) {
+            this.matchEmit(e);
         }
-        else if ((m = pattern.match(dotStarRE))) {
-            fastTest = dotStarTest;
+        else if (abs) {
+            const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath();
+            this.matchEmit(abs + mark);
         }
-        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
-        if (fastTest && typeof re === 'object') {
-            // Avoids overriding in frozen environments
-            Reflect.defineProperty(re, 'test', { value: fastTest });
+        else {
+            const rel = this.opts.posix ? e.relativePosix() : e.relative();
+            const pre = this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?
+                '.' + this.#sep
+                : '';
+            this.matchEmit(!rel ? '.' + mark : pre + rel + mark);
         }
-        return re;
     }
-    makeRe() {
-        if (this.regexp || this.regexp === false)
-            return this.regexp;
-        // at this point, this.set is a 2d array of partial
-        // pattern strings, or "**".
-        //
-        // It's better to use .match().  This function shouldn't
-        // be used, really, but it's pretty convenient sometimes,
-        // when you just want to work with a regex.
-        const set = this.set;
-        if (!set.length) {
-            this.regexp = false;
-            return this.regexp;
-        }
-        const options = this.options;
-        const twoStar = options.noglobstar
-            ? star
-            : options.dot
-                ? twoStarDot
-                : twoStarNoDot;
-        const flags = new Set(options.nocase ? ['i'] : []);
-        // regexpify non-globstar patterns
-        // if ** is only item, then we just do one twoStar
-        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
-        // if ** is last, append (\/twoStar|) to previous
-        // if ** is in the middle, append (\/|\/twoStar\/) to previous
-        // then filter out GLOBSTAR symbols
-        let re = set
-            .map(pattern => {
-            const pp = pattern.map(p => {
-                if (p instanceof RegExp) {
-                    for (const f of p.flags.split(''))
-                        flags.add(f);
-                }
-                return typeof p === 'string'
-                    ? regExpEscape(p)
-                    : p === exports.GLOBSTAR
-                        ? exports.GLOBSTAR
-                        : p._src;
-            });
-            pp.forEach((p, i) => {
-                const next = pp[i + 1];
-                const prev = pp[i - 1];
-                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
-                    return;
-                }
-                if (prev === undefined) {
-                    if (next !== undefined && next !== exports.GLOBSTAR) {
-                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
-                    }
-                    else {
-                        pp[i] = twoStar;
-                    }
-                }
-                else if (next === undefined) {
-                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
-                }
-                else if (next !== exports.GLOBSTAR) {
-                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
-                    pp[i + 1] = exports.GLOBSTAR;
-                }
-            });
-            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
-        })
-            .join('|');
-        // need to wrap in parens if we had more than one thing with |,
-        // otherwise only the first will be anchored to ^ and the last to $
-        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
-        // must match entire pattern
-        // ending in a * or ** will make it less strict.
-        re = '^' + open + re + close + '$';
-        // can match anything, as long as it's not this.
-        if (this.negate)
-            re = '^(?!' + re + ').+$';
-        try {
-            this.regexp = new RegExp(re, [...flags].join(''));
-            /* c8 ignore start */
-        }
-        catch (ex) {
-            // should be impossible
-            this.regexp = false;
-        }
+    async match(e, absolute, ifDir) {
+        const p = await this.matchCheck(e, ifDir);
+        if (p)
+            this.matchFinish(p, absolute);
+    }
+    matchSync(e, absolute, ifDir) {
+        const p = this.matchCheckSync(e, ifDir);
+        if (p)
+            this.matchFinish(p, absolute);
+    }
+    walkCB(target, patterns, cb) {
+        /* c8 ignore start */
+        if (this.signal?.aborted)
+            cb();
         /* c8 ignore stop */
-        return this.regexp;
+        this.walkCB2(target, patterns, new processor_js_1.Processor(this.opts), cb);
     }
-    slashSplit(p) {
-        // if p starts with // on windows, we preserve that
-        // so that UNC paths aren't broken.  Otherwise, any number of
-        // / characters are coalesced into one, unless
-        // preserveMultipleSlashes is set to true.
-        if (this.preserveMultipleSlashes) {
-            return p.split('/');
+    walkCB2(target, patterns, processor, cb) {
+        if (this.#childrenIgnored(target))
+            return cb();
+        if (this.signal?.aborted)
+            cb();
+        if (this.paused) {
+            this.onResume(() => this.walkCB2(target, patterns, processor, cb));
+            return;
         }
-        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
-            // add an extra '' for the one we lose
-            return ['', ...p.split(/\/+/)];
+        processor.processPatterns(target, patterns);
+        // done processing.  all of the above is sync, can be abstracted out.
+        // subwalks is a map of paths to the entry filters they need
+        // matches is a map of paths to [absolute, ifDir] tuples.
+        let tasks = 1;
+        const next = () => {
+            if (--tasks === 0)
+                cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+            if (this.#ignored(m))
+                continue;
+            tasks++;
+            this.match(m, absolute, ifDir).then(() => next());
         }
-        else {
-            return p.split(/\/+/);
+        for (const t of processor.subwalkTargets()) {
+            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
+                continue;
+            }
+            tasks++;
+            const childrenCached = t.readdirCached();
+            if (t.calledReaddir())
+                this.walkCB3(t, childrenCached, processor, next);
+            else {
+                t.readdirCB((_, entries) => this.walkCB3(t, entries, processor, next), true);
+            }
         }
+        next();
     }
-    match(f, partial = this.partial) {
-        this.debug('match', f, this.pattern);
-        // short-circuit in the case of busted things.
-        // comments, etc.
-        if (this.comment) {
-            return false;
+    walkCB3(target, entries, processor, cb) {
+        processor = processor.filterEntries(target, entries);
+        let tasks = 1;
+        const next = () => {
+            if (--tasks === 0)
+                cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+            if (this.#ignored(m))
+                continue;
+            tasks++;
+            this.match(m, absolute, ifDir).then(() => next());
         }
-        if (this.empty) {
-            return f === '';
+        for (const [target, patterns] of processor.subwalks.entries()) {
+            tasks++;
+            this.walkCB2(target, patterns, processor.child(), next);
         }
-        if (f === '/' && partial) {
-            return true;
+        next();
+    }
+    walkCBSync(target, patterns, cb) {
+        /* c8 ignore start */
+        if (this.signal?.aborted)
+            cb();
+        /* c8 ignore stop */
+        this.walkCB2Sync(target, patterns, new processor_js_1.Processor(this.opts), cb);
+    }
+    walkCB2Sync(target, patterns, processor, cb) {
+        if (this.#childrenIgnored(target))
+            return cb();
+        if (this.signal?.aborted)
+            cb();
+        if (this.paused) {
+            this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
+            return;
         }
-        const options = this.options;
-        // windows: need to use /, not \
-        if (this.isWindows) {
-            f = f.split('\\').join('/');
+        processor.processPatterns(target, patterns);
+        // done processing.  all of the above is sync, can be abstracted out.
+        // subwalks is a map of paths to the entry filters they need
+        // matches is a map of paths to [absolute, ifDir] tuples.
+        let tasks = 1;
+        const next = () => {
+            if (--tasks === 0)
+                cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+            if (this.#ignored(m))
+                continue;
+            this.matchSync(m, absolute, ifDir);
         }
-        // treat the test path as a set of pathparts.
-        const ff = this.slashSplit(f);
-        this.debug(this.pattern, 'split', ff);
-        // just ONE of the pattern sets in this.set needs to match
-        // in order for it to be valid.  If negating, then just one
-        // match means that we have failed.
-        // Either way, return on the first hit.
-        const set = this.set;
-        this.debug(this.pattern, 'set', set);
-        // Find the basename of the path by looking for the last non-empty segment
-        let filename = ff[ff.length - 1];
-        if (!filename) {
-            for (let i = ff.length - 2; !filename && i >= 0; i--) {
-                filename = ff[i];
+        for (const t of processor.subwalkTargets()) {
+            if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {
+                continue;
             }
+            tasks++;
+            const children = t.readdirSync();
+            this.walkCB3Sync(t, children, processor, next);
         }
-        for (let i = 0; i < set.length; i++) {
-            const pattern = set[i];
-            let file = ff;
-            if (options.matchBase && pattern.length === 1) {
-                file = [filename];
-            }
-            const hit = this.matchOne(file, pattern, partial);
-            if (hit) {
-                if (options.flipNegate) {
-                    return true;
+        next();
+    }
+    walkCB3Sync(target, entries, processor, cb) {
+        processor = processor.filterEntries(target, entries);
+        let tasks = 1;
+        const next = () => {
+            if (--tasks === 0)
+                cb();
+        };
+        for (const [m, absolute, ifDir] of processor.matches.entries()) {
+            if (this.#ignored(m))
+                continue;
+            this.matchSync(m, absolute, ifDir);
+        }
+        for (const [target, patterns] of processor.subwalks.entries()) {
+            tasks++;
+            this.walkCB2Sync(target, patterns, processor.child(), next);
+        }
+        next();
+    }
+}
+exports.GlobUtil = GlobUtil;
+class GlobWalker extends GlobUtil {
+    matches = new Set();
+    constructor(patterns, path, opts) {
+        super(patterns, path, opts);
+    }
+    matchEmit(e) {
+        this.matches.add(e);
+    }
+    async walk() {
+        if (this.signal?.aborted)
+            throw this.signal.reason;
+        if (this.path.isUnknown()) {
+            await this.path.lstat();
+        }
+        await new Promise((res, rej) => {
+            this.walkCB(this.path, this.patterns, () => {
+                if (this.signal?.aborted) {
+                    rej(this.signal.reason);
                 }
-                return !this.negate;
-            }
+                else {
+                    res(this.matches);
+                }
+            });
+        });
+        return this.matches;
+    }
+    walkSync() {
+        if (this.signal?.aborted)
+            throw this.signal.reason;
+        if (this.path.isUnknown()) {
+            this.path.lstatSync();
         }
-        // didn't get any hits.  this is success if it's a negative
-        // pattern, failure otherwise.
-        if (options.flipNegate) {
-            return false;
+        // nothing for the callback to do, because this never pauses
+        this.walkCBSync(this.path, this.patterns, () => {
+            if (this.signal?.aborted)
+                throw this.signal.reason;
+        });
+        return this.matches;
+    }
+}
+exports.GlobWalker = GlobWalker;
+class GlobStream extends GlobUtil {
+    results;
+    constructor(patterns, path, opts) {
+        super(patterns, path, opts);
+        this.results = new minipass_1.Minipass({
+            signal: this.signal,
+            objectMode: true,
+        });
+        this.results.on('drain', () => this.resume());
+        this.results.on('resume', () => this.resume());
+    }
+    matchEmit(e) {
+        this.results.write(e);
+        if (!this.results.flowing)
+            this.pause();
+    }
+    stream() {
+        const target = this.path;
+        if (target.isUnknown()) {
+            target.lstat().then(() => {
+                this.walkCB(target, this.patterns, () => this.results.end());
+            });
         }
-        return this.negate;
+        else {
+            this.walkCB(target, this.patterns, () => this.results.end());
+        }
+        return this.results;
     }
-    static defaults(def) {
-        return exports.minimatch.defaults(def).Minimatch;
+    streamSync() {
+        if (this.path.isUnknown()) {
+            this.path.lstatSync();
+        }
+        this.walkCBSync(this.path, this.patterns, () => this.results.end());
+        return this.results;
     }
 }
-exports.Minimatch = Minimatch;
-/* c8 ignore start */
-var ast_js_2 = __nccwpck_require__(10421);
-Object.defineProperty(exports, "AST", ({ enumerable: true, get: function () { return ast_js_2.AST; } }));
-var escape_js_2 = __nccwpck_require__(4578);
-Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return escape_js_2.escape; } }));
-var unescape_js_2 = __nccwpck_require__(11633);
-Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return unescape_js_2.unescape; } }));
-/* c8 ignore stop */
-exports.minimatch.AST = ast_js_1.AST;
-exports.minimatch.Minimatch = Minimatch;
-exports.minimatch.escape = escape_js_1.escape;
-exports.minimatch.unescape = unescape_js_1.unescape;
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 11633:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.unescape = void 0;
-/**
- * Un-escape a string that has been escaped with {@link escape}.
- *
- * If the {@link windowsPathsNoEscape} option is used, then square-brace
- * escapes are removed, but not backslash escapes.  For example, it will turn
- * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
- * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
- *
- * When `windowsPathsNoEscape` is not set, then both brace escapes and
- * backslash escapes are removed.
- *
- * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
- * or unescaped.
- */
-const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
-    return windowsPathsNoEscape
-        ? s.replace(/\[([^\/\\])\]/g, '$1')
-        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
-};
-exports.unescape = unescape;
-//# sourceMappingURL=unescape.js.map
+exports.GlobStream = GlobStream;
+//# sourceMappingURL=walker.js.map
 
 /***/ }),
 
@@ -77752,1975 +77403,2285 @@ class LRUCache {
         const fetchOpts = {
             signal: ac.signal,
             options,
-            context,
-        };
-        const cb = (v, updateCache = false) => {
-            const { aborted } = ac.signal;
-            const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
-            if (options.status) {
-                if (aborted && !updateCache) {
-                    options.status.fetchAborted = true;
-                    options.status.fetchError = ac.signal.reason;
-                    if (ignoreAbort)
-                        options.status.fetchAbortIgnored = true;
-                }
-                else {
-                    options.status.fetchResolved = true;
-                }
-            }
-            if (aborted && !ignoreAbort && !updateCache) {
-                return fetchFail(ac.signal.reason);
-            }
-            // either we didn't abort, and are still here, or we did, and ignored
-            const bf = p;
-            if (this.#valList[index] === p) {
-                if (v === undefined) {
-                    if (bf.__staleWhileFetching) {
-                        this.#valList[index] = bf.__staleWhileFetching;
-                    }
-                    else {
-                        this.#delete(k, 'fetch');
-                    }
-                }
-                else {
-                    if (options.status)
-                        options.status.fetchUpdated = true;
-                    this.set(k, v, fetchOpts.options);
-                }
-            }
-            return v;
-        };
-        const eb = (er) => {
-            if (options.status) {
-                options.status.fetchRejected = true;
-                options.status.fetchError = er;
-            }
-            return fetchFail(er);
-        };
-        const fetchFail = (er) => {
-            const { aborted } = ac.signal;
-            const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
-            const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
-            const noDelete = allowStale || options.noDeleteOnFetchRejection;
-            const bf = p;
-            if (this.#valList[index] === p) {
-                // if we allow stale on fetch rejections, then we need to ensure that
-                // the stale value is not removed from the cache when the fetch fails.
-                const del = !noDelete || bf.__staleWhileFetching === undefined;
-                if (del) {
-                    this.#delete(k, 'fetch');
-                }
-                else if (!allowStaleAborted) {
-                    // still replace the *promise* with the stale value,
-                    // since we are done with the promise at this point.
-                    // leave it untouched if we're still waiting for an
-                    // aborted background fetch that hasn't yet returned.
-                    this.#valList[index] = bf.__staleWhileFetching;
-                }
-            }
-            if (allowStale) {
-                if (options.status && bf.__staleWhileFetching !== undefined) {
-                    options.status.returnedStale = true;
-                }
-                return bf.__staleWhileFetching;
-            }
-            else if (bf.__returned === bf) {
-                throw er;
-            }
-        };
-        const pcall = (res, rej) => {
-            const fmp = this.#fetchMethod?.(k, v, fetchOpts);
-            if (fmp && fmp instanceof Promise) {
-                fmp.then(v => res(v === undefined ? undefined : v), rej);
-            }
-            // ignored, we go until we finish, regardless.
-            // defer check until we are actually aborting,
-            // so fetchMethod can override.
-            ac.signal.addEventListener('abort', () => {
-                if (!options.ignoreFetchAbort ||
-                    options.allowStaleOnFetchAbort) {
-                    res(undefined);
-                    // when it eventually resolves, update the cache.
-                    if (options.allowStaleOnFetchAbort) {
-                        res = v => cb(v, true);
-                    }
-                }
-            });
-        };
-        if (options.status)
-            options.status.fetchDispatched = true;
-        const p = new Promise(pcall).then(cb, eb);
-        const bf = Object.assign(p, {
-            __abortController: ac,
-            __staleWhileFetching: v,
-            __returned: undefined,
-        });
-        if (index === undefined) {
-            // internal, don't expose status.
-            this.set(k, bf, { ...fetchOpts.options, status: undefined });
-            index = this.#keyMap.get(k);
-        }
-        else {
-            this.#valList[index] = bf;
-        }
-        return bf;
-    }
-    #isBackgroundFetch(p) {
-        if (!this.#hasFetchMethod)
-            return false;
-        const b = p;
-        return (!!b &&
-            b instanceof Promise &&
-            b.hasOwnProperty('__staleWhileFetching') &&
-            b.__abortController instanceof AC);
-    }
-    async fetch(k, fetchOptions = {}) {
-        const { 
-        // 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 = false, status, signal, } = fetchOptions;
-        if (!this.#hasFetchMethod) {
-            if (status)
-                status.fetch = 'get';
-            return this.get(k, {
-                allowStale,
-                updateAgeOnGet,
-                noDeleteOnStaleGet,
-                status,
-            });
-        }
-        const options = {
-            allowStale,
-            updateAgeOnGet,
-            noDeleteOnStaleGet,
-            ttl,
-            noDisposeOnSet,
-            size,
-            sizeCalculation,
-            noUpdateTTL,
-            noDeleteOnFetchRejection,
-            allowStaleOnFetchRejection,
-            allowStaleOnFetchAbort,
-            ignoreFetchAbort,
-            status,
-            signal,
-        };
-        let index = this.#keyMap.get(k);
-        if (index === undefined) {
-            if (status)
-                status.fetch = 'miss';
-            const p = this.#backgroundFetch(k, index, options, context);
-            return (p.__returned = p);
-        }
-        else {
-            // in cache, maybe already fetching
-            const v = this.#valList[index];
-            if (this.#isBackgroundFetch(v)) {
-                const stale = allowStale && v.__staleWhileFetching !== undefined;
-                if (status) {
-                    status.fetch = 'inflight';
-                    if (stale)
-                        status.returnedStale = true;
-                }
-                return stale ? v.__staleWhileFetching : (v.__returned = v);
-            }
-            // if we force a refresh, that means do NOT serve the cached value,
-            // unless we are already in the process of refreshing the cache.
-            const isStale = this.#isStale(index);
-            if (!forceRefresh && !isStale) {
-                if (status)
-                    status.fetch = 'hit';
-                this.#moveToTail(index);
-                if (updateAgeOnGet) {
-                    this.#updateItemAge(index);
-                }
-                if (status)
-                    this.#statusTTL(status, index);
-                return v;
-            }
-            // ok, it is stale or a forced refresh, and not already fetching.
-            // refresh the cache.
-            const p = this.#backgroundFetch(k, index, options, context);
-            const hasStale = p.__staleWhileFetching !== undefined;
-            const staleVal = hasStale && allowStale;
-            if (status) {
-                status.fetch = isStale ? 'stale' : 'refresh';
-                if (staleVal && isStale)
-                    status.returnedStale = true;
-            }
-            return staleVal ? p.__staleWhileFetching : (p.__returned = p);
-        }
-    }
-    async forceFetch(k, fetchOptions = {}) {
-        const v = await this.fetch(k, fetchOptions);
-        if (v === undefined)
-            throw new Error('fetch() returned undefined');
-        return v;
-    }
-    memo(k, memoOptions = {}) {
-        const memoMethod = this.#memoMethod;
-        if (!memoMethod) {
-            throw new Error('no memoMethod provided to constructor');
-        }
-        const { context, forceRefresh, ...options } = memoOptions;
-        const v = this.get(k, options);
-        if (!forceRefresh && v !== undefined)
-            return v;
-        const vv = memoMethod(k, v, {
-            options,
-            context,
-        });
-        this.set(k, vv, options);
-        return vv;
-    }
-    /**
-     * 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 = {}) {
-        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
-        const index = this.#keyMap.get(k);
-        if (index !== undefined) {
-            const value = this.#valList[index];
-            const fetching = this.#isBackgroundFetch(value);
-            if (status)
-                this.#statusTTL(status, index);
-            if (this.#isStale(index)) {
-                if (status)
-                    status.get = 'stale';
-                // delete only if not an in-flight background fetch
-                if (!fetching) {
-                    if (!noDeleteOnStaleGet) {
-                        this.#delete(k, 'expire');
-                    }
-                    if (status && allowStale)
-                        status.returnedStale = true;
-                    return allowStale ? value : undefined;
-                }
-                else {
-                    if (status &&
-                        allowStale &&
-                        value.__staleWhileFetching !== undefined) {
-                        status.returnedStale = true;
-                    }
-                    return allowStale ? value.__staleWhileFetching : undefined;
-                }
-            }
-            else {
-                if (status)
-                    status.get = 'hit';
-                // if we're currently fetching it, we don't actually have it yet
-                // it's not stale, which means this isn't a staleWhileRefetching.
-                // If it's not stale, and fetching, AND has a __staleWhileFetching
-                // value, then that means the user fetched with {forceRefresh:true},
-                // so it's safe to return that value.
-                if (fetching) {
-                    return value.__staleWhileFetching;
-                }
-                this.#moveToTail(index);
-                if (updateAgeOnGet) {
-                    this.#updateItemAge(index);
-                }
-                return value;
-            }
-        }
-        else if (status) {
-            status.get = 'miss';
-        }
-    }
-    #connect(p, n) {
-        this.#prev[n] = p;
-        this.#next[p] = n;
-    }
-    #moveToTail(index) {
-        // if tail already, nothing to do
-        // if head, move head to next[index]
-        // else
-        //   move next[prev[index]] to next[index] (head has no prev)
-        //   move prev[next[index]] to prev[index]
-        // prev[index] = tail
-        // next[tail] = index
-        // tail = index
-        if (index !== this.#tail) {
-            if (index === this.#head) {
-                this.#head = this.#next[index];
-            }
-            else {
-                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) {
-        return this.#delete(k, 'delete');
-    }
-    #delete(k, reason) {
-        let deleted = false;
-        if (this.#size !== 0) {
-            const index = this.#keyMap.get(k);
-            if (index !== undefined) {
-                deleted = true;
-                if (this.#size === 1) {
-                    this.#clear(reason);
+            context,
+        };
+        const cb = (v, updateCache = false) => {
+            const { aborted } = ac.signal;
+            const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
+            if (options.status) {
+                if (aborted && !updateCache) {
+                    options.status.fetchAborted = true;
+                    options.status.fetchError = ac.signal.reason;
+                    if (ignoreAbort)
+                        options.status.fetchAbortIgnored = true;
                 }
                 else {
-                    this.#removeItemSize(index);
-                    const v = this.#valList[index];
-                    if (this.#isBackgroundFetch(v)) {
-                        v.__abortController.abort(new Error('deleted'));
-                    }
-                    else if (this.#hasDispose || this.#hasDisposeAfter) {
-                        if (this.#hasDispose) {
-                            this.#dispose?.(v, k, reason);
-                        }
-                        if (this.#hasDisposeAfter) {
-                            this.#disposed?.push([v, k, reason]);
-                        }
-                    }
-                    this.#keyMap.delete(k);
-                    this.#keyList[index] = undefined;
-                    this.#valList[index] = undefined;
-                    if (index === this.#tail) {
-                        this.#tail = this.#prev[index];
-                    }
-                    else if (index === this.#head) {
-                        this.#head = this.#next[index];
+                    options.status.fetchResolved = true;
+                }
+            }
+            if (aborted && !ignoreAbort && !updateCache) {
+                return fetchFail(ac.signal.reason);
+            }
+            // either we didn't abort, and are still here, or we did, and ignored
+            const bf = p;
+            if (this.#valList[index] === p) {
+                if (v === undefined) {
+                    if (bf.__staleWhileFetching) {
+                        this.#valList[index] = bf.__staleWhileFetching;
                     }
                     else {
-                        const pi = this.#prev[index];
-                        this.#next[pi] = this.#next[index];
-                        const ni = this.#next[index];
-                        this.#prev[ni] = this.#prev[index];
+                        this.#delete(k, 'fetch');
                     }
-                    this.#size--;
-                    this.#free.push(index);
+                }
+                else {
+                    if (options.status)
+                        options.status.fetchUpdated = true;
+                    this.set(k, v, fetchOpts.options);
                 }
             }
-        }
-        if (this.#hasDisposeAfter && this.#disposed?.length) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
-            }
-        }
-        return deleted;
-    }
-    /**
-     * Clear the cache entirely, throwing away all values.
-     */
-    clear() {
-        return this.#clear('delete');
-    }
-    #clear(reason) {
-        for (const index of this.#rindexes({ allowStale: true })) {
-            const v = this.#valList[index];
-            if (this.#isBackgroundFetch(v)) {
-                v.__abortController.abort(new Error('deleted'));
+            return v;
+        };
+        const eb = (er) => {
+            if (options.status) {
+                options.status.fetchRejected = true;
+                options.status.fetchError = er;
             }
-            else {
-                const k = this.#keyList[index];
-                if (this.#hasDispose) {
-                    this.#dispose?.(v, k, reason);
+            return fetchFail(er);
+        };
+        const fetchFail = (er) => {
+            const { aborted } = ac.signal;
+            const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
+            const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
+            const noDelete = allowStale || options.noDeleteOnFetchRejection;
+            const bf = p;
+            if (this.#valList[index] === p) {
+                // if we allow stale on fetch rejections, then we need to ensure that
+                // the stale value is not removed from the cache when the fetch fails.
+                const del = !noDelete || bf.__staleWhileFetching === undefined;
+                if (del) {
+                    this.#delete(k, 'fetch');
                 }
-                if (this.#hasDisposeAfter) {
-                    this.#disposed?.push([v, k, reason]);
+                else if (!allowStaleAborted) {
+                    // still replace the *promise* with the stale value,
+                    // since we are done with the promise at this point.
+                    // leave it untouched if we're still waiting for an
+                    // aborted background fetch that hasn't yet returned.
+                    this.#valList[index] = bf.__staleWhileFetching;
                 }
             }
-        }
-        this.#keyMap.clear();
-        this.#valList.fill(undefined);
-        this.#keyList.fill(undefined);
-        if (this.#ttls && this.#starts) {
-            this.#ttls.fill(0);
-            this.#starts.fill(0);
-        }
-        if (this.#sizes) {
-            this.#sizes.fill(0);
-        }
-        this.#head = 0;
-        this.#tail = 0;
-        this.#free.length = 0;
-        this.#calculatedSize = 0;
-        this.#size = 0;
-        if (this.#hasDisposeAfter && this.#disposed) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
+            if (allowStale) {
+                if (options.status && bf.__staleWhileFetching !== undefined) {
+                    options.status.returnedStale = true;
+                }
+                return bf.__staleWhileFetching;
             }
-        }
-    }
-}
-exports.LRUCache = LRUCache;
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 32477:
-/***/ ((__unused_webpack_module, exports) => {
-
-"use strict";
-
-/**
- * @module LRUCache
- */
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LRUCache = void 0;
-const perf = typeof performance === 'object' &&
-    performance &&
-    typeof performance.now === 'function'
-    ? performance
-    : Date;
-const warned = new Set();
-/* c8 ignore start */
-const PROCESS = (typeof process === 'object' && !!process ? process : {});
-/* c8 ignore start */
-const emitWarning = (msg, type, code, fn) => {
-    typeof PROCESS.emitWarning === 'function'
-        ? PROCESS.emitWarning(msg, type, code, fn)
-        : console.error(`[${code}] ${type}: ${msg}`);
-};
-let AC = globalThis.AbortController;
-let AS = globalThis.AbortSignal;
-/* c8 ignore start */
-if (typeof AC === 'undefined') {
-    //@ts-ignore
-    AS = class AbortSignal {
-        onabort;
-        _onabort = [];
-        reason;
-        aborted = false;
-        addEventListener(_, fn) {
-            this._onabort.push(fn);
-        }
-    };
-    //@ts-ignore
-    AC = class AbortController {
-        constructor() {
-            warnACPolyfill();
-        }
-        signal = new AS();
-        abort(reason) {
-            if (this.signal.aborted)
-                return;
-            //@ts-ignore
-            this.signal.reason = reason;
-            //@ts-ignore
-            this.signal.aborted = true;
-            //@ts-ignore
-            for (const fn of this.signal._onabort) {
-                fn(reason);
+            else if (bf.__returned === bf) {
+                throw er;
             }
-            this.signal.onabort?.(reason);
+        };
+        const pcall = (res, rej) => {
+            const fmp = this.#fetchMethod?.(k, v, fetchOpts);
+            if (fmp && fmp instanceof Promise) {
+                fmp.then(v => res(v === undefined ? undefined : v), rej);
+            }
+            // ignored, we go until we finish, regardless.
+            // defer check until we are actually aborting,
+            // so fetchMethod can override.
+            ac.signal.addEventListener('abort', () => {
+                if (!options.ignoreFetchAbort ||
+                    options.allowStaleOnFetchAbort) {
+                    res(undefined);
+                    // when it eventually resolves, update the cache.
+                    if (options.allowStaleOnFetchAbort) {
+                        res = v => cb(v, true);
+                    }
+                }
+            });
+        };
+        if (options.status)
+            options.status.fetchDispatched = true;
+        const p = new Promise(pcall).then(cb, eb);
+        const bf = Object.assign(p, {
+            __abortController: ac,
+            __staleWhileFetching: v,
+            __returned: undefined,
+        });
+        if (index === undefined) {
+            // internal, don't expose status.
+            this.set(k, bf, { ...fetchOpts.options, status: undefined });
+            index = this.#keyMap.get(k);
         }
-    };
-    let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
-    const warnACPolyfill = () => {
-        if (!printACPolyfillWarning)
-            return;
-        printACPolyfillWarning = false;
-        emitWarning('AbortController is not defined. If using lru-cache in ' +
-            'node 14, load an AbortController polyfill from the ' +
-            '`node-abort-controller` package. A minimal polyfill is ' +
-            'provided for use by LRUCache.fetch(), but it should not be ' +
-            'relied upon in other contexts (eg, passing it to other APIs that ' +
-            'use AbortController/AbortSignal might have undesirable effects). ' +
-            'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
-    };
-}
-/* c8 ignore stop */
-const shouldWarn = (code) => !warned.has(code);
-const TYPE = Symbol('type');
-const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
-/* c8 ignore start */
-// This is a little bit ridiculous, tbh.
-// The maximum array length is 2^32-1 or thereabouts on most JS impls.
-// And well before that point, you're caching the entire world, I mean,
-// that's ~32GB of just integers for the next/prev links, plus whatever
-// else to hold that many keys and values.  Just filling the memory with
-// zeroes at init time is brutal when you get that big.
-// But why not be complete?
-// Maybe in the future, these limits will have expanded.
-const getUintArray = (max) => !isPosInt(max)
-    ? null
-    : 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;
-/* c8 ignore stop */
-class ZeroArray extends Array {
-    constructor(size) {
-        super(size);
-        this.fill(0);
-    }
-}
-class Stack {
-    heap;
-    length;
-    // private constructor
-    static #constructing = false;
-    static create(max) {
-        const HeapCls = getUintArray(max);
-        if (!HeapCls)
-            return [];
-        Stack.#constructing = true;
-        const s = new Stack(max, HeapCls);
-        Stack.#constructing = false;
-        return s;
-    }
-    constructor(max, HeapCls) {
-        /* c8 ignore start */
-        if (!Stack.#constructing) {
-            throw new TypeError('instantiate Stack using Stack.create(n)');
+        else {
+            this.#valList[index] = bf;
         }
-        /* c8 ignore stop */
-        this.heap = new HeapCls(max);
-        this.length = 0;
-    }
-    push(n) {
-        this.heap[this.length++] = n;
+        return bf;
     }
-    pop() {
-        return this.heap[--this.length];
+    #isBackgroundFetch(p) {
+        if (!this.#hasFetchMethod)
+            return false;
+        const b = p;
+        return (!!b &&
+            b instanceof Promise &&
+            b.hasOwnProperty('__staleWhileFetching') &&
+            b.__abortController instanceof AC);
     }
-}
-/**
- * Default export, the thing you're using this module to get.
- *
- * The `K` and `V` types define the key and value types, respectively. The
- * optional `FC` type defines the type of the `context` object passed to
- * `cache.fetch()` and `cache.memo()`.
- *
- * Keys and values **must not** be `null` or `undefined`.
- *
- * All properties from the options object (with the exception of `max`,
- * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
- * added as normal public members. (The listed options are read-only getters.)
- *
- * Changing any of these will alter the defaults for subsequent method calls.
- */
-class LRUCache {
-    // options that cannot be changed without disaster
-    #max;
-    #maxSize;
-    #dispose;
-    #disposeAfter;
-    #fetchMethod;
-    #memoMethod;
-    /**
-     * {@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),
+    async fetch(k, fetchOptions = {}) {
+        const { 
+        // 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 = false, status, signal, } = fetchOptions;
+        if (!this.#hasFetchMethod) {
+            if (status)
+                status.fetch = 'get';
+            return this.get(k, {
+                allowStale,
+                updateAgeOnGet,
+                noDeleteOnStaleGet,
+                status,
+            });
+        }
+        const options = {
+            allowStale,
+            updateAgeOnGet,
+            noDeleteOnStaleGet,
+            ttl,
+            noDisposeOnSet,
+            size,
+            sizeCalculation,
+            noUpdateTTL,
+            noDeleteOnFetchRejection,
+            allowStaleOnFetchRejection,
+            allowStaleOnFetchAbort,
+            ignoreFetchAbort,
+            status,
+            signal,
         };
+        let index = this.#keyMap.get(k);
+        if (index === undefined) {
+            if (status)
+                status.fetch = 'miss';
+            const p = this.#backgroundFetch(k, index, options, context);
+            return (p.__returned = p);
+        }
+        else {
+            // in cache, maybe already fetching
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                const stale = allowStale && v.__staleWhileFetching !== undefined;
+                if (status) {
+                    status.fetch = 'inflight';
+                    if (stale)
+                        status.returnedStale = true;
+                }
+                return stale ? v.__staleWhileFetching : (v.__returned = v);
+            }
+            // if we force a refresh, that means do NOT serve the cached value,
+            // unless we are already in the process of refreshing the cache.
+            const isStale = this.#isStale(index);
+            if (!forceRefresh && !isStale) {
+                if (status)
+                    status.fetch = 'hit';
+                this.#moveToTail(index);
+                if (updateAgeOnGet) {
+                    this.#updateItemAge(index);
+                }
+                if (status)
+                    this.#statusTTL(status, index);
+                return v;
+            }
+            // ok, it is stale or a forced refresh, and not already fetching.
+            // refresh the cache.
+            const p = this.#backgroundFetch(k, index, options, context);
+            const hasStale = p.__staleWhileFetching !== undefined;
+            const staleVal = hasStale && allowStale;
+            if (status) {
+                status.fetch = isStale ? 'stale' : 'refresh';
+                if (staleVal && isStale)
+                    status.returnedStale = true;
+            }
+            return staleVal ? p.__staleWhileFetching : (p.__returned = p);
+        }
     }
-    // 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;
+    async forceFetch(k, fetchOptions = {}) {
+        const v = await this.fetch(k, fetchOptions);
+        if (v === undefined)
+            throw new Error('fetch() returned undefined');
+        return v;
     }
-    /**
-     * The total computed size of items in the cache (read-only)
-     */
-    get calculatedSize() {
-        return this.#calculatedSize;
+    memo(k, memoOptions = {}) {
+        const memoMethod = this.#memoMethod;
+        if (!memoMethod) {
+            throw new Error('no memoMethod provided to constructor');
+        }
+        const { context, forceRefresh, ...options } = memoOptions;
+        const v = this.get(k, options);
+        if (!forceRefresh && v !== undefined)
+            return v;
+        const vv = memoMethod(k, v, {
+            options,
+            context,
+        });
+        this.set(k, vv, options);
+        return vv;
     }
     /**
-     * The number of items stored in the cache (read-only)
+     * 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 size() {
-        return this.#size;
+    get(k, getOptions = {}) {
+        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
+        const index = this.#keyMap.get(k);
+        if (index !== undefined) {
+            const value = this.#valList[index];
+            const fetching = this.#isBackgroundFetch(value);
+            if (status)
+                this.#statusTTL(status, index);
+            if (this.#isStale(index)) {
+                if (status)
+                    status.get = 'stale';
+                // delete only if not an in-flight background fetch
+                if (!fetching) {
+                    if (!noDeleteOnStaleGet) {
+                        this.#delete(k, 'expire');
+                    }
+                    if (status && allowStale)
+                        status.returnedStale = true;
+                    return allowStale ? value : undefined;
+                }
+                else {
+                    if (status &&
+                        allowStale &&
+                        value.__staleWhileFetching !== undefined) {
+                        status.returnedStale = true;
+                    }
+                    return allowStale ? value.__staleWhileFetching : undefined;
+                }
+            }
+            else {
+                if (status)
+                    status.get = 'hit';
+                // if we're currently fetching it, we don't actually have it yet
+                // it's not stale, which means this isn't a staleWhileRefetching.
+                // If it's not stale, and fetching, AND has a __staleWhileFetching
+                // value, then that means the user fetched with {forceRefresh:true},
+                // so it's safe to return that value.
+                if (fetching) {
+                    return value.__staleWhileFetching;
+                }
+                this.#moveToTail(index);
+                if (updateAgeOnGet) {
+                    this.#updateItemAge(index);
+                }
+                return value;
+            }
+        }
+        else if (status) {
+            status.get = 'miss';
+        }
     }
-    /**
-     * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
-     */
-    get fetchMethod() {
-        return this.#fetchMethod;
+    #connect(p, n) {
+        this.#prev[n] = p;
+        this.#next[p] = n;
     }
-    get memoMethod() {
-        return this.#memoMethod;
+    #moveToTail(index) {
+        // if tail already, nothing to do
+        // if head, move head to next[index]
+        // else
+        //   move next[prev[index]] to next[index] (head has no prev)
+        //   move prev[next[index]] to prev[index]
+        // prev[index] = tail
+        // next[tail] = index
+        // tail = index
+        if (index !== this.#tail) {
+            if (index === this.#head) {
+                this.#head = this.#next[index];
+            }
+            else {
+                this.#connect(this.#prev[index], this.#next[index]);
+            }
+            this.#connect(this.#tail, index);
+            this.#tail = index;
+        }
     }
     /**
-     * {@link LRUCache.OptionsBase.dispose} (read-only)
+     * Deletes a key out of the cache.
+     *
+     * Returns true if the key was deleted, false otherwise.
      */
-    get dispose() {
-        return this.#dispose;
+    delete(k) {
+        return this.#delete(k, 'delete');
+    }
+    #delete(k, reason) {
+        let deleted = false;
+        if (this.#size !== 0) {
+            const index = this.#keyMap.get(k);
+            if (index !== undefined) {
+                deleted = true;
+                if (this.#size === 1) {
+                    this.#clear(reason);
+                }
+                else {
+                    this.#removeItemSize(index);
+                    const v = this.#valList[index];
+                    if (this.#isBackgroundFetch(v)) {
+                        v.__abortController.abort(new Error('deleted'));
+                    }
+                    else if (this.#hasDispose || this.#hasDisposeAfter) {
+                        if (this.#hasDispose) {
+                            this.#dispose?.(v, k, reason);
+                        }
+                        if (this.#hasDisposeAfter) {
+                            this.#disposed?.push([v, k, reason]);
+                        }
+                    }
+                    this.#keyMap.delete(k);
+                    this.#keyList[index] = undefined;
+                    this.#valList[index] = undefined;
+                    if (index === this.#tail) {
+                        this.#tail = this.#prev[index];
+                    }
+                    else if (index === this.#head) {
+                        this.#head = this.#next[index];
+                    }
+                    else {
+                        const pi = this.#prev[index];
+                        this.#next[pi] = this.#next[index];
+                        const ni = this.#next[index];
+                        this.#prev[ni] = this.#prev[index];
+                    }
+                    this.#size--;
+                    this.#free.push(index);
+                }
+            }
+        }
+        if (this.#hasDisposeAfter && this.#disposed?.length) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
+            }
+        }
+        return deleted;
     }
     /**
-     * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
+     * Clear the cache entirely, throwing away all values.
      */
-    get disposeAfter() {
-        return this.#disposeAfter;
+    clear() {
+        return this.#clear('delete');
     }
-    constructor(options) {
-        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
-        if (max !== 0 && !isPosInt(max)) {
-            throw new TypeError('max option must be a nonnegative integer');
-        }
-        const UintArray = max ? getUintArray(max) : Array;
-        if (!UintArray) {
-            throw new Error('invalid max value: ' + max);
-        }
-        this.#max = max;
-        this.#maxSize = maxSize;
-        this.maxEntrySize = maxEntrySize || this.#maxSize;
-        this.sizeCalculation = sizeCalculation;
-        if (this.sizeCalculation) {
-            if (!this.#maxSize && !this.maxEntrySize) {
-                throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
+    #clear(reason) {
+        for (const index of this.#rindexes({ allowStale: true })) {
+            const v = this.#valList[index];
+            if (this.#isBackgroundFetch(v)) {
+                v.__abortController.abort(new Error('deleted'));
             }
-            if (typeof this.sizeCalculation !== 'function') {
-                throw new TypeError('sizeCalculation set to non-function');
+            else {
+                const k = this.#keyList[index];
+                if (this.#hasDispose) {
+                    this.#dispose?.(v, k, reason);
+                }
+                if (this.#hasDisposeAfter) {
+                    this.#disposed?.push([v, k, reason]);
+                }
             }
         }
-        if (memoMethod !== undefined &&
-            typeof memoMethod !== 'function') {
-            throw new TypeError('memoMethod must be a function if defined');
+        this.#keyMap.clear();
+        this.#valList.fill(undefined);
+        this.#keyList.fill(undefined);
+        if (this.#ttls && this.#starts) {
+            this.#ttls.fill(0);
+            this.#starts.fill(0);
         }
-        this.#memoMethod = memoMethod;
-        if (fetchMethod !== undefined &&
-            typeof fetchMethod !== 'function') {
-            throw new TypeError('fetchMethod must be a function if specified');
+        if (this.#sizes) {
+            this.#sizes.fill(0);
         }
-        this.#fetchMethod = fetchMethod;
-        this.#hasFetchMethod = !!fetchMethod;
-        this.#keyMap = new Map();
-        this.#keyList = new Array(max).fill(undefined);
-        this.#valList = new Array(max).fill(undefined);
-        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.#free.length = 0;
         this.#calculatedSize = 0;
-        if (typeof dispose === 'function') {
-            this.#dispose = dispose;
+        this.#size = 0;
+        if (this.#hasDisposeAfter && this.#disposed) {
+            const dt = this.#disposed;
+            let task;
+            while ((task = dt?.shift())) {
+                this.#disposeAfter?.(...task);
+            }
         }
-        if (typeof disposeAfter === 'function') {
-            this.#disposeAfter = disposeAfter;
-            this.#disposed = [];
+    }
+}
+exports.LRUCache = LRUCache;
+//# sourceMappingURL=index.js.map
+
+/***/ }),
+
+/***/ 30013:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.assertValidPattern = void 0;
+const MAX_PATTERN_LENGTH = 1024 * 64;
+const assertValidPattern = (pattern) => {
+    if (typeof pattern !== 'string') {
+        throw new TypeError('invalid pattern');
+    }
+    if (pattern.length > MAX_PATTERN_LENGTH) {
+        throw new TypeError('pattern is too long');
+    }
+};
+exports.assertValidPattern = assertValidPattern;
+//# sourceMappingURL=assert-valid-pattern.js.map
+
+/***/ }),
+
+/***/ 6215:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+"use strict";
+
+// parse a single path portion
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AST = void 0;
+const brace_expressions_js_1 = __nccwpck_require__(10038);
+const unescape_js_1 = __nccwpck_require__(18047);
+const types = new Set(['!', '?', '+', '*', '@']);
+const isExtglobType = (c) => types.has(c);
+// Patterns that get prepended to bind to the start of either the
+// entire string, or just a single path portion, to prevent dots
+// and/or traversal patterns, when needed.
+// Exts don't need the ^ or / bit, because the root binds that already.
+const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
+const startNoDot = '(?!\\.)';
+// characters that indicate a start of pattern needs the "no dots" bit,
+// because a dot *might* be matched. ( is not in the list, because in
+// the case of a child extglob, it will handle the prevention itself.
+const addPatternStart = new Set(['[', '.']);
+// cases where traversal is A-OK, no dot prevention needed
+const justDots = new Set(['..', '.']);
+const reSpecials = new Set('().*{}+?[]^$\\!');
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// any single thing other than /
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// use + when we need to ensure that *something* matches, because the * is
+// the only thing in the path portion.
+const starNoEmpty = qmark + '+?';
+// remove the \ chars that we added if we end up doing a nonmagic compare
+// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
+class AST {
+    type;
+    #root;
+    #hasMagic;
+    #uflag = false;
+    #parts = [];
+    #parent;
+    #parentIndex;
+    #negs;
+    #filledNegs = false;
+    #options;
+    #toString;
+    // set to true if it's an extglob with no children
+    // (which really means one child of '')
+    #emptyExt = false;
+    constructor(type, parent, options = {}) {
+        this.type = type;
+        // extglobs are inherently magical
+        if (type)
+            this.#hasMagic = true;
+        this.#parent = parent;
+        this.#root = this.#parent ? this.#parent.#root : this;
+        this.#options = this.#root === this ? options : this.#root.#options;
+        this.#negs = this.#root === this ? [] : this.#root.#negs;
+        if (type === '!' && !this.#root.#filledNegs)
+            this.#negs.push(this);
+        this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
+    }
+    get hasMagic() {
+        /* c8 ignore start */
+        if (this.#hasMagic !== undefined)
+            return this.#hasMagic;
+        /* c8 ignore stop */
+        for (const p of this.#parts) {
+            if (typeof p === 'string')
+                continue;
+            if (p.type || p.hasMagic)
+                return (this.#hasMagic = true);
+        }
+        // note: will be undefined until we generate the regexp src and find out
+        return this.#hasMagic;
+    }
+    // reconstructs the pattern
+    toString() {
+        if (this.#toString !== undefined)
+            return this.#toString;
+        if (!this.type) {
+            return (this.#toString = this.#parts.map(p => String(p)).join(''));
         }
         else {
-            this.#disposeAfter = undefined;
-            this.#disposed = undefined;
+            return (this.#toString =
+                this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
         }
-        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;
-        // NB: maxEntrySize is set to maxSize if it's set
-        if (this.maxEntrySize !== 0) {
-            if (this.#maxSize !== 0) {
-                if (!isPosInt(this.#maxSize)) {
-                    throw new TypeError('maxSize must be a positive integer if specified');
+    }
+    #fillNegs() {
+        /* c8 ignore start */
+        if (this !== this.#root)
+            throw new Error('should only call on root');
+        if (this.#filledNegs)
+            return this;
+        /* c8 ignore stop */
+        // call toString() once to fill this out
+        this.toString();
+        this.#filledNegs = true;
+        let n;
+        while ((n = this.#negs.pop())) {
+            if (n.type !== '!')
+                continue;
+            // walk up the tree, appending everthing that comes AFTER parentIndex
+            let p = n;
+            let pp = p.#parent;
+            while (pp) {
+                for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
+                    for (const part of n.#parts) {
+                        /* c8 ignore start */
+                        if (typeof part === 'string') {
+                            throw new Error('string part in extglob AST??');
+                        }
+                        /* c8 ignore stop */
+                        part.copyIn(pp.#parts[i]);
+                    }
+                }
+                p = pp;
+                pp = p.#parent;
+            }
+        }
+        return this;
+    }
+    push(...parts) {
+        for (const p of parts) {
+            if (p === '')
+                continue;
+            /* c8 ignore start */
+            if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
+                throw new Error('invalid part: ' + p);
+            }
+            /* c8 ignore stop */
+            this.#parts.push(p);
+        }
+    }
+    toJSON() {
+        const ret = this.type === null
+            ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
+            : [this.type, ...this.#parts.map(p => p.toJSON())];
+        if (this.isStart() && !this.type)
+            ret.unshift([]);
+        if (this.isEnd() &&
+            (this === this.#root ||
+                (this.#root.#filledNegs && this.#parent?.type === '!'))) {
+            ret.push({});
+        }
+        return ret;
+    }
+    isStart() {
+        if (this.#root === this)
+            return true;
+        // if (this.type) return !!this.#parent?.isStart()
+        if (!this.#parent?.isStart())
+            return false;
+        if (this.#parentIndex === 0)
+            return true;
+        // if everything AHEAD of this is a negation, then it's still the "start"
+        const p = this.#parent;
+        for (let i = 0; i < this.#parentIndex; i++) {
+            const pp = p.#parts[i];
+            if (!(pp instanceof AST && pp.type === '!')) {
+                return false;
+            }
+        }
+        return true;
+    }
+    isEnd() {
+        if (this.#root === this)
+            return true;
+        if (this.#parent?.type === '!')
+            return true;
+        if (!this.#parent?.isEnd())
+            return false;
+        if (!this.type)
+            return this.#parent?.isEnd();
+        // if not root, it'll always have a parent
+        /* c8 ignore start */
+        const pl = this.#parent ? this.#parent.#parts.length : 0;
+        /* c8 ignore stop */
+        return this.#parentIndex === pl - 1;
+    }
+    copyIn(part) {
+        if (typeof part === 'string')
+            this.push(part);
+        else
+            this.push(part.clone(this));
+    }
+    clone(parent) {
+        const c = new AST(this.type, parent);
+        for (const p of this.#parts) {
+            c.copyIn(p);
+        }
+        return c;
+    }
+    static #parseAST(str, ast, pos, opt) {
+        let escaping = false;
+        let inBrace = false;
+        let braceStart = -1;
+        let braceNeg = false;
+        if (ast.type === null) {
+            // outside of a extglob, append until we find a start
+            let i = pos;
+            let acc = '';
+            while (i < str.length) {
+                const c = str.charAt(i++);
+                // still accumulate escapes at this point, but we do ignore
+                // starts that are escaped
+                if (escaping || c === '\\') {
+                    escaping = !escaping;
+                    acc += c;
+                    continue;
                 }
+                if (inBrace) {
+                    if (i === braceStart + 1) {
+                        if (c === '^' || c === '!') {
+                            braceNeg = true;
+                        }
+                    }
+                    else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+                        inBrace = false;
+                    }
+                    acc += c;
+                    continue;
+                }
+                else if (c === '[') {
+                    inBrace = true;
+                    braceStart = i;
+                    braceNeg = false;
+                    acc += c;
+                    continue;
+                }
+                if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
+                    ast.push(acc);
+                    acc = '';
+                    const ext = new AST(c, ast);
+                    i = AST.#parseAST(str, ext, i, opt);
+                    ast.push(ext);
+                    continue;
+                }
+                acc += c;
             }
-            if (!isPosInt(this.maxEntrySize)) {
-                throw new TypeError('maxEntrySize must be a positive integer if specified');
-            }
-            this.#initializeSizeTracking();
-        }
-        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;
-        if (this.ttl) {
-            if (!isPosInt(this.ttl)) {
-                throw new TypeError('ttl must be a positive integer if specified');
-            }
-            this.#initializeTTLTracking();
-        }
-        // do not allow completely unbounded caches
-        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
-            throw new TypeError('At least one of max, maxSize, or ttl is required');
+            ast.push(acc);
+            return i;
         }
-        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
-            const code = 'LRU_CACHE_UNBOUNDED';
-            if (shouldWarn(code)) {
-                warned.add(code);
-                const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
-                    'result in unbounded memory consumption.';
-                emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
+        // some kind of extglob, pos is at the (
+        // find the next | or )
+        let i = pos + 1;
+        let part = new AST(null, ast);
+        const parts = [];
+        let acc = '';
+        while (i < str.length) {
+            const c = str.charAt(i++);
+            // still accumulate escapes at this point, but we do ignore
+            // starts that are escaped
+            if (escaping || c === '\\') {
+                escaping = !escaping;
+                acc += c;
+                continue;
             }
-        }
-    }
-    /**
-     * Return the number of ms left in the item's TTL. If item is not in cache,
-     * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
-     */
-    getRemainingTTL(key) {
-        return this.#keyMap.has(key) ? Infinity : 0;
-    }
-    #initializeTTLTracking() {
-        const ttls = new ZeroArray(this.#max);
-        const starts = new ZeroArray(this.#max);
-        this.#ttls = ttls;
-        this.#starts = starts;
-        this.#setItemTTL = (index, ttl, start = perf.now()) => {
-            starts[index] = ttl !== 0 ? start : 0;
-            ttls[index] = ttl;
-            if (ttl !== 0 && this.ttlAutopurge) {
-                const t = setTimeout(() => {
-                    if (this.#isStale(index)) {
-                        this.#delete(this.#keyList[index], 'expire');
+            if (inBrace) {
+                if (i === braceStart + 1) {
+                    if (c === '^' || c === '!') {
+                        braceNeg = true;
                     }
-                }, ttl + 1);
-                // unref() not supported on all platforms
-                /* c8 ignore start */
-                if (t.unref) {
-                    t.unref();
                 }
-                /* c8 ignore stop */
+                else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
+                    inBrace = false;
+                }
+                acc += c;
+                continue;
             }
-        };
-        this.#updateItemAge = index => {
-            starts[index] = ttls[index] !== 0 ? perf.now() : 0;
-        };
-        this.#statusTTL = (status, index) => {
-            if (ttls[index]) {
-                const ttl = ttls[index];
-                const start = starts[index];
-                /* c8 ignore next */
-                if (!ttl || !start)
-                    return;
-                status.ttl = ttl;
-                status.start = start;
-                status.now = cachedNow || getNow();
-                const age = status.now - start;
-                status.remainingTTL = ttl - age;
+            else if (c === '[') {
+                inBrace = true;
+                braceStart = i;
+                braceNeg = false;
+                acc += c;
+                continue;
             }
-        };
-        // debounce calls to perf.now() to 1s so we're not hitting
-        // that costly call repeatedly.
-        let cachedNow = 0;
-        const getNow = () => {
-            const n = perf.now();
-            if (this.ttlResolution > 0) {
-                cachedNow = n;
-                const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
-                // not available on all platforms
-                /* c8 ignore start */
-                if (t.unref) {
-                    t.unref();
-                }
-                /* c8 ignore stop */
+            if (isExtglobType(c) && str.charAt(i) === '(') {
+                part.push(acc);
+                acc = '';
+                const ext = new AST(c, part);
+                part.push(ext);
+                i = AST.#parseAST(str, ext, i, opt);
+                continue;
             }
-            return n;
-        };
-        this.getRemainingTTL = key => {
-            const index = this.#keyMap.get(key);
-            if (index === undefined) {
-                return 0;
+            if (c === '|') {
+                part.push(acc);
+                acc = '';
+                parts.push(part);
+                part = new AST(null, ast);
+                continue;
             }
-            const ttl = ttls[index];
-            const start = starts[index];
-            if (!ttl || !start) {
-                return Infinity;
+            if (c === ')') {
+                if (acc === '' && ast.#parts.length === 0) {
+                    ast.#emptyExt = true;
+                }
+                part.push(acc);
+                acc = '';
+                ast.push(...parts, part);
+                return i;
             }
-            const age = (cachedNow || getNow()) - start;
-            return ttl - age;
-        };
-        this.#isStale = index => {
-            const s = starts[index];
-            const t = ttls[index];
-            return !!t && !!s && (cachedNow || getNow()) - s > t;
-        };
+            acc += c;
+        }
+        // unfinished extglob
+        // if we got here, it was a malformed extglob! not an extglob, but
+        // maybe something else in there.
+        ast.type = null;
+        ast.#hasMagic = undefined;
+        ast.#parts = [str.substring(pos - 1)];
+        return i;
     }
-    // conditionally set private methods related to TTL
-    #updateItemAge = () => { };
-    #statusTTL = () => { };
-    #setItemTTL = () => { };
-    /* c8 ignore stop */
-    #isStale = () => false;
-    #initializeSizeTracking() {
-        const 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) => {
-            // provisionally accept background fetches.
-            // actual value size will be checked when they return.
-            if (this.#isBackgroundFetch(v)) {
-                return 0;
-            }
-            if (!isPosInt(size)) {
-                if (sizeCalculation) {
-                    if (typeof sizeCalculation !== 'function') {
-                        throw new TypeError('sizeCalculation must be a function');
-                    }
-                    size = sizeCalculation(v, k);
-                    if (!isPosInt(size)) {
-                        throw new TypeError('sizeCalculation return invalid (expect positive integer)');
+    static fromGlob(pattern, options = {}) {
+        const ast = new AST(null, undefined, options);
+        AST.#parseAST(pattern, ast, 0, options);
+        return ast;
+    }
+    // returns the regular expression if there's magic, or the unescaped
+    // string if not.
+    toMMPattern() {
+        // should only be called on root
+        /* c8 ignore start */
+        if (this !== this.#root)
+            return this.#root.toMMPattern();
+        /* c8 ignore stop */
+        const glob = this.toString();
+        const [re, body, hasMagic, uflag] = this.toRegExpSource();
+        // if we're in nocase mode, and not nocaseMagicOnly, then we do
+        // still need a regular expression if we have to case-insensitively
+        // match capital/lowercase characters.
+        const anyMagic = hasMagic ||
+            this.#hasMagic ||
+            (this.#options.nocase &&
+                !this.#options.nocaseMagicOnly &&
+                glob.toUpperCase() !== glob.toLowerCase());
+        if (!anyMagic) {
+            return body;
+        }
+        const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
+        return Object.assign(new RegExp(`^${re}$`, flags), {
+            _src: re,
+            _glob: glob,
+        });
+    }
+    get options() {
+        return this.#options;
+    }
+    // returns the string match, the regexp source, whether there's magic
+    // in the regexp (so a regular expression is required) and whether or
+    // not the uflag is needed for the regular expression (for posix classes)
+    // TODO: instead of injecting the start/end at this point, just return
+    // the BODY of the regexp, along with the start/end portions suitable
+    // for binding the start/end in either a joined full-path makeRe context
+    // (where we bind to (^|/), or a standalone matchPart context (where
+    // we bind to ^, and not /).  Otherwise slashes get duped!
+    //
+    // In part-matching mode, the start is:
+    // - if not isStart: nothing
+    // - if traversal possible, but not allowed: ^(?!\.\.?$)
+    // - if dots allowed or not possible: ^
+    // - if dots possible and not allowed: ^(?!\.)
+    // end is:
+    // - if not isEnd(): nothing
+    // - else: $
+    //
+    // In full-path matching mode, we put the slash at the START of the
+    // pattern, so start is:
+    // - if first pattern: same as part-matching mode
+    // - if not isStart(): nothing
+    // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
+    // - if dots allowed or not possible: /
+    // - if dots possible and not allowed: /(?!\.)
+    // end is:
+    // - if last pattern, same as part-matching mode
+    // - else nothing
+    //
+    // Always put the (?:$|/) on negated tails, though, because that has to be
+    // there to bind the end of the negated pattern portion, and it's easier to
+    // just stick it in now rather than try to inject it later in the middle of
+    // the pattern.
+    //
+    // We can just always return the same end, and leave it up to the caller
+    // to know whether it's going to be used joined or in parts.
+    // And, if the start is adjusted slightly, can do the same there:
+    // - if not isStart: nothing
+    // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
+    // - if dots allowed or not possible: (?:/|^)
+    // - if dots possible and not allowed: (?:/|^)(?!\.)
+    //
+    // But it's better to have a simpler binding without a conditional, for
+    // performance, so probably better to return both start options.
+    //
+    // Then the caller just ignores the end if it's not the first pattern,
+    // and the start always gets applied.
+    //
+    // But that's always going to be $ if it's the ending pattern, or nothing,
+    // so the caller can just attach $ at the end of the pattern when building.
+    //
+    // So the todo is:
+    // - better detect what kind of start is needed
+    // - return both flavors of starting pattern
+    // - attach $ at the end of the pattern when creating the actual RegExp
+    //
+    // Ah, but wait, no, that all only applies to the root when the first pattern
+    // is not an extglob. If the first pattern IS an extglob, then we need all
+    // that dot prevention biz to live in the extglob portions, because eg
+    // +(*|.x*) can match .xy but not .yx.
+    //
+    // So, return the two flavors if it's #root and the first child is not an
+    // AST, otherwise leave it to the child AST to handle it, and there,
+    // use the (?:^|/) style of start binding.
+    //
+    // Even simplified further:
+    // - Since the start for a join is eg /(?!\.) and the start for a part
+    // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
+    // or start or whatever) and prepend ^ or / at the Regexp construction.
+    toRegExpSource(allowDot) {
+        const dot = allowDot ?? !!this.#options.dot;
+        if (this.#root === this)
+            this.#fillNegs();
+        if (!this.type) {
+            const noEmpty = this.isStart() && this.isEnd();
+            const src = this.#parts
+                .map(p => {
+                const [re, _, hasMagic, uflag] = typeof p === 'string'
+                    ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
+                    : p.toRegExpSource(allowDot);
+                this.#hasMagic = this.#hasMagic || hasMagic;
+                this.#uflag = this.#uflag || uflag;
+                return re;
+            })
+                .join('');
+            let start = '';
+            if (this.isStart()) {
+                if (typeof this.#parts[0] === 'string') {
+                    // this is the string that will match the start of the pattern,
+                    // so we need to protect against dots and such.
+                    // '.' and '..' cannot match unless the pattern is that exactly,
+                    // even if it starts with . or dot:true is set.
+                    const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
+                    if (!dotTravAllowed) {
+                        const aps = addPatternStart;
+                        // check if we have a possibility of matching . or ..,
+                        // and prevent that.
+                        const needNoTrav = 
+                        // dots are allowed, and the pattern starts with [ or .
+                        (dot && aps.has(src.charAt(0))) ||
+                            // the pattern starts with \., and then [ or .
+                            (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
+                            // the pattern starts with \.\., and then [ or .
+                            (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
+                        // no need to prevent dots if it can't match a dot, or if a
+                        // sub-pattern will be preventing it anyway.
+                        const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
+                        start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
                     }
                 }
-                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) => {
-            sizes[index] = size;
-            if (this.#maxSize) {
-                const maxSize = this.#maxSize - sizes[index];
-                while (this.#calculatedSize > maxSize) {
-                    this.#evict(true);
-                }
+            // append the "end of path portion" pattern to negation tails
+            let end = '';
+            if (this.isEnd() &&
+                this.#root.#filledNegs &&
+                this.#parent?.type === '!') {
+                end = '(?:$|\\/)';
             }
-            this.#calculatedSize += sizes[index];
-            if (status) {
-                status.entrySize = size;
-                status.totalCalculatedSize = this.#calculatedSize;
+            const final = start + src + end;
+            return [
+                final,
+                (0, unescape_js_1.unescape)(src),
+                (this.#hasMagic = !!this.#hasMagic),
+                this.#uflag,
+            ];
+        }
+        // We need to calculate the body *twice* if it's a repeat pattern
+        // at the start, once in nodot mode, then again in dot mode, so a
+        // pattern like *(?) can match 'x.y'
+        const repeated = this.type === '*' || this.type === '+';
+        // some kind of extglob
+        const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
+        let body = this.#partsToRegExp(dot);
+        if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
+            // invalid extglob, has to at least be *something* present, if it's
+            // the entire path portion.
+            const s = this.toString();
+            this.#parts = [s];
+            this.type = null;
+            this.#hasMagic = undefined;
+            return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
+        }
+        // XXX abstract out this map method
+        let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
+            ? ''
+            : this.#partsToRegExp(true);
+        if (bodyDotAllowed === body) {
+            bodyDotAllowed = '';
+        }
+        if (bodyDotAllowed) {
+            body = `(?:${body})(?:${bodyDotAllowed})*?`;
+        }
+        // an empty !() is exactly equivalent to a starNoEmpty
+        let final = '';
+        if (this.type === '!' && this.#emptyExt) {
+            final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
+        }
+        else {
+            const close = this.type === '!'
+                ? // !() must match something,but !(x) can match ''
+                    '))' +
+                        (this.isStart() && !dot && !allowDot ? startNoDot : '') +
+                        star +
+                        ')'
+                : this.type === '@'
+                    ? ')'
+                    : this.type === '?'
+                        ? ')?'
+                        : this.type === '+' && bodyDotAllowed
+                            ? ')'
+                            : this.type === '*' && bodyDotAllowed
+                                ? `)?`
+                                : `)${this.type}`;
+            final = start + body + close;
+        }
+        return [
+            final,
+            (0, unescape_js_1.unescape)(body),
+            (this.#hasMagic = !!this.#hasMagic),
+            this.#uflag,
+        ];
+    }
+    #partsToRegExp(dot) {
+        return this.#parts
+            .map(p => {
+            // extglob ASTs should only contain parent ASTs
+            /* c8 ignore start */
+            if (typeof p === 'string') {
+                throw new Error('string type in extglob ast??');
             }
-        };
+            /* c8 ignore stop */
+            // can ignore hasMagic, because extglobs are already always magic
+            const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
+            this.#uflag = this.#uflag || uflag;
+            return re;
+        })
+            .filter(p => !(this.isStart() && this.isEnd()) || !!p)
+            .join('|');
     }
-    #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; true;) {
-                if (!this.#isValidIndex(i)) {
-                    break;
-                }
-                if (allowStale || !this.#isStale(i)) {
-                    yield i;
-                }
-                if (i === this.#head) {
-                    break;
+    static #parseGlob(glob, hasMagic, noEmpty = false) {
+        let escaping = false;
+        let re = '';
+        let uflag = false;
+        for (let i = 0; i < glob.length; i++) {
+            const c = glob.charAt(i);
+            if (escaping) {
+                escaping = false;
+                re += (reSpecials.has(c) ? '\\' : '') + c;
+                continue;
+            }
+            if (c === '\\') {
+                if (i === glob.length - 1) {
+                    re += '\\\\';
                 }
                 else {
-                    i = this.#prev[i];
+                    escaping = true;
                 }
+                continue;
             }
-        }
-    }
-    *#rindexes({ allowStale = this.allowStale } = {}) {
-        if (this.#size) {
-            for (let i = this.#head; true;) {
-                if (!this.#isValidIndex(i)) {
-                    break;
-                }
-                if (allowStale || !this.#isStale(i)) {
-                    yield i;
-                }
-                if (i === this.#tail) {
-                    break;
-                }
-                else {
-                    i = this.#next[i];
+            if (c === '[') {
+                const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
+                if (consumed) {
+                    re += src;
+                    uflag = uflag || needUflag;
+                    i += consumed - 1;
+                    hasMagic = hasMagic || magic;
+                    continue;
                 }
             }
+            if (c === '*') {
+                if (noEmpty && glob === '*')
+                    re += starNoEmpty;
+                else
+                    re += star;
+                hasMagic = true;
+                continue;
+            }
+            if (c === '?') {
+                re += qmark;
+                hasMagic = true;
+                continue;
+            }
+            re += regExpEscape(c);
         }
+        return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
     }
-    #isValidIndex(index) {
-        return (index !== undefined &&
-            this.#keyMap.get(this.#keyList[index]) === index);
+}
+exports.AST = AST;
+//# sourceMappingURL=ast.js.map
+
+/***/ }),
+
+/***/ 10038:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+// translate the various posix character classes into unicode properties
+// this works across all unicode locales
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseClass = void 0;
+// { : [, /u flag required, negated]
+const posixClasses = {
+    '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
+    '[:alpha:]': ['\\p{L}\\p{Nl}', true],
+    '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
+    '[:blank:]': ['\\p{Zs}\\t', true],
+    '[:cntrl:]': ['\\p{Cc}', true],
+    '[:digit:]': ['\\p{Nd}', true],
+    '[:graph:]': ['\\p{Z}\\p{C}', true, true],
+    '[:lower:]': ['\\p{Ll}', true],
+    '[:print:]': ['\\p{C}', true],
+    '[:punct:]': ['\\p{P}', true],
+    '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
+    '[:upper:]': ['\\p{Lu}', true],
+    '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
+    '[:xdigit:]': ['A-Fa-f0-9', false],
+};
+// only need to escape a few things inside of brace expressions
+// escapes: [ \ ] -
+const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
+// escape all regexp magic characters
+const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+// everything has already been escaped, we just have to join
+const rangesToString = (ranges) => ranges.join('');
+// takes a glob string at a posix brace expression, and returns
+// an equivalent regular expression source, and boolean indicating
+// whether the /u flag needs to be applied, and the number of chars
+// consumed to parse the character class.
+// This also removes out of order ranges, and returns ($.) if the
+// entire class just no good.
+const parseClass = (glob, position) => {
+    const pos = position;
+    /* c8 ignore start */
+    if (glob.charAt(pos) !== '[') {
+        throw new Error('not in a brace expression');
     }
-    /**
-     * Return a generator yielding `[key, value]` pairs,
-     * in order from most recently used to least recently used.
-     */
-    *entries() {
-        for (const i of this.#indexes()) {
-            if (this.#valList[i] !== undefined &&
-                this.#keyList[i] !== undefined &&
-                !this.#isBackgroundFetch(this.#valList[i])) {
-                yield [this.#keyList[i], this.#valList[i]];
-            }
+    /* c8 ignore stop */
+    const ranges = [];
+    const negs = [];
+    let i = pos + 1;
+    let sawStart = false;
+    let uflag = false;
+    let escaping = false;
+    let negate = false;
+    let endPos = pos;
+    let rangeStart = '';
+    WHILE: while (i < glob.length) {
+        const c = glob.charAt(i);
+        if ((c === '!' || c === '^') && i === pos + 1) {
+            negate = true;
+            i++;
+            continue;
         }
-    }
-    /**
-     * 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 (const i of this.#rindexes()) {
-            if (this.#valList[i] !== undefined &&
-                this.#keyList[i] !== undefined &&
-                !this.#isBackgroundFetch(this.#valList[i])) {
-                yield [this.#keyList[i], this.#valList[i]];
-            }
+        if (c === ']' && sawStart && !escaping) {
+            endPos = i + 1;
+            break;
         }
-    }
-    /**
-     * Return a generator yielding the keys in the cache,
-     * in order from most recently used to least recently used.
-     */
-    *keys() {
-        for (const i of this.#indexes()) {
-            const k = this.#keyList[i];
-            if (k !== undefined &&
-                !this.#isBackgroundFetch(this.#valList[i])) {
-                yield k;
+        sawStart = true;
+        if (c === '\\') {
+            if (!escaping) {
+                escaping = true;
+                i++;
+                continue;
             }
+            // escaped \ char, fall through and treat like normal char
         }
-    }
-    /**
-     * 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 (const i of this.#rindexes()) {
-            const k = this.#keyList[i];
-            if (k !== undefined &&
-                !this.#isBackgroundFetch(this.#valList[i])) {
-                yield k;
+        if (c === '[' && !escaping) {
+            // either a posix class, a collation equivalent, or just a [
+            for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
+                if (glob.startsWith(cls, i)) {
+                    // invalid, [a-[] is fine, but not [a-[:alpha]]
+                    if (rangeStart) {
+                        return ['$.', false, glob.length - pos, true];
+                    }
+                    i += cls.length;
+                    if (neg)
+                        negs.push(unip);
+                    else
+                        ranges.push(unip);
+                    uflag = uflag || u;
+                    continue WHILE;
+                }
             }
         }
-    }
-    /**
-     * Return a generator yielding the values in the cache,
-     * in order from most recently used to least recently used.
-     */
-    *values() {
-        for (const i of this.#indexes()) {
-            const v = this.#valList[i];
-            if (v !== undefined &&
-                !this.#isBackgroundFetch(this.#valList[i])) {
-                yield this.#valList[i];
+        // now it's just a normal character, effectively
+        escaping = false;
+        if (rangeStart) {
+            // throw this range away if it's not valid, but others
+            // can still match.
+            if (c > rangeStart) {
+                ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
+            }
+            else if (c === rangeStart) {
+                ranges.push(braceEscape(c));
             }
+            rangeStart = '';
+            i++;
+            continue;
+        }
+        // now might be the start of a range.
+        // can be either c-d or c-] or c] or c] at this point
+        if (glob.startsWith('-]', i + 1)) {
+            ranges.push(braceEscape(c + '-'));
+            i += 2;
+            continue;
         }
+        if (glob.startsWith('-', i + 1)) {
+            rangeStart = c;
+            i += 2;
+            continue;
+        }
+        // not the start of a range, just a single character
+        ranges.push(braceEscape(c));
+        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 (const i of this.#rindexes()) {
-            const v = this.#valList[i];
-            if (v !== undefined &&
-                !this.#isBackgroundFetch(this.#valList[i])) {
-                yield this.#valList[i];
+    if (endPos < i) {
+        // didn't see the end of the class, not a valid class,
+        // but might still be valid as a literal match.
+        return ['', false, 0, false];
+    }
+    // if we got no ranges and no negates, then we have a range that
+    // cannot possibly match anything, and that poisons the whole glob
+    if (!ranges.length && !negs.length) {
+        return ['$.', false, glob.length - pos, true];
+    }
+    // if we got one positive range, and it's a single character, then that's
+    // not actually a magic pattern, it's just that one literal character.
+    // we should not treat that as "magic", we should just return the literal
+    // character. [_] is a perfectly valid way to escape glob magic chars.
+    if (negs.length === 0 &&
+        ranges.length === 1 &&
+        /^\\?.$/.test(ranges[0]) &&
+        !negate) {
+        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
+        return [regexpEscape(r), false, endPos - pos, false];
+    }
+    const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
+    const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
+    const comb = ranges.length && negs.length
+        ? '(' + sranges + '|' + snegs + ')'
+        : ranges.length
+            ? sranges
+            : snegs;
+    return [comb, uflag, endPos - pos, true];
+};
+exports.parseClass = parseClass;
+//# sourceMappingURL=brace-expressions.js.map
+
+/***/ }),
+
+/***/ 96076:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.escape = void 0;
+/**
+ * Escape all magic characters in a glob pattern.
+ *
+ * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
+ * option is used, then characters are escaped by wrapping in `[]`, because
+ * a magic character wrapped in a character class can only be satisfied by
+ * that exact character.  In this mode, `\` is _not_ escaped, because it is
+ * not interpreted as a magic character, but instead as a path separator.
+ */
+const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    // don't need to escape +@! because we escape the parens
+    // that make those magic, and escaping ! as [!] isn't valid,
+    // because [!]] is a valid glob class meaning not ']'.
+    return windowsPathsNoEscape
+        ? s.replace(/[?*()[\]]/g, '[$&]')
+        : s.replace(/[?*()[\]\\]/g, '\\$&');
+};
+exports.escape = escape;
+//# sourceMappingURL=escape.js.map
+
+/***/ }),
+
+/***/ 85207:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+"use strict";
+
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.unescape = exports.escape = exports.AST = exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0;
+const brace_expansion_1 = __importDefault(__nccwpck_require__(45177));
+const assert_valid_pattern_js_1 = __nccwpck_require__(30013);
+const ast_js_1 = __nccwpck_require__(6215);
+const escape_js_1 = __nccwpck_require__(96076);
+const unescape_js_1 = __nccwpck_require__(18047);
+const minimatch = (p, pattern, options = {}) => {
+    (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+    // shortcut: comments match nothing.
+    if (!options.nocomment && pattern.charAt(0) === '#') {
+        return false;
+    }
+    return new Minimatch(pattern, options).match(p);
+};
+exports.minimatch = minimatch;
+// Optimized checking for the most common glob patterns.
+const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
+const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
+const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
+const starDotExtTestNocase = (ext) => {
+    ext = ext.toLowerCase();
+    return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
+};
+const starDotExtTestNocaseDot = (ext) => {
+    ext = ext.toLowerCase();
+    return (f) => f.toLowerCase().endsWith(ext);
+};
+const starDotStarRE = /^\*+\.\*+$/;
+const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
+const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
+const dotStarRE = /^\.\*+$/;
+const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
+const starRE = /^\*+$/;
+const starTest = (f) => f.length !== 0 && !f.startsWith('.');
+const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
+const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
+const qmarksTestNocase = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExt([$0]);
+    if (!ext)
+        return noext;
+    ext = ext.toLowerCase();
+    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestNocaseDot = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExtDot([$0]);
+    if (!ext)
+        return noext;
+    ext = ext.toLowerCase();
+    return (f) => noext(f) && f.toLowerCase().endsWith(ext);
+};
+const qmarksTestDot = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExtDot([$0]);
+    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTest = ([$0, ext = '']) => {
+    const noext = qmarksTestNoExt([$0]);
+    return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
+};
+const qmarksTestNoExt = ([$0]) => {
+    const len = $0.length;
+    return (f) => f.length === len && !f.startsWith('.');
+};
+const qmarksTestNoExtDot = ([$0]) => {
+    const len = $0.length;
+    return (f) => f.length === len && f !== '.' && f !== '..';
+};
+/* c8 ignore start */
+const defaultPlatform = (typeof process === 'object' && process
+    ? (typeof process.env === 'object' &&
+        process.env &&
+        process.env.__MINIMATCH_TESTING_PLATFORM__) ||
+        process.platform
+    : 'posix');
+const path = {
+    win32: { sep: '\\' },
+    posix: { sep: '/' },
+};
+/* c8 ignore stop */
+exports.sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
+exports.minimatch.sep = exports.sep;
+exports.GLOBSTAR = Symbol('globstar **');
+exports.minimatch.GLOBSTAR = exports.GLOBSTAR;
+// any single thing other than /
+// don't need to escape / when using new RegExp()
+const qmark = '[^/]';
+// * => any number of characters
+const star = qmark + '*?';
+// ** when dots are allowed.  Anything goes, except .. and .
+// not (^ or / followed by one or two dots followed by $ or /),
+// followed by anything, any number of times.
+const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
+// not a ^ or / followed by a dot,
+// followed by anything, any number of times.
+const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
+const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options);
+exports.filter = filter;
+exports.minimatch.filter = exports.filter;
+const ext = (a, b = {}) => Object.assign({}, a, b);
+const defaults = (def) => {
+    if (!def || typeof def !== 'object' || !Object.keys(def).length) {
+        return exports.minimatch;
+    }
+    const orig = exports.minimatch;
+    const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
+    return Object.assign(m, {
+        Minimatch: class Minimatch extends orig.Minimatch {
+            constructor(pattern, options = {}) {
+                super(pattern, ext(def, options));
+            }
+            static defaults(options) {
+                return orig.defaults(ext(def, options)).Minimatch;
+            }
+        },
+        AST: class AST extends orig.AST {
+            /* c8 ignore start */
+            constructor(type, parent, options = {}) {
+                super(type, parent, ext(def, options));
+            }
+            /* c8 ignore stop */
+            static fromGlob(pattern, options = {}) {
+                return orig.AST.fromGlob(pattern, ext(def, options));
             }
+        },
+        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
+        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
+        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
+        defaults: (options) => orig.defaults(ext(def, options)),
+        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
+        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
+        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
+        sep: orig.sep,
+        GLOBSTAR: exports.GLOBSTAR,
+    });
+};
+exports.defaults = defaults;
+exports.minimatch.defaults = exports.defaults;
+// Brace expansion:
+// a{b,c}d -> abd acd
+// a{b,}c -> abc ac
+// a{0..3}d -> a0d a1d a2d a3d
+// a{b,c{d,e}f}g -> abg acdfg acefg
+// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
+//
+// Invalid sets are not expanded.
+// a{2..}b -> a{2..}b
+// a{b}c -> a{b}c
+const braceExpand = (pattern, options = {}) => {
+    (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+    // Thanks to Yeting Li  for
+    // improving this regexp to avoid a ReDOS vulnerability.
+    if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+        // shortcut. no need to expand.
+        return [pattern];
+    }
+    return (0, brace_expansion_1.default)(pattern);
+};
+exports.braceExpand = braceExpand;
+exports.minimatch.braceExpand = exports.braceExpand;
+// parse a component of the expanded set.
+// At this point, no pattern may contain "/" in it
+// so we're going to return a 2d array, where each entry is the full
+// pattern, split on '/', and then turned into a regular expression.
+// A regexp is made at the end which joins each array with an
+// escaped /, and another full one which joins each regexp with |.
+//
+// Following the lead of Bash 4.1, note that "**" only has special meaning
+// when it is the *only* thing in a path portion.  Otherwise, any series
+// of * is equivalent to a single *.  Globstar behavior is enabled by
+// default, and can be disabled by setting options.noglobstar.
+const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
+exports.makeRe = makeRe;
+exports.minimatch.makeRe = exports.makeRe;
+const match = (list, pattern, options = {}) => {
+    const mm = new Minimatch(pattern, options);
+    list = list.filter(f => mm.match(f));
+    if (mm.options.nonull && !list.length) {
+        list.push(pattern);
+    }
+    return list;
+};
+exports.match = match;
+exports.minimatch.match = exports.match;
+// replace stuff like \* with *
+const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
+const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
+class Minimatch {
+    options;
+    set;
+    pattern;
+    windowsPathsNoEscape;
+    nonegate;
+    negate;
+    comment;
+    empty;
+    preserveMultipleSlashes;
+    partial;
+    globSet;
+    globParts;
+    nocase;
+    isWindows;
+    platform;
+    windowsNoMagicRoot;
+    regexp;
+    constructor(pattern, options = {}) {
+        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+        options = options || {};
+        this.options = options;
+        this.pattern = pattern;
+        this.platform = options.platform || defaultPlatform;
+        this.isWindows = this.platform === 'win32';
+        this.windowsPathsNoEscape =
+            !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
+        if (this.windowsPathsNoEscape) {
+            this.pattern = this.pattern.replace(/\\/g, '/');
         }
+        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
+        this.regexp = null;
+        this.negate = false;
+        this.nonegate = !!options.nonegate;
+        this.comment = false;
+        this.empty = false;
+        this.partial = !!options.partial;
+        this.nocase = !!this.options.nocase;
+        this.windowsNoMagicRoot =
+            options.windowsNoMagicRoot !== undefined
+                ? options.windowsNoMagicRoot
+                : !!(this.isWindows && this.nocase);
+        this.globSet = [];
+        this.globParts = [];
+        this.set = [];
+        // make the set of regexps etc.
+        this.make();
     }
-    /**
-     * Iterating over the cache itself yields the same results as
-     * {@link LRUCache.entries}
-     */
-    [Symbol.iterator]() {
-        return this.entries();
-    }
-    /**
-     * A String value that is used in the creation of the default string
-     * description of an object. Called by the built-in method
-     * `Object.prototype.toString`.
-     */
-    [Symbol.toStringTag] = 'LRUCache';
-    /**
-     * 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 (const i of this.#indexes()) {
-            const v = this.#valList[i];
-            const value = this.#isBackgroundFetch(v)
-                ? v.__staleWhileFetching
-                : v;
-            if (value === undefined)
-                continue;
-            if (fn(value, this.#keyList[i], this)) {
-                return this.get(this.#keyList[i], getOptions);
+    hasMagic() {
+        if (this.options.magicalBraces && this.set.length > 1) {
+            return true;
+        }
+        for (const pattern of this.set) {
+            for (const part of pattern) {
+                if (typeof part !== 'string')
+                    return true;
             }
         }
+        return false;
     }
-    /**
-     * 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)`.
-     *
-     * If `thisp` is provided, function will be called in the `this`-context of
-     * the provided object, or the cache if no `thisp` object is provided.
-     *
-     * Does not update age or recenty of use, or iterate over stale values.
-     */
-    forEach(fn, thisp = this) {
-        for (const i of this.#indexes()) {
-            const v = this.#valList[i];
-            const value = this.#isBackgroundFetch(v)
-                ? v.__staleWhileFetching
-                : v;
-            if (value === undefined)
-                continue;
-            fn.call(thisp, value, this.#keyList[i], this);
+    debug(..._) { }
+    make() {
+        const pattern = this.pattern;
+        const options = this.options;
+        // empty patterns and comments match nothing.
+        if (!options.nocomment && pattern.charAt(0) === '#') {
+            this.comment = true;
+            return;
         }
-    }
-    /**
-     * 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 (const i of this.#rindexes()) {
-            const v = this.#valList[i];
-            const value = this.#isBackgroundFetch(v)
-                ? v.__staleWhileFetching
-                : v;
-            if (value === undefined)
-                continue;
-            fn.call(thisp, value, this.#keyList[i], this);
+        if (!pattern) {
+            this.empty = true;
+            return;
         }
-    }
-    /**
-     * Delete any stale entries. Returns true if anything was removed,
-     * false otherwise.
-     */
-    purgeStale() {
-        let deleted = false;
-        for (const i of this.#rindexes({ allowStale: true })) {
-            if (this.#isStale(i)) {
-                this.#delete(this.#keyList[i], 'expire');
-                deleted = true;
+        // step 1: figure out negation, etc.
+        this.parseNegate();
+        // step 2: expand braces
+        this.globSet = [...new Set(this.braceExpand())];
+        if (options.debug) {
+            this.debug = (...args) => console.error(...args);
+        }
+        this.debug(this.pattern, this.globSet);
+        // step 3: now we have a set, so turn each one into a series of
+        // path-portion matching patterns.
+        // These will be regexps, except in the case of "**", which is
+        // set to the GLOBSTAR object for globstar behavior,
+        // and will not contain any / characters
+        //
+        // First, we preprocess to make the glob pattern sets a bit simpler
+        // and deduped.  There are some perf-killing patterns that can cause
+        // problems with a glob walk, but we can simplify them down a bit.
+        const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
+        this.globParts = this.preprocess(rawGlobParts);
+        this.debug(this.pattern, this.globParts);
+        // glob --> regexps
+        let set = this.globParts.map((s, _, __) => {
+            if (this.isWindows && this.windowsNoMagicRoot) {
+                // check if it's a drive or unc path.
+                const isUNC = s[0] === '' &&
+                    s[1] === '' &&
+                    (s[2] === '?' || !globMagic.test(s[2])) &&
+                    !globMagic.test(s[3]);
+                const isDrive = /^[a-z]:/i.test(s[0]);
+                if (isUNC) {
+                    return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
+                }
+                else if (isDrive) {
+                    return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
+                }
+            }
+            return s.map(ss => this.parse(ss));
+        });
+        this.debug(this.pattern, set);
+        // filter out everything that didn't compile properly.
+        this.set = set.filter(s => s.indexOf(false) === -1);
+        // do not treat the ? in UNC paths as magic
+        if (this.isWindows) {
+            for (let i = 0; i < this.set.length; i++) {
+                const p = this.set[i];
+                if (p[0] === '' &&
+                    p[1] === '' &&
+                    this.globParts[i][2] === '?' &&
+                    typeof p[3] === 'string' &&
+                    /^[a-z]:$/i.test(p[3])) {
+                    p[2] = '?';
+                }
             }
         }
-        return deleted;
+        this.debug(this.pattern, this.set);
     }
-    /**
-     * Get the extended info about a given entry, to get its value, size, and
-     * TTL info simultaneously. Returns `undefined` if the key is not present.
-     *
-     * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
-     * serialization, the `start` value is always the current timestamp, and the
-     * `ttl` is a calculated remaining time to live (negative if expired).
-     *
-     * Always returns stale values, if their info is found in the cache, so be
-     * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
-     * if relevant.
-     */
-    info(key) {
-        const i = this.#keyMap.get(key);
-        if (i === undefined)
-            return undefined;
-        const v = this.#valList[i];
-        const value = this.#isBackgroundFetch(v)
-            ? v.__staleWhileFetching
-            : v;
-        if (value === undefined)
-            return undefined;
-        const entry = { value };
-        if (this.#ttls && this.#starts) {
-            const ttl = this.#ttls[i];
-            const start = this.#starts[i];
-            if (ttl && start) {
-                const remain = ttl - (perf.now() - start);
-                entry.ttl = remain;
-                entry.start = Date.now();
+    // various transforms to equivalent pattern sets that are
+    // faster to process in a filesystem walk.  The goal is to
+    // eliminate what we can, and push all ** patterns as far
+    // to the right as possible, even if it increases the number
+    // of patterns that we have to process.
+    preprocess(globParts) {
+        // if we're not in globstar mode, then turn all ** into *
+        if (this.options.noglobstar) {
+            for (let i = 0; i < globParts.length; i++) {
+                for (let j = 0; j < globParts[i].length; j++) {
+                    if (globParts[i][j] === '**') {
+                        globParts[i][j] = '*';
+                    }
+                }
             }
         }
-        if (this.#sizes) {
-            entry.size = this.#sizes[i];
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            // aggressive optimization for the purpose of fs walking
+            globParts = this.firstPhasePreProcess(globParts);
+            globParts = this.secondPhasePreProcess(globParts);
         }
-        return entry;
-    }
-    /**
-     * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
-     * passed to {@link LRLUCache#load}.
-     *
-     * The `start` fields are calculated relative to a portable `Date.now()`
-     * timestamp, even if `performance.now()` is available.
-     *
-     * Stale entries are always included in the `dump`, even if
-     * {@link LRUCache.OptionsBase.allowStale} is false.
-     *
-     * Note: this returns an actual array, not a generator, so it can be more
-     * easily passed around.
-     */
-    dump() {
-        const arr = [];
-        for (const i of this.#indexes({ allowStale: true })) {
-            const key = this.#keyList[i];
-            const v = this.#valList[i];
-            const value = this.#isBackgroundFetch(v)
-                ? v.__staleWhileFetching
-                : v;
-            if (value === undefined || key === undefined)
-                continue;
-            const entry = { value };
-            if (this.#ttls && this.#starts) {
-                entry.ttl = this.#ttls[i];
-                // always dump the start relative to a portable timestamp
-                // it's ok for this to be a bit slow, it's a rare operation.
-                const age = perf.now() - this.#starts[i];
-                entry.start = Math.floor(Date.now() - age);
-            }
-            if (this.#sizes) {
-                entry.size = this.#sizes[i];
-            }
-            arr.unshift([key, entry]);
+        else if (optimizationLevel >= 1) {
+            // just basic optimizations to remove some .. parts
+            globParts = this.levelOneOptimize(globParts);
         }
-        return arr;
+        else {
+            // just collapse multiple ** portions into one
+            globParts = this.adjascentGlobstarOptimize(globParts);
+        }
+        return globParts;
     }
-    /**
-     * Reset the cache and load in the items in entries in the order listed.
-     *
-     * The shape of the resulting cache may be different if the same options are
-     * not used in both caches.
-     *
-     * The `start` fields are assumed to be calculated relative to a portable
-     * `Date.now()` timestamp, even if `performance.now()` is available.
-     */
-    load(arr) {
-        this.clear();
-        for (const [key, entry] of arr) {
-            if (entry.start) {
-                // entry.start is a portable timestamp, but we may be using
-                // node's performance.now(), so calculate the offset, so that
-                // we get the intended remaining TTL, no matter how long it's
-                // been on ice.
-                //
-                // it's ok for this to be a bit slow, it's a rare operation.
-                const age = Date.now() - entry.start;
-                entry.start = perf.now() - age;
+    // just get rid of adjascent ** portions
+    adjascentGlobstarOptimize(globParts) {
+        return globParts.map(parts => {
+            let gs = -1;
+            while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
+                let i = gs;
+                while (parts[i + 1] === '**') {
+                    i++;
+                }
+                if (i !== gs) {
+                    parts.splice(gs, i - gs);
+                }
             }
-            this.set(key, entry.value, entry);
-        }
+            return parts;
+        });
     }
-    /**
-     * Add a value to the cache.
-     *
-     * Note: if `undefined` is specified as a value, this is an alias for
-     * {@link LRUCache#delete}
-     *
-     * Fields on the {@link LRUCache.SetOptions} options param will override
-     * their corresponding values in the constructor options for the scope
-     * of this single `set()` operation.
-     *
-     * If `start` is provided, then that will set the effective start
-     * time for the TTL calculation. Note that this must be a previous
-     * value of `performance.now()` if supported, or a previous value of
-     * `Date.now()` if not.
-     *
-     * Options object may also include `size`, which will prevent
-     * calling the `sizeCalculation` function and just use the specified
-     * number if it is a positive integer, and `noDisposeOnSet` which
-     * will prevent calling a `dispose` function in the case of
-     * overwrites.
-     *
-     * If the `size` (or return value of `sizeCalculation`) for a given
-     * entry is greater than `maxEntrySize`, then the item will not be
-     * added to the cache.
-     *
-     * Will update the recency of the entry.
-     *
-     * If the value is `undefined`, then this is an alias for
-     * `cache.delete(key)`. `undefined` is never stored in the cache.
-     */
-    set(k, v, setOptions = {}) {
-        if (v === undefined) {
-            this.delete(k);
-            return this;
+    // get rid of adjascent ** and resolve .. portions
+    levelOneOptimize(globParts) {
+        return globParts.map(parts => {
+            parts = parts.reduce((set, part) => {
+                const prev = set[set.length - 1];
+                if (part === '**' && prev === '**') {
+                    return set;
+                }
+                if (part === '..') {
+                    if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
+                        set.pop();
+                        return set;
+                    }
+                }
+                set.push(part);
+                return set;
+            }, []);
+            return parts.length === 0 ? [''] : parts;
+        });
+    }
+    levelTwoFileOptimize(parts) {
+        if (!Array.isArray(parts)) {
+            parts = this.slashSplit(parts);
         }
-        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
-        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
-        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
-        // if the item doesn't fit, don't do anything
-        // NB: maxEntrySize set to maxSize by default
-        if (this.maxEntrySize && size > this.maxEntrySize) {
-            if (status) {
-                status.set = 'miss';
-                status.maxEntrySizeExceeded = true;
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
// -> 
/
+            if (!this.preserveMultipleSlashes) {
+                for (let i = 1; i < parts.length - 1; i++) {
+                    const p = parts[i];
+                    // don't squeeze out UNC patterns
+                    if (i === 1 && p === '' && parts[0] === '')
+                        continue;
+                    if (p === '.' || p === '') {
+                        didSomething = true;
+                        parts.splice(i, 1);
+                        i--;
+                    }
+                }
+                if (parts[0] === '.' &&
+                    parts.length === 2 &&
+                    (parts[1] === '.' || parts[1] === '')) {
+                    didSomething = true;
+                    parts.pop();
+                }
             }
-            // have to delete, in case something is there already.
-            this.#delete(k, 'set');
-            return this;
-        }
-        let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
-        if (index === undefined) {
-            // addition
-            index = (this.#size === 0
-                ? this.#tail
-                : this.#free.length !== 0
-                    ? this.#free.pop()
-                    : this.#size === this.#max
-                        ? this.#evict(false)
-                        : 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);
-            if (status)
-                status.set = 'add';
-            noUpdateTTL = false;
-        }
-        else {
-            // update
-            this.#moveToTail(index);
-            const oldVal = this.#valList[index];
-            if (v !== oldVal) {
-                if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
-                    oldVal.__abortController.abort(new Error('replaced'));
-                    const { __staleWhileFetching: s } = oldVal;
-                    if (s !== undefined && !noDisposeOnSet) {
-                        if (this.#hasDispose) {
-                            this.#dispose?.(s, k, 'set');
-                        }
-                        if (this.#hasDisposeAfter) {
-                            this.#disposed?.push([s, k, 'set']);
-                        }
+            // 
/

/../ ->

/
+            let dd = 0;
+            while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                const p = parts[dd - 1];
+                if (p && p !== '.' && p !== '..' && p !== '**') {
+                    didSomething = true;
+                    parts.splice(dd - 1, 2);
+                    dd -= 2;
+                }
+            }
+        } while (didSomething);
+        return parts.length === 0 ? [''] : parts;
+    }
+    // First phase: single-pattern processing
+    // 
 is 1 or more portions
+    //  is 1 or more portions
+    // 

is any portion other than ., .., '', or ** + // is . or '' + // + // **/.. is *brutal* for filesystem walking performance, because + // it effectively resets the recursive walk each time it occurs, + // and ** cannot be reduced out by a .. pattern part like a regexp + // or most strings (other than .., ., and '') can be. + // + //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + //

// -> 
/
+    // 
/

/../ ->

/
+    // **/**/ -> **/
+    //
+    // **/*/ -> */**/ <== not valid because ** doesn't follow
+    // this WOULD be allowed if ** did follow symlinks, or * didn't
+    firstPhasePreProcess(globParts) {
+        let didSomething = false;
+        do {
+            didSomething = false;
+            // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/} + for (let parts of globParts) { + let gs = -1; + while (-1 !== (gs = parts.indexOf('**', gs + 1))) { + let gss = gs; + while (parts[gss + 1] === '**') { + //

/**/**/ -> 
/**/
+                        gss++;
+                    }
+                    // eg, if gs is 2 and gss is 4, that means we have 3 **
+                    // parts, and can remove 2 of them.
+                    if (gss > gs) {
+                        parts.splice(gs + 1, gss - gs);
+                    }
+                    let next = parts[gs + 1];
+                    const p = parts[gs + 2];
+                    const p2 = parts[gs + 3];
+                    if (next !== '..')
+                        continue;
+                    if (!p ||
+                        p === '.' ||
+                        p === '..' ||
+                        !p2 ||
+                        p2 === '.' ||
+                        p2 === '..') {
+                        continue;
                     }
+                    didSomething = true;
+                    // edit parts in place, and push the new one
+                    parts.splice(gs, 1);
+                    const other = parts.slice(0);
+                    other[gs] = '**';
+                    globParts.push(other);
+                    gs--;
                 }
-                else if (!noDisposeOnSet) {
-                    if (this.#hasDispose) {
-                        this.#dispose?.(oldVal, k, 'set');
+                // 
// -> 
/
+                if (!this.preserveMultipleSlashes) {
+                    for (let i = 1; i < parts.length - 1; i++) {
+                        const p = parts[i];
+                        // don't squeeze out UNC patterns
+                        if (i === 1 && p === '' && parts[0] === '')
+                            continue;
+                        if (p === '.' || p === '') {
+                            didSomething = true;
+                            parts.splice(i, 1);
+                            i--;
+                        }
                     }
-                    if (this.#hasDisposeAfter) {
-                        this.#disposed?.push([oldVal, k, 'set']);
+                    if (parts[0] === '.' &&
+                        parts.length === 2 &&
+                        (parts[1] === '.' || parts[1] === '')) {
+                        didSomething = true;
+                        parts.pop();
                     }
                 }
-                this.#removeItemSize(index);
-                this.#addItemSize(index, size, status);
-                this.#valList[index] = v;
-                if (status) {
-                    status.set = 'replace';
-                    const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
-                        ? oldVal.__staleWhileFetching
-                        : oldVal;
-                    if (oldValue !== undefined)
-                        status.oldValue = oldValue;
-                }
-            }
-            else if (status) {
-                status.set = 'update';
-            }
-        }
-        if (ttl !== 0 && !this.#ttls) {
-            this.#initializeTTLTracking();
-        }
-        if (this.#ttls) {
-            if (!noUpdateTTL) {
-                this.#setItemTTL(index, ttl, start);
-            }
-            if (status)
-                this.#statusTTL(status, index);
-        }
-        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
-            }
-        }
-        return this;
-    }
-    /**
-     * Evict the least recently used item, returning its value or
-     * `undefined` if cache is empty.
-     */
-    pop() {
-        try {
-            while (this.#size) {
-                const val = this.#valList[this.#head];
-                this.#evict(true);
-                if (this.#isBackgroundFetch(val)) {
-                    if (val.__staleWhileFetching) {
-                        return val.__staleWhileFetching;
+                // 
/

/../ ->

/
+                let dd = 0;
+                while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
+                    const p = parts[dd - 1];
+                    if (p && p !== '.' && p !== '..' && p !== '**') {
+                        didSomething = true;
+                        const needDot = dd === 1 && parts[dd + 1] === '**';
+                        const splin = needDot ? ['.'] : [];
+                        parts.splice(dd - 1, 2, ...splin);
+                        if (parts.length === 0)
+                            parts.push('');
+                        dd -= 2;
                     }
                 }
-                else if (val !== undefined) {
-                    return val;
-                }
             }
-        }
-        finally {
-            if (this.#hasDisposeAfter && this.#disposed) {
-                const dt = this.#disposed;
-                let task;
-                while ((task = dt?.shift())) {
-                    this.#disposeAfter?.(...task);
+        } while (didSomething);
+        return globParts;
+    }
+    // second phase: multi-pattern dedupes
+    // {
/*/,
/

/} ->

/*/
+    // {
/,
/} -> 
/
+    // {
/**/,
/} -> 
/**/
+    //
+    // {
/**/,
/**/

/} ->

/**/
+    // ^-- not valid because ** doens't follow symlinks
+    secondPhasePreProcess(globParts) {
+        for (let i = 0; i < globParts.length - 1; i++) {
+            for (let j = i + 1; j < globParts.length; j++) {
+                const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
+                if (matched) {
+                    globParts[i] = [];
+                    globParts[j] = matched;
+                    break;
                 }
             }
         }
+        return globParts.filter(gs => gs.length);
     }
-    #evict(free) {
-        const head = this.#head;
-        const k = this.#keyList[head];
-        const v = this.#valList[head];
-        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
-            v.__abortController.abort(new Error('evicted'));
-        }
-        else if (this.#hasDispose || this.#hasDisposeAfter) {
-            if (this.#hasDispose) {
-                this.#dispose?.(v, k, 'evict');
+    partsMatch(a, b, emptyGSMatch = false) {
+        let ai = 0;
+        let bi = 0;
+        let result = [];
+        let which = '';
+        while (ai < a.length && bi < b.length) {
+            if (a[ai] === b[bi]) {
+                result.push(which === 'b' ? b[bi] : a[ai]);
+                ai++;
+                bi++;
             }
-            if (this.#hasDisposeAfter) {
-                this.#disposed?.push([v, k, 'evict']);
+            else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
+                result.push(a[ai]);
+                ai++;
             }
-        }
-        this.#removeItemSize(head);
-        // if we aren't about to use the index, then null these out
-        if (free) {
-            this.#keyList[head] = undefined;
-            this.#valList[head] = undefined;
-            this.#free.push(head);
-        }
-        if (this.#size === 1) {
-            this.#head = this.#tail = 0;
-            this.#free.length = 0;
-        }
-        else {
-            this.#head = this.#next[head];
-        }
-        this.#keyMap.delete(k);
-        this.#size--;
-        return 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.
-     *
-     * Check if a key is in the cache, without updating the recency of
-     * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
-     * to `true` in either the options or the constructor.
-     *
-     * Will return `false` if the item is stale, even though it is technically in
-     * the cache. The difference can be determined (if it matters) by using a
-     * `status` argument, and inspecting the `has` field.
-     *
-     * Will not update item age unless
-     * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
-     */
-    has(k, hasOptions = {}) {
-        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
-        const index = this.#keyMap.get(k);
-        if (index !== undefined) {
-            const v = this.#valList[index];
-            if (this.#isBackgroundFetch(v) &&
-                v.__staleWhileFetching === undefined) {
-                return false;
+            else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
+                result.push(b[bi]);
+                bi++;
             }
-            if (!this.#isStale(index)) {
-                if (updateAgeOnHas) {
-                    this.#updateItemAge(index);
-                }
-                if (status) {
-                    status.has = 'hit';
-                    this.#statusTTL(status, index);
-                }
-                return true;
+            else if (a[ai] === '*' &&
+                b[bi] &&
+                (this.options.dot || !b[bi].startsWith('.')) &&
+                b[bi] !== '**') {
+                if (which === 'b')
+                    return false;
+                which = 'a';
+                result.push(a[ai]);
+                ai++;
+                bi++;
             }
-            else if (status) {
-                status.has = 'stale';
-                this.#statusTTL(status, index);
+            else if (b[bi] === '*' &&
+                a[ai] &&
+                (this.options.dot || !a[ai].startsWith('.')) &&
+                a[ai] !== '**') {
+                if (which === 'a')
+                    return false;
+                which = 'b';
+                result.push(b[bi]);
+                ai++;
+                bi++;
+            }
+            else {
+                return false;
             }
         }
-        else if (status) {
-            status.has = 'miss';
-        }
-        return false;
+        // if we fall out of the loop, it means they two are identical
+        // as long as their lengths match
+        return a.length === b.length && result;
     }
-    /**
-     * 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 = {}) {
-        const { allowStale = this.allowStale } = peekOptions;
-        const index = this.#keyMap.get(k);
-        if (index === undefined ||
-            (!allowStale && this.#isStale(index))) {
+    parseNegate() {
+        if (this.nonegate)
             return;
+        const pattern = this.pattern;
+        let negate = false;
+        let negateOffset = 0;
+        for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
+            negate = !negate;
+            negateOffset++;
         }
-        const v = this.#valList[index];
-        // either stale and allowed, or forcing a refresh of non-stale value
-        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
+        if (negateOffset)
+            this.pattern = pattern.slice(negateOffset);
+        this.negate = negate;
     }
-    #backgroundFetch(k, index, options, context) {
-        const v = index === undefined ? undefined : this.#valList[index];
-        if (this.#isBackgroundFetch(v)) {
-            return v;
-        }
-        const ac = new AC();
-        const { signal } = options;
-        // when/if our AC signals, then stop listening to theirs.
-        signal?.addEventListener('abort', () => ac.abort(signal.reason), {
-            signal: ac.signal,
-        });
-        const fetchOpts = {
-            signal: ac.signal,
-            options,
-            context,
-        };
-        const cb = (v, updateCache = false) => {
-            const { aborted } = ac.signal;
-            const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
-            if (options.status) {
-                if (aborted && !updateCache) {
-                    options.status.fetchAborted = true;
-                    options.status.fetchError = ac.signal.reason;
-                    if (ignoreAbort)
-                        options.status.fetchAbortIgnored = true;
-                }
-                else {
-                    options.status.fetchResolved = true;
-                }
-            }
-            if (aborted && !ignoreAbort && !updateCache) {
-                return fetchFail(ac.signal.reason);
-            }
-            // either we didn't abort, and are still here, or we did, and ignored
-            const bf = p;
-            if (this.#valList[index] === p) {
-                if (v === undefined) {
-                    if (bf.__staleWhileFetching) {
-                        this.#valList[index] = bf.__staleWhileFetching;
+    // set partial to true to test if, for example,
+    // "/a/b" matches the start of "/*/b/*/d"
+    // Partial means, if you run out of file before you run
+    // out of pattern, then that's fine, as long as all
+    // the parts match.
+    matchOne(file, pattern, partial = false) {
+        const options = this.options;
+        // UNC paths like //?/X:/... can match X:/... and vice versa
+        // Drive letters in absolute drive or unc paths are always compared
+        // case-insensitively.
+        if (this.isWindows) {
+            const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
+            const fileUNC = !fileDrive &&
+                file[0] === '' &&
+                file[1] === '' &&
+                file[2] === '?' &&
+                /^[a-z]:$/i.test(file[3]);
+            const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
+            const patternUNC = !patternDrive &&
+                pattern[0] === '' &&
+                pattern[1] === '' &&
+                pattern[2] === '?' &&
+                typeof pattern[3] === 'string' &&
+                /^[a-z]:$/i.test(pattern[3]);
+            const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
+            const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
+            if (typeof fdi === 'number' && typeof pdi === 'number') {
+                const [fd, pd] = [file[fdi], pattern[pdi]];
+                if (fd.toLowerCase() === pd.toLowerCase()) {
+                    pattern[pdi] = fd;
+                    if (pdi > fdi) {
+                        pattern = pattern.slice(pdi);
                     }
-                    else {
-                        this.#delete(k, 'fetch');
+                    else if (fdi > pdi) {
+                        file = file.slice(fdi);
                     }
                 }
-                else {
-                    if (options.status)
-                        options.status.fetchUpdated = true;
-                    this.set(k, v, fetchOpts.options);
-                }
-            }
-            return v;
-        };
-        const eb = (er) => {
-            if (options.status) {
-                options.status.fetchRejected = true;
-                options.status.fetchError = er;
-            }
-            return fetchFail(er);
-        };
-        const fetchFail = (er) => {
-            const { aborted } = ac.signal;
-            const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
-            const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
-            const noDelete = allowStale || options.noDeleteOnFetchRejection;
-            const bf = p;
-            if (this.#valList[index] === p) {
-                // if we allow stale on fetch rejections, then we need to ensure that
-                // the stale value is not removed from the cache when the fetch fails.
-                const del = !noDelete || bf.__staleWhileFetching === undefined;
-                if (del) {
-                    this.#delete(k, 'fetch');
-                }
-                else if (!allowStaleAborted) {
-                    // still replace the *promise* with the stale value,
-                    // since we are done with the promise at this point.
-                    // leave it untouched if we're still waiting for an
-                    // aborted background fetch that hasn't yet returned.
-                    this.#valList[index] = bf.__staleWhileFetching;
-                }
-            }
-            if (allowStale) {
-                if (options.status && bf.__staleWhileFetching !== undefined) {
-                    options.status.returnedStale = true;
-                }
-                return bf.__staleWhileFetching;
-            }
-            else if (bf.__returned === bf) {
-                throw er;
-            }
-        };
-        const pcall = (res, rej) => {
-            const fmp = this.#fetchMethod?.(k, v, fetchOpts);
-            if (fmp && fmp instanceof Promise) {
-                fmp.then(v => res(v === undefined ? undefined : v), rej);
             }
-            // ignored, we go until we finish, regardless.
-            // defer check until we are actually aborting,
-            // so fetchMethod can override.
-            ac.signal.addEventListener('abort', () => {
-                if (!options.ignoreFetchAbort ||
-                    options.allowStaleOnFetchAbort) {
-                    res(undefined);
-                    // when it eventually resolves, update the cache.
-                    if (options.allowStaleOnFetchAbort) {
-                        res = v => cb(v, true);
-                    }
-                }
-            });
-        };
-        if (options.status)
-            options.status.fetchDispatched = true;
-        const p = new Promise(pcall).then(cb, eb);
-        const bf = Object.assign(p, {
-            __abortController: ac,
-            __staleWhileFetching: v,
-            __returned: undefined,
-        });
-        if (index === undefined) {
-            // internal, don't expose status.
-            this.set(k, bf, { ...fetchOpts.options, status: undefined });
-            index = this.#keyMap.get(k);
-        }
-        else {
-            this.#valList[index] = bf;
-        }
-        return bf;
-    }
-    #isBackgroundFetch(p) {
-        if (!this.#hasFetchMethod)
-            return false;
-        const b = p;
-        return (!!b &&
-            b instanceof Promise &&
-            b.hasOwnProperty('__staleWhileFetching') &&
-            b.__abortController instanceof AC);
-    }
-    async fetch(k, fetchOptions = {}) {
-        const { 
-        // 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 = false, status, signal, } = fetchOptions;
-        if (!this.#hasFetchMethod) {
-            if (status)
-                status.fetch = 'get';
-            return this.get(k, {
-                allowStale,
-                updateAgeOnGet,
-                noDeleteOnStaleGet,
-                status,
-            });
         }
-        const options = {
-            allowStale,
-            updateAgeOnGet,
-            noDeleteOnStaleGet,
-            ttl,
-            noDisposeOnSet,
-            size,
-            sizeCalculation,
-            noUpdateTTL,
-            noDeleteOnFetchRejection,
-            allowStaleOnFetchRejection,
-            allowStaleOnFetchAbort,
-            ignoreFetchAbort,
-            status,
-            signal,
-        };
-        let index = this.#keyMap.get(k);
-        if (index === undefined) {
-            if (status)
-                status.fetch = 'miss';
-            const p = this.#backgroundFetch(k, index, options, context);
-            return (p.__returned = p);
+        // resolve and reduce . and .. portions in the file as well.
+        // dont' need to do the second phase, because it's only one string[]
+        const { optimizationLevel = 1 } = this.options;
+        if (optimizationLevel >= 2) {
+            file = this.levelTwoFileOptimize(file);
         }
-        else {
-            // in cache, maybe already fetching
-            const v = this.#valList[index];
-            if (this.#isBackgroundFetch(v)) {
-                const stale = allowStale && v.__staleWhileFetching !== undefined;
-                if (status) {
-                    status.fetch = 'inflight';
-                    if (stale)
-                        status.returnedStale = true;
-                }
-                return stale ? v.__staleWhileFetching : (v.__returned = v);
+        this.debug('matchOne', this, { file, pattern });
+        this.debug('matchOne', file.length, pattern.length);
+        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
+            this.debug('matchOne loop');
+            var p = pattern[pi];
+            var f = file[fi];
+            this.debug(pattern, p, f);
+            // should be impossible.
+            // some invalid regexp stuff in the set.
+            /* c8 ignore start */
+            if (p === false) {
+                return false;
             }
-            // if we force a refresh, that means do NOT serve the cached value,
-            // unless we are already in the process of refreshing the cache.
-            const isStale = this.#isStale(index);
-            if (!forceRefresh && !isStale) {
-                if (status)
-                    status.fetch = 'hit';
-                this.#moveToTail(index);
-                if (updateAgeOnGet) {
-                    this.#updateItemAge(index);
+            /* c8 ignore stop */
+            if (p === exports.GLOBSTAR) {
+                this.debug('GLOBSTAR', [pattern, p, f]);
+                // "**"
+                // a/**/b/**/c would match the following:
+                // a/b/x/y/z/c
+                // a/x/y/z/b/c
+                // a/b/x/b/x/c
+                // a/b/c
+                // To do this, take the rest of the pattern after
+                // the **, and see if it would match the file remainder.
+                // If so, return success.
+                // If not, the ** "swallows" a segment, and try again.
+                // This is recursively awful.
+                //
+                // a/**/b/**/c matching a/b/x/y/z/c
+                // - a matches a
+                // - doublestar
+                //   - matchOne(b/x/y/z/c, b/**/c)
+                //     - b matches b
+                //     - doublestar
+                //       - matchOne(x/y/z/c, c) -> no
+                //       - matchOne(y/z/c, c) -> no
+                //       - matchOne(z/c, c) -> no
+                //       - matchOne(c, c) yes, hit
+                var fr = fi;
+                var pr = pi + 1;
+                if (pr === pl) {
+                    this.debug('** at the end');
+                    // a ** at the end will just swallow the rest.
+                    // We have found a match.
+                    // however, it will not swallow /.x, unless
+                    // options.dot is set.
+                    // . and .. are *never* matched by **, for explosively
+                    // exponential reasons.
+                    for (; fi < fl; fi++) {
+                        if (file[fi] === '.' ||
+                            file[fi] === '..' ||
+                            (!options.dot && file[fi].charAt(0) === '.'))
+                            return false;
+                    }
+                    return true;
                 }
-                if (status)
-                    this.#statusTTL(status, index);
-                return v;
-            }
-            // ok, it is stale or a forced refresh, and not already fetching.
-            // refresh the cache.
-            const p = this.#backgroundFetch(k, index, options, context);
-            const hasStale = p.__staleWhileFetching !== undefined;
-            const staleVal = hasStale && allowStale;
-            if (status) {
-                status.fetch = isStale ? 'stale' : 'refresh';
-                if (staleVal && isStale)
-                    status.returnedStale = true;
-            }
-            return staleVal ? p.__staleWhileFetching : (p.__returned = p);
-        }
-    }
-    async forceFetch(k, fetchOptions = {}) {
-        const v = await this.fetch(k, fetchOptions);
-        if (v === undefined)
-            throw new Error('fetch() returned undefined');
-        return v;
-    }
-    memo(k, memoOptions = {}) {
-        const memoMethod = this.#memoMethod;
-        if (!memoMethod) {
-            throw new Error('no memoMethod provided to constructor');
-        }
-        const { context, forceRefresh, ...options } = memoOptions;
-        const v = this.get(k, options);
-        if (!forceRefresh && v !== undefined)
-            return v;
-        const vv = memoMethod(k, v, {
-            options,
-            context,
-        });
-        this.set(k, vv, options);
-        return vv;
-    }
-    /**
-     * 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 = {}) {
-        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
-        const index = this.#keyMap.get(k);
-        if (index !== undefined) {
-            const value = this.#valList[index];
-            const fetching = this.#isBackgroundFetch(value);
-            if (status)
-                this.#statusTTL(status, index);
-            if (this.#isStale(index)) {
-                if (status)
-                    status.get = 'stale';
-                // delete only if not an in-flight background fetch
-                if (!fetching) {
-                    if (!noDeleteOnStaleGet) {
-                        this.#delete(k, 'expire');
+                // ok, let's see if we can swallow whatever we can.
+                while (fr < fl) {
+                    var swallowee = file[fr];
+                    this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
+                    // XXX remove this slice.  Just pass the start index.
+                    if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
+                        this.debug('globstar found match!', fr, fl, swallowee);
+                        // found a match.
+                        return true;
+                    }
+                    else {
+                        // can't swallow "." or ".." ever.
+                        // can only swallow ".foo" when explicitly asked.
+                        if (swallowee === '.' ||
+                            swallowee === '..' ||
+                            (!options.dot && swallowee.charAt(0) === '.')) {
+                            this.debug('dot detected!', file, fr, pattern, pr);
+                            break;
+                        }
+                        // ** swallows a segment, and continue.
+                        this.debug('globstar swallow a segment, and continue');
+                        fr++;
                     }
-                    if (status && allowStale)
-                        status.returnedStale = true;
-                    return allowStale ? value : undefined;
                 }
-                else {
-                    if (status &&
-                        allowStale &&
-                        value.__staleWhileFetching !== undefined) {
-                        status.returnedStale = true;
+                // no match was found.
+                // However, in partial mode, we can't say this is necessarily over.
+                /* c8 ignore start */
+                if (partial) {
+                    // ran out of file
+                    this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
+                    if (fr === fl) {
+                        return true;
                     }
-                    return allowStale ? value.__staleWhileFetching : undefined;
                 }
+                /* c8 ignore stop */
+                return false;
+            }
+            // something other than **
+            // non-magic patterns just have to match exactly
+            // patterns with magic have been turned into regexps.
+            let hit;
+            if (typeof p === 'string') {
+                hit = f === p;
+                this.debug('string match', p, f, hit);
             }
             else {
-                if (status)
-                    status.get = 'hit';
-                // if we're currently fetching it, we don't actually have it yet
-                // it's not stale, which means this isn't a staleWhileRefetching.
-                // If it's not stale, and fetching, AND has a __staleWhileFetching
-                // value, then that means the user fetched with {forceRefresh:true},
-                // so it's safe to return that value.
-                if (fetching) {
-                    return value.__staleWhileFetching;
-                }
-                this.#moveToTail(index);
-                if (updateAgeOnGet) {
-                    this.#updateItemAge(index);
-                }
-                return value;
+                hit = p.test(f);
+                this.debug('pattern match', p, f, hit);
             }
+            if (!hit)
+                return false;
         }
-        else if (status) {
-            status.get = 'miss';
+        // Note: ending in / means that we'll get a final ""
+        // at the end of the pattern.  This can only match a
+        // corresponding "" at the end of the file.
+        // If the file ends in /, then it can only match a
+        // a pattern that ends in /, unless the pattern just
+        // doesn't have any more for it. But, a/b/ should *not*
+        // match "a/b/*", even though "" matches against the
+        // [^/]*? pattern, except in partial mode, where it might
+        // simply not be reached yet.
+        // However, a/b/ should still satisfy a/*
+        // now either we fell off the end of the pattern, or we're done.
+        if (fi === fl && pi === pl) {
+            // ran out of pattern and filename at the same time.
+            // an exact hit!
+            return true;
+        }
+        else if (fi === fl) {
+            // ran out of file, but still had pattern left.
+            // this is ok if we're doing the match as part of
+            // a glob fs traversal.
+            return partial;
+        }
+        else if (pi === pl) {
+            // ran out of pattern, still have file left.
+            // this is only acceptable if we're on the very last
+            // empty segment of a file with a trailing slash.
+            // a/* should match a/b/
+            return fi === fl - 1 && file[fi] === '';
+            /* c8 ignore start */
+        }
+        else {
+            // should be unreachable.
+            throw new Error('wtf?');
         }
+        /* c8 ignore stop */
     }
-    #connect(p, n) {
-        this.#prev[n] = p;
-        this.#next[p] = n;
+    braceExpand() {
+        return (0, exports.braceExpand)(this.pattern, this.options);
     }
-    #moveToTail(index) {
-        // if tail already, nothing to do
-        // if head, move head to next[index]
-        // else
-        //   move next[prev[index]] to next[index] (head has no prev)
-        //   move prev[next[index]] to prev[index]
-        // prev[index] = tail
-        // next[tail] = index
-        // tail = index
-        if (index !== this.#tail) {
-            if (index === this.#head) {
-                this.#head = this.#next[index];
-            }
-            else {
-                this.#connect(this.#prev[index], this.#next[index]);
-            }
-            this.#connect(this.#tail, index);
-            this.#tail = index;
+    parse(pattern) {
+        (0, assert_valid_pattern_js_1.assertValidPattern)(pattern);
+        const options = this.options;
+        // shortcuts
+        if (pattern === '**')
+            return exports.GLOBSTAR;
+        if (pattern === '')
+            return '';
+        // far and away, the most common glob pattern parts are
+        // *, *.*, and *.  Add a fast check method for those.
+        let m;
+        let fastTest = null;
+        if ((m = pattern.match(starRE))) {
+            fastTest = options.dot ? starTestDot : starTest;
         }
+        else if ((m = pattern.match(starDotExtRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? starDotExtTestNocaseDot
+                    : starDotExtTestNocase
+                : options.dot
+                    ? starDotExtTestDot
+                    : starDotExtTest)(m[1]);
+        }
+        else if ((m = pattern.match(qmarksRE))) {
+            fastTest = (options.nocase
+                ? options.dot
+                    ? qmarksTestNocaseDot
+                    : qmarksTestNocase
+                : options.dot
+                    ? qmarksTestDot
+                    : qmarksTest)(m);
+        }
+        else if ((m = pattern.match(starDotStarRE))) {
+            fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
+        }
+        else if ((m = pattern.match(dotStarRE))) {
+            fastTest = dotStarTest;
+        }
+        const re = ast_js_1.AST.fromGlob(pattern, this.options).toMMPattern();
+        if (fastTest && typeof re === 'object') {
+            // Avoids overriding in frozen environments
+            Reflect.defineProperty(re, 'test', { value: fastTest });
+        }
+        return re;
     }
-    /**
-     * Deletes a key out of the cache.
-     *
-     * Returns true if the key was deleted, false otherwise.
-     */
-    delete(k) {
-        return this.#delete(k, 'delete');
-    }
-    #delete(k, reason) {
-        let deleted = false;
-        if (this.#size !== 0) {
-            const index = this.#keyMap.get(k);
-            if (index !== undefined) {
-                deleted = true;
-                if (this.#size === 1) {
-                    this.#clear(reason);
+    makeRe() {
+        if (this.regexp || this.regexp === false)
+            return this.regexp;
+        // at this point, this.set is a 2d array of partial
+        // pattern strings, or "**".
+        //
+        // It's better to use .match().  This function shouldn't
+        // be used, really, but it's pretty convenient sometimes,
+        // when you just want to work with a regex.
+        const set = this.set;
+        if (!set.length) {
+            this.regexp = false;
+            return this.regexp;
+        }
+        const options = this.options;
+        const twoStar = options.noglobstar
+            ? star
+            : options.dot
+                ? twoStarDot
+                : twoStarNoDot;
+        const flags = new Set(options.nocase ? ['i'] : []);
+        // regexpify non-globstar patterns
+        // if ** is only item, then we just do one twoStar
+        // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
+        // if ** is last, append (\/twoStar|) to previous
+        // if ** is in the middle, append (\/|\/twoStar\/) to previous
+        // then filter out GLOBSTAR symbols
+        let re = set
+            .map(pattern => {
+            const pp = pattern.map(p => {
+                if (p instanceof RegExp) {
+                    for (const f of p.flags.split(''))
+                        flags.add(f);
                 }
-                else {
-                    this.#removeItemSize(index);
-                    const v = this.#valList[index];
-                    if (this.#isBackgroundFetch(v)) {
-                        v.__abortController.abort(new Error('deleted'));
-                    }
-                    else if (this.#hasDispose || this.#hasDisposeAfter) {
-                        if (this.#hasDispose) {
-                            this.#dispose?.(v, k, reason);
-                        }
-                        if (this.#hasDisposeAfter) {
-                            this.#disposed?.push([v, k, reason]);
-                        }
-                    }
-                    this.#keyMap.delete(k);
-                    this.#keyList[index] = undefined;
-                    this.#valList[index] = undefined;
-                    if (index === this.#tail) {
-                        this.#tail = this.#prev[index];
-                    }
-                    else if (index === this.#head) {
-                        this.#head = this.#next[index];
+                return typeof p === 'string'
+                    ? regExpEscape(p)
+                    : p === exports.GLOBSTAR
+                        ? exports.GLOBSTAR
+                        : p._src;
+            });
+            pp.forEach((p, i) => {
+                const next = pp[i + 1];
+                const prev = pp[i - 1];
+                if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) {
+                    return;
+                }
+                if (prev === undefined) {
+                    if (next !== undefined && next !== exports.GLOBSTAR) {
+                        pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
                     }
                     else {
-                        const pi = this.#prev[index];
-                        this.#next[pi] = this.#next[index];
-                        const ni = this.#next[index];
-                        this.#prev[ni] = this.#prev[index];
+                        pp[i] = twoStar;
                     }
-                    this.#size--;
-                    this.#free.push(index);
                 }
-            }
+                else if (next === undefined) {
+                    pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
+                }
+                else if (next !== exports.GLOBSTAR) {
+                    pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
+                    pp[i + 1] = exports.GLOBSTAR;
+                }
+            });
+            return pp.filter(p => p !== exports.GLOBSTAR).join('/');
+        })
+            .join('|');
+        // need to wrap in parens if we had more than one thing with |,
+        // otherwise only the first will be anchored to ^ and the last to $
+        const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
+        // must match entire pattern
+        // ending in a * or ** will make it less strict.
+        re = '^' + open + re + close + '$';
+        // can match anything, as long as it's not this.
+        if (this.negate)
+            re = '^(?!' + re + ').+$';
+        try {
+            this.regexp = new RegExp(re, [...flags].join(''));
+            /* c8 ignore start */
         }
-        if (this.#hasDisposeAfter && this.#disposed?.length) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
-            }
+        catch (ex) {
+            // should be impossible
+            this.regexp = false;
         }
-        return deleted;
+        /* c8 ignore stop */
+        return this.regexp;
     }
-    /**
-     * Clear the cache entirely, throwing away all values.
-     */
-    clear() {
-        return this.#clear('delete');
+    slashSplit(p) {
+        // if p starts with // on windows, we preserve that
+        // so that UNC paths aren't broken.  Otherwise, any number of
+        // / characters are coalesced into one, unless
+        // preserveMultipleSlashes is set to true.
+        if (this.preserveMultipleSlashes) {
+            return p.split('/');
+        }
+        else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
+            // add an extra '' for the one we lose
+            return ['', ...p.split(/\/+/)];
+        }
+        else {
+            return p.split(/\/+/);
+        }
     }
-    #clear(reason) {
-        for (const index of this.#rindexes({ allowStale: true })) {
-            const v = this.#valList[index];
-            if (this.#isBackgroundFetch(v)) {
-                v.__abortController.abort(new Error('deleted'));
-            }
-            else {
-                const k = this.#keyList[index];
-                if (this.#hasDispose) {
-                    this.#dispose?.(v, k, reason);
-                }
-                if (this.#hasDisposeAfter) {
-                    this.#disposed?.push([v, k, reason]);
-                }
-            }
+    match(f, partial = this.partial) {
+        this.debug('match', f, this.pattern);
+        // short-circuit in the case of busted things.
+        // comments, etc.
+        if (this.comment) {
+            return false;
         }
-        this.#keyMap.clear();
-        this.#valList.fill(undefined);
-        this.#keyList.fill(undefined);
-        if (this.#ttls && this.#starts) {
-            this.#ttls.fill(0);
-            this.#starts.fill(0);
+        if (this.empty) {
+            return f === '';
         }
-        if (this.#sizes) {
-            this.#sizes.fill(0);
+        if (f === '/' && partial) {
+            return true;
         }
-        this.#head = 0;
-        this.#tail = 0;
-        this.#free.length = 0;
-        this.#calculatedSize = 0;
-        this.#size = 0;
-        if (this.#hasDisposeAfter && this.#disposed) {
-            const dt = this.#disposed;
-            let task;
-            while ((task = dt?.shift())) {
-                this.#disposeAfter?.(...task);
+        const options = this.options;
+        // windows: need to use /, not \
+        if (this.isWindows) {
+            f = f.split('\\').join('/');
+        }
+        // treat the test path as a set of pathparts.
+        const ff = this.slashSplit(f);
+        this.debug(this.pattern, 'split', ff);
+        // just ONE of the pattern sets in this.set needs to match
+        // in order for it to be valid.  If negating, then just one
+        // match means that we have failed.
+        // Either way, return on the first hit.
+        const set = this.set;
+        this.debug(this.pattern, 'set', set);
+        // Find the basename of the path by looking for the last non-empty segment
+        let filename = ff[ff.length - 1];
+        if (!filename) {
+            for (let i = ff.length - 2; !filename && i >= 0; i--) {
+                filename = ff[i];
             }
         }
+        for (let i = 0; i < set.length; i++) {
+            const pattern = set[i];
+            let file = ff;
+            if (options.matchBase && pattern.length === 1) {
+                file = [filename];
+            }
+            const hit = this.matchOne(file, pattern, partial);
+            if (hit) {
+                if (options.flipNegate) {
+                    return true;
+                }
+                return !this.negate;
+            }
+        }
+        // didn't get any hits.  this is success if it's a negative
+        // pattern, failure otherwise.
+        if (options.flipNegate) {
+            return false;
+        }
+        return this.negate;
+    }
+    static defaults(def) {
+        return exports.minimatch.defaults(def).Minimatch;
     }
 }
-exports.LRUCache = LRUCache;
+exports.Minimatch = Minimatch;
+/* c8 ignore start */
+var ast_js_2 = __nccwpck_require__(6215);
+Object.defineProperty(exports, "AST", ({ enumerable: true, get: function () { return ast_js_2.AST; } }));
+var escape_js_2 = __nccwpck_require__(96076);
+Object.defineProperty(exports, "escape", ({ enumerable: true, get: function () { return escape_js_2.escape; } }));
+var unescape_js_2 = __nccwpck_require__(18047);
+Object.defineProperty(exports, "unescape", ({ enumerable: true, get: function () { return unescape_js_2.unescape; } }));
+/* c8 ignore stop */
+exports.minimatch.AST = ast_js_1.AST;
+exports.minimatch.Minimatch = Minimatch;
+exports.minimatch.escape = escape_js_1.escape;
+exports.minimatch.unescape = unescape_js_1.unescape;
 //# sourceMappingURL=index.js.map
 
 /***/ }),
 
+/***/ 18047:
+/***/ ((__unused_webpack_module, exports) => {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.unescape = void 0;
+/**
+ * Un-escape a string that has been escaped with {@link escape}.
+ *
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
+ * escapes are removed, but not backslash escapes.  For example, it will turn
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
+ *
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
+ * backslash escapes are removed.
+ *
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
+ * or unescaped.
+ */
+const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
+    return windowsPathsNoEscape
+        ? s.replace(/\[([^\/\\])\]/g, '$1')
+        : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
+};
+exports.unescape = unescape;
+//# sourceMappingURL=unescape.js.map
+
+/***/ }),
+
 /***/ 78275:
 /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
 

From c85ef89b80a872d84e565ff463405ef686ae30d1 Mon Sep 17 00:00:00 2001
From: Adam Turner <9087854+aa-turner@users.noreply.github.com>
Date: Sat, 1 Mar 2025 02:19:34 +0000
Subject: [PATCH 3/7] Inline createAttestation wrapper functions

---
 src/attest.ts | 11 +++++-----
 src/main.ts   | 56 ++++++++++++++-------------------------------------
 2 files changed, 20 insertions(+), 47 deletions(-)

diff --git a/src/attest.ts b/src/attest.ts
index 7e5edb8aa..b6b930d86 100644
--- a/src/attest.ts
+++ b/src/attest.ts
@@ -6,11 +6,6 @@ const OCI_TIMEOUT = 30000
 const OCI_RETRY = 3
 
 export type SigstoreInstance = 'public-good' | 'github'
-export type CreateAttestationOptions = {
-  sigstoreInstance: SigstoreInstance
-  pushToRegistry: boolean
-  githubToken: string
-}
 export type AttestResult = Attestation & {
   attestationDigest?: string
   attestationSubjects: Subject[]
@@ -19,7 +14,11 @@ export type AttestResult = Attestation & {
 export const createAttestation = async (
   subjects: Subject[],
   predicate: Predicate,
-  opts: CreateAttestationOptions
+  opts: {
+    sigstoreInstance: SigstoreInstance
+    pushToRegistry: boolean
+    githubToken: string
+  }
 ): Promise => {
   // Sign provenance w/ Sigstore
   const attestation: Attestation = await attest({
diff --git a/src/main.ts b/src/main.ts
index 9a56b0602..2364490b7 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -3,12 +3,7 @@ import * as github from '@actions/github'
 import fs from 'fs'
 import os from 'os'
 import path from 'path'
-import {
-  AttestResult,
-  SigstoreInstance,
-  createAttestation,
-  CreateAttestationOptions
-} from './attest'
+import { AttestResult, SigstoreInstance, createAttestation } from './attest'
 import { SEARCH_PUBLIC_GOOD_URL } from './endpoints'
 import { PredicateInputs, predicateFromInputs } from './predicate'
 import * as style from './style'
@@ -18,8 +13,6 @@ import {
   subjectFromInputs
 } from './subject'
 
-import type { Predicate, Subject } from '@actions/attest'
-
 const ATTESTATION_FILE_NAME = 'attestation.json'
 
 export type RunInputs = SubjectInputs &
@@ -72,17 +65,22 @@ export async function run(inputs: RunInputs): Promise {
     const outputPath = path.join(tempDir(), ATTESTATION_FILE_NAME)
     core.setOutput('bundle-path', outputPath)
 
-    const opts: CreateAttestationOptions = {
+    const opts = {
       sigstoreInstance,
       pushToRegistry: inputs.pushToRegistry,
       githubToken: inputs.githubToken
     }
 
-    let atts: AttestResult[]
+    const atts: AttestResult[] = []
     if (inputs.singleSubjectAttestations) {
-      atts = await createSingleSubjectAttestations(subjects, predicate, opts)
+      // Generate one attestation for each subject
+      for (const subject of subjects) {
+        const att = await createAttestation([subject], predicate, opts)
+        atts.push(att)
+      }
     } else {
-      atts = await createMultiSubjectAttestation(subjects, predicate, opts)
+      const att = await createAttestation(subjects, predicate, opts)
+      atts.push(att)
     }
 
     for (const att of atts) {
@@ -95,6 +93,11 @@ export async function run(inputs: RunInputs): Promise {
       })
     }
 
+    if (atts[0].attestationID) {
+      core.setOutput('attestation-id', atts[0].attestationID)
+      core.setOutput('attestation-url', attestationURL(atts[0].attestationID))
+    }
+
     if (inputs.showSummary) {
       await logSummary(atts)
     }
@@ -119,35 +122,6 @@ export async function run(inputs: RunInputs): Promise {
   }
 }
 
-const createSingleSubjectAttestations = async (
-  subjects: Subject[],
-  predicate: Predicate,
-  opts: CreateAttestationOptions
-): Promise => {
-  const atts: AttestResult[] = []
-  // Generate one attestation for each subject
-  for (const subject of subjects) {
-    const att = await createAttestation([subject], predicate, opts)
-    atts.push(att)
-  }
-  return atts
-}
-
-const createMultiSubjectAttestation = async (
-  subjects: Subject[],
-  predicate: Predicate,
-  opts: CreateAttestationOptions
-): Promise => {
-  const att = await createAttestation(subjects, predicate, opts)
-
-  if (att.attestationID) {
-    core.setOutput('attestation-id', att.attestationID)
-    core.setOutput('attestation-url', attestationURL(att.attestationID))
-  }
-
-  return [att]
-}
-
 // Log details about the attestation to the GitHub Actions run
 const logAttestation = (
   attestation: AttestResult,

From 6d832e666b0fd580dd532f8326ad8897fede80b1 Mon Sep 17 00:00:00 2001
From: Adam Turner <9087854+aa-turner@users.noreply.github.com>
Date: Sat, 1 Mar 2025 02:39:37 +0000
Subject: [PATCH 4/7] Improve documentation/wording

---
 README.md  | 7 +++++--
 action.yml | 4 +---
 2 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/README.md b/README.md
index 233a99308..f64413c1c 100644
--- a/README.md
+++ b/README.md
@@ -137,8 +137,11 @@ Attestations are saved in the JSON-serialized [Sigstore bundle][6] format.
 
 If multiple subjects are being attested at the same time, a single attestation
 will be created with references to each of the supplied subjects.
-If `single-subject-attestations` is true, each attestation will be written
-to the output file on  a separate line (using the [JSON Lines][7] format).
+
+If the `single-subject-attestations` option has been set to true,
+one attestation will be generated per provided subject.
+All of these attestations will be written to the output file,
+using the [JSON Lines][7] format (one attestation per line).
 
 ## Attestation Limits
 
diff --git a/action.yml b/action.yml
index 0ccd203a9..e9ee1c20f 100644
--- a/action.yml
+++ b/action.yml
@@ -66,9 +66,7 @@ inputs:
     required: false
   single-subject-attestations:
     description: >
-      If true, generate one attestation per subject, 
-      otherwise generate a single attestations with multiple subjects.
-      Defaults to false.
+      If true, generate one attestation per subject. Defaults to false.
     default: false
     required: false
 outputs:

From 967e74874778a7e5593d6c611e6b9f46b115cdee Mon Sep 17 00:00:00 2001
From: Adam Turner <9087854+aa-turner@users.noreply.github.com>
Date: Sat, 1 Mar 2025 02:40:59 +0000
Subject: [PATCH 5/7] Remove attestationSubjects from logSummary

---
 src/main.ts | 33 ++++++++++++++-------------------
 1 file changed, 14 insertions(+), 19 deletions(-)

diff --git a/src/main.ts b/src/main.ts
index 2364490b7..bd09d0d8a 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -168,27 +168,22 @@ const logAttestation = (
 
 // Attach summary information to the GitHub Actions run
 const logSummary = async (attestations: AttestResult[]): Promise => {
-  if (attestations.length > 0) {
-    core.summary.addHeading(
-      /* istanbul ignore next */
-      attestations.length !== 1
-        ? 'Attestations Created'
-        : 'Attestation Created',
-      3
-    )
-    const listItems: string[] = []
-    for (const attestation of attestations) {
-      if (attestation.attestationID) {
-        const url = attestationURL(attestation.attestationID)
-        for (const subject of attestation.attestationSubjects) {
-          const digest = formatSubjectDigest(subject)
-          listItems.push(`${subject.name}@${digest}`)
-        }
-      }
+  if (attestations.length <= 0) return
+
+  core.summary.addHeading(
+    /* istanbul ignore next */
+    attestations.length !== 1 ? 'Attestations Created' : 'Attestation Created',
+    3
+  )
+  const listItems: string[] = []
+  for (const { attestationID } of attestations) {
+    if (attestationID) {
+      const url = attestationURL(attestationID)
+      listItems.push(`${url}`)
     }
-    core.summary.addList(listItems)
-    await core.summary.write()
   }
+  core.summary.addList(listItems)
+  await core.summary.write()
 }
 
 const tempDir = (): string => {

From 7d6949838a129dbebfb4614731f344fecf95a99a Mon Sep 17 00:00:00 2001
From: Adam Turner <9087854+aa-turner@users.noreply.github.com>
Date: Sat, 1 Mar 2025 02:41:59 +0000
Subject: [PATCH 6/7] Remove attestationSubjects

---
 src/attest.ts | 6 +-----
 src/main.ts   | 6 ++++--
 2 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/src/attest.ts b/src/attest.ts
index b6b930d86..4db3cd1be 100644
--- a/src/attest.ts
+++ b/src/attest.ts
@@ -8,7 +8,6 @@ const OCI_RETRY = 3
 export type SigstoreInstance = 'public-good' | 'github'
 export type AttestResult = Attestation & {
   attestationDigest?: string
-  attestationSubjects: Subject[]
 }
 
 export const createAttestation = async (
@@ -29,10 +28,7 @@ export const createAttestation = async (
     token: opts.githubToken
   })
 
-  const result: AttestResult = {
-    ...attestation,
-    attestationSubjects: subjects
-  }
+  const result: AttestResult = attestation
 
   if (subjects.length === 1 && opts.pushToRegistry) {
     const subject = subjects[0]
diff --git a/src/main.ts b/src/main.ts
index bd09d0d8a..0a51137bb 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -13,6 +13,8 @@ import {
   subjectFromInputs
 } from './subject'
 
+import type { Subject } from '@actions/attest'
+
 const ATTESTATION_FILE_NAME = 'attestation.json'
 
 export type RunInputs = SubjectInputs &
@@ -84,7 +86,7 @@ export async function run(inputs: RunInputs): Promise {
     }
 
     for (const att of atts) {
-      logAttestation(att, sigstoreInstance)
+      logAttestation(subjects, att, sigstoreInstance)
 
       // Write attestation bundle to output file
       fs.writeFileSync(outputPath, JSON.stringify(att.bundle) + os.EOL, {
@@ -124,10 +126,10 @@ export async function run(inputs: RunInputs): Promise {
 
 // Log details about the attestation to the GitHub Actions run
 const logAttestation = (
+  subjects: Subject[],
   attestation: AttestResult,
   sigstoreInstance: SigstoreInstance
 ): void => {
-  const subjects = attestation.attestationSubjects
   if (subjects.length === 1) {
     core.info(
       `Attestation created for ${subjects[0].name}@${formatSubjectDigest(subjects[0])}`

From 0b37d8a45b0b35c3e729d5a4c91a946f6b77792b Mon Sep 17 00:00:00 2001
From: Adam Turner <9087854+aa-turner@users.noreply.github.com>
Date: Tue, 4 Mar 2025 16:45:49 +0000
Subject: [PATCH 7/7] Introduce ``logSubjects()``

---
 src/main.ts | 23 +++++++++++++----------
 1 file changed, 13 insertions(+), 10 deletions(-)

diff --git a/src/main.ts b/src/main.ts
index 0a51137bb..ed42872be 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -86,7 +86,7 @@ export async function run(inputs: RunInputs): Promise {
     }
 
     for (const att of atts) {
-      logAttestation(subjects, att, sigstoreInstance)
+      logAttestation(att, sigstoreInstance)
 
       // Write attestation bundle to output file
       fs.writeFileSync(outputPath, JSON.stringify(att.bundle) + os.EOL, {
@@ -95,6 +95,8 @@ export async function run(inputs: RunInputs): Promise {
       })
     }
 
+    logSubjects(subjects)
+
     if (atts[0].attestationID) {
       core.setOutput('attestation-id', atts[0].attestationID)
       core.setOutput('attestation-url', attestationURL(atts[0].attestationID))
@@ -126,18 +128,9 @@ export async function run(inputs: RunInputs): Promise {
 
 // Log details about the attestation to the GitHub Actions run
 const logAttestation = (
-  subjects: Subject[],
   attestation: AttestResult,
   sigstoreInstance: SigstoreInstance
 ): void => {
-  if (subjects.length === 1) {
-    core.info(
-      `Attestation created for ${subjects[0].name}@${formatSubjectDigest(subjects[0])}`
-    )
-  } else {
-    core.info(`Attestation created for ${subjects.length} subjects`)
-  }
-
   const instanceName =
     sigstoreInstance === 'public-good' ? 'Public Good' : 'GitHub'
   core.startGroup(
@@ -168,6 +161,16 @@ const logAttestation = (
   }
 }
 
+// Log details about attestation subjects to the GitHub Actions run
+const logSubjects = (subjects: Subject[]): void => {
+  core.info(`Attestation created for ${subjects.length} subjects`)
+  for (const subject of subjects) {
+    core.info(
+      `Attestation created for ${subject.name}@${formatSubjectDigest(subject)}`
+    )
+  }
+}
+
 // Attach summary information to the GitHub Actions run
 const logSummary = async (attestations: AttestResult[]): Promise => {
   if (attestations.length <= 0) return